Basically, this isn't recursion but just overloading methods being called from each other, which is a valid approach targeting the problem.

But nevertheless, you could do better.

Naming

Based on the naming guidelines method parameters should be nameed using camelCase casing.
If you have own naming guidelines you for sure should stick to them.

Abbreviations for naming variables like loFound doesn't tell anything at all. You should name your variable as meaningful as possible. In that way Sam the maintainer won't have a hard time evaluating the purpose of the variable. That being said, I would have expected a name like foundTable inside a method named GetTable().
Scope

You should declare your variables as near as possible to their usage. It does not help readability if you declare them at the top of the method if you use them way down the method.
Using the right type

It doesn't make sense to use a List<T> to collect items and then calling ToArray() because the method to be called takes an array as parameter, at least if you can change it.

I would like to suggest changing the parameter to IEnumerable<T> because you are only iterating over the array which can be done in the same way with an IEnumerable<T> and much better, if you want to pass an array, a List<T> or a ICollection<T> you can still do it.

You should always try to code against interfaces and not against a concrete implementation.
Spacing

By adding vertical space to logicaly related code your code will improve readability.

So let us take a look at this

Public Overloads Function GetTable(ByVal SearchName As String, ByVal SearchBooks() As Workbook, Optional ByVal ExactMatch As Boolean = False) As ListObject
   Dim loFound As ListObject
   Dim wsList As New List(Of Worksheet)
   Try
       For Each wb In SearchBooks
           For Each ws In wb.Worksheets
               wsList.Add(ws)
           Next
           loFound = Me.GetTable(SearchName:=SearchName, SearchSheets:=wsList.ToArray, ExactMatch:=ExactMatch)
           If Not loFound Is Nothing Then Return loFound
       Next
   Catch ex As Exception
       MessageBox.Show(ex.ToString)
   End Try
   Return Nothing
End Function

The List<T> class has a method AddRange() to add a range of objects. This would improve the method regarding performance.

But you would gain lot more performance if you would declare the List<T> just inside the outer loop. Why do you add all of the WorkSheets but never clear the List ? You will iterate over the whole list each time the searched item isn't found.

So let us do this right. Because the Sheets interface implements IEnumerable we can use the overloaded constructor of List<T> and pass the IEnumerable like so

Public Overloads Function GetTable(ByVal searchName As String, ByVal searchBooks As IEnumerable(Of Workbook), Optional ByVal exactMatch As Boolean = False) As ListObject()

    Try
        For Each wb In searchBooks
            Dim sheets As New List(Of Worksheet)(wb.Sheets.OfType(Of Worksheet))

            Dim foundTable As ListObject = Me.GetTable(searchName:=searchName, searchSheets:=sheets, exactMatch:=exactMatch)
            If Not foundTable Is Nothing Then Return foundTable

        Next
    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try
    Return Nothing
End Function


Double LinkedList Deep Copy in Kotlin with Generics and Thread Safety

I'm not going to touch on your question on thread safety as it is a broad topic I am not familiar with. However, I can help with your questions about generics.
Right now, you're using generics great, except in one single place
node.data = 0 as T

The type of node.data is T. This code will fail if T is not Int - for example, if T is String, the code will look like this:
node.data = 0 as String

and that will throw a runtime exception.
Here's the important thing, though. There's no reason to do node.data = <anything>.
I assume the reason for having it originally was to "zero out" or get rid of the data as it's removed from the list - but that's what java will do for you automatically!
Let's say you have the following structure
linked list    /--> node 1   /--> value 1
-----------    |    ------   |    --------
first node ---/     data ---/        7

when you delete the pointer to node 1, you end up in this situation
linked list         node 1   /--> value 1
-----------         ------   |    --------
first node->null    data ---/        7

now that there is no reference anywhere to node 1, the jvm garbage collector deletes it
linked list         value 1
-----------         ------
first node->null        7

and because there is no reference to value 1, it's also deallocated.
This means that there's no reason to set the data field to anything - and, besides the point, there is no possible value you could set it to that would work for any value of T (in java, though, you could use null)


Plot daily time spent on codereview.stackexchange.com

Here is how I would rewrite your code. I will add my comments after:

plotActivity <- function(
   activity  = 'codereview.stackexchange.com',
   api_key   = getOption('rescuetime_api_key'),
   from_date = NULL,
   to_date   = NULL) {

## This function plots time spent on a given URL
## using the rescue time API
##
## Arguments:
##    - activity:  the url you want to check for usage
##    - api_key:   user API key, you can get yours at
##                 https://www.rescuetime.com/anapi/manage
##    - from_date: a Date or string in "YYYY-MM-DD" format,
##                 defaults to January 1st of the same year as to_date
##    - to_date:   a Date or string in "YYYY-MM-DD" format,
##                 defaults to today
##    - verbose:   adds verbose, defaults to FALSE

   library("RCurl")
   library("ggplot2")

   # arguments parsing and default settings
   if (is.null(api_key)) stop("please set your rescue time API key...")

   if (is.null(to_date)) to_date <- Sys.Date()
   to_date <- as.Date(to_date)
   if (is.na(to_date)) stop("error parsing to_date...")

   if (is.null(from_date)) from_date <- format(to_date, "%Y-01-01")
   from_date <- as.Date(from_date)
   if (is.na(from_date)) stop("error parsing from_date...")

   # build the API request url
   # for more details see https://www.rescuetime.com/anapi/setup/documentation

   base_url  <- "https://www.rescuetime.com/anapi/data"
   arguments <- c(key = api_key,   # API key
                  format = 'csv',  # Output format
                  rb = from_date,  # Restrict Start Date
                  re = end_date,   # Restrict End Date
                  rk = 'activity', # Restrict Kind
                  pv = 'interval', # Perspective
                  rs = 'day',      # Resolution Time
                  rt = activity)   # Restrict Thingy (Restrict Kind of Type)

   arg_str <- paste(names(arguments), arguments, sep = '=', collapse = '&')
   api_url <- sprintf("%s?%s", base_url, arg_str)

   # read data
   csv_text_data <- textConnection(getURL(api_url))
   activity_data <- read.csv(csv_text_data, header = TRUE)

   # print diagnostic and plot
   cat(sprintf("Total Time Spent between %s and %s on '%s':%f (seconds)",
               activity, from_date, end_date, sum(activity_data$Time)))

   activity_data$Date <- as.Date(activity_data$Date)
   ggplot(activity_data, aes(x=Date, y=Time.Spent..seconds.)) +
      geom_bar(stat="identity") +
      xlab("Date") +
      ylab("Time (seconds)")
}

So here are a few ideas:

I went from a script to a function. This way it is a lot easier to use and share. I have abstracted what I believe were all the right inputs and chosen sensible defaults. Of interest is the use of getOption for the api_key so the user can set it once for all by running options(rescuetime_api_key = "xyz123abc"). So now, all you have to do is source the file where this function will be stored, then call the function. A function, when executed, runs in its own environment so all the variables that are created at runtime are deleted as you exit the function. Your global environment is never polluted, which removes the need for your "clean up" section (which was otherwise pretty harmful as janos pointed out.)
Like rm(list=ls()), forcing the install of packages via install.packages() is a bit harmful. No, you just want to use library and it will die right there, leaving the user with the decision of installing the package. There is a nice blog about why some people -me included- prefer library over require: http://yihui.name/en/2014/07/library-vs-require
I made use of R's Date object wherever it made sense.
I rewrote the way the api url is built, making use of a named vector for the arguments. With inline comments. I hope you'll agree the code is a bit more readable and easier to maintain, something you should always aim for.
I replaced print with cat. This way you don't get the [1] prefix that comes with printing a vector.
This has less to do with code reviewing but I thought that it would be more useful to see the total time spent on the website. Average time spent per day can be a little confusing: the user might be wondering if it is including all days or only those when the website was visited (you chose the latter.) While total time removes that ambiguity. Also, I thought it would be more useful to plot the data as a barplot with a real timescale, i.e. including holes for periods when the website was not visited. I used ggplot2 for that, see the picture below. The x-axis might look weird but you did spend six seconds on the website on July 1st so that's why it starts on that day, although you won't really notice there is a data point there.

My rewrite got rid of activity_date_index <- 1:length(activity_dates) but had I needed it, I would have used activity_date_index <- seq_along(activity_dates). Functions like seq_len or seq_along are better practice than 1:n because they properly handle the special case when n is zero. They return an empty vector (c()) while 1:n will return the vector c(1, 0) and create havoc.

Disclaimer: I don't have an account to that rescuetime website so I was not able to fully test my code. If you find a mistake, please feel free to edit my post, I won't mind.

Thanks for sharing your code, I like R and particularly enjoy seeing people use it to connect and analyze online databases like you did here. I hope my comments will help you.


Copying List Elements To Another List And Changing Them

Your second version is better than your first version, for two reasons:

All else being equal, building a new list is IMO easier to reason about than changing a list you're iterating over.
You're iterating using for...in rather than iterating by index using a range (and the range in your first example is hardcoded rather than being over the len of the list, which is doubly bad).

The most efficient/pythonic way is to use the comprehension syntax:

currentUsersLower = [user.lower() for user in currentUsers]

(Also, standard Python style would be to name these current_users and current_users_lower!)


As far as optimizing the tolower logic itself for a single ASCII character, your table is about as fast as it gets.

Alternatives would be:
 A) the standard tolower function
 B) this bit trick if you have only ASCII alpha characters

(unsigned char)((c) | (unsigned char)0x20)

C) this bit trick for all ASCII characters

// set the most significant bit in value X if greater than or equal to 'A'
// set the most significant bit in value Y if less than or equal to 'Z'
// bitwise AND X and Y to determine if both are true and mask out all other bits
// shift the set bit into the 0x20 place and bitwise OR in the bit
(unsigned char)(((((unsigned char)0x40 - (c)) & ((c) - (unsigned char)0x5b) & (unsigned char)0x80) >> 2) | (c))

I ran 300 iterations on a pre-generated random string of one-billion bytes (including the null terminator) of some x64 code under full optimization and no debugger attached from Visual Studio 2013.

your table lookup took about 22.4 seconds
alternative A took about 106.0 seconds (the call was not inlined)
alternative B took about 15.1 seconds (but it only works for strings only containing letters)
alternative C took about 31.9 seconds (so the table beats the bit tricks)

For whatever it's worth, replacing the tolower logic with a NOP and simply copying the source string took 15.0 seconds, so that's what's being spent in loop overhead.

But no matter, your real opportunity for optimization here is in vectorization and parallelization.

However this cannot happen as the signature and contract to the StrToLowerCase function exists now. This is for two reasons:

Any vectorized instructions will need to access data in larger chunks than one byte, and reading (and writing) past the null is bad if you don't know the arrays are padded out the appropriate amount.
You don't know the length of the string without doing a byte-by-byte scan for the null terminator. So you can't break the string into chunks easily and spin off threads to process separate chunks, and you're going to have to check for the null terminator in the middle of vectorized code (if you go that route), and you will lose much of if not all of what you gain.

So, for the sake of moving forward. Let's assume our signature now looks like this:
void StrToLowerCase(const char *src, char *dst, unsigned len)
where for the sake simplicity, len is however many chunks of data the function must process whatever its size may be for the given implementation.

Lets explore vectorized approaches:

If you have a processor that supports AVX2 instructions, then you can use the VGATHERDPS instruction which performs 8 vectorized lookups. However I don't have this instruction so I couldn't try it out. In fact few CPUs will since it first showed up in 2013. So moving on...

Almost everyone has SSE2 now days, and luckily the above bit trick can be vectorized with SSE2. Here is an implementation that operates on 128-bit chunks:

__forceinline void StrToLowerCaseSSE2(const char *src, char *dst, unsigned len)
{
   __m128i const *src128 = (__m128i const*)src;
   __m128i       *dst128 = (__m128i*)dst;
   while (len--)
   {
      __m128i const c16  = _mm_load_si128(src128++);
      __m128i const abv  = _mm_sub_epi8(_mm_set_epi32(0x40404040, 0x40404040, 0x40404040, 0x40404040), c16);
      __m128i const blw  = _mm_sub_epi8(c16, _mm_set_epi32(0x5B5B5B5B, 0x5B5B5B5B, 0x5B5B5B5B, 0x5B5B5B5B));
      __m128i       msk  = _mm_and_si128(abv, blw);
      msk                = _mm_and_si128(msk, _mm_set_epi32(0x80808080, 0x80808080, 0x80808080, 0x80808080));
      msk                = _mm_srli_epi16(msk, 2);
      msk                = _mm_or_si128(msk, c16);
      _mm_store_si128(dst128++, msk);
   }
}

The above SSE2 implementation finishes the test in just 5.3 seconds, roughly 4.5 times faster than the table lookup code that was previously that fastest. However, keep in mind some of this is in the loop overhead we eliminated by effectively unrolling the loop 16 times (each iteration of the SSE2 loop lower-cases 16 ASCII chars). If we unroll the loop 16 times for the lookup code, it finishes in 15.3 seconds. So loop overhead aside, the SSE2 implementation is about 3 times faster. Furthermore, if we employee the alpha-character only tolower in the unrolled loop it finishes in 8.9 seconds, and the SSE2 code that handles non-alpha ASCII characters as well as extended ASCII (codes greater than 127) is still faster.

The SSE2 implementation will be the fastest presented here, but lets say you don't want to use SSE2, you have 64-bit support, and you only have standard ASCII in the range [0, 127] and not extended ASCII in the range [0, 255] (the most significant bit is always zero). In that case you can use a 64-bit vectorized approach that hijacks the 64-valued bit in the same way the above bit trick operations hijack the 128-valued bit. The subtractions can be done on 8 characters shoved into a 64-bit integer, but the trick will be ensuring carries and borrows don't escape the byte you're working in. This can be done by keeping in mind the 128-valued bit in every byte will be zero. Here is the 64-bit implementation where len is the number of 64-bit chunks:

 __forceinline void StrToLowerCase64(const char *src, char *dst, unsigned len)
{
   unsigned const __int64 *src64 = (unsigned const __int64 *)src;
   unsigned       __int64 *dst64 = (unsigned __int64 *)dst;
   while (len--)
   {
      unsigned const __int64 x = *src64++;
      *dst64++ = (((0xC0C0C0C0C0C0C0C0 - x) & (x + 0x2525252525252525) & 0x4040404040404040) >> 1) | x;
   }
}

The above 64-bit implementation finishes the test in 6.3 seconds, and is almost as fast as the 128-bit SSE2 implementation that finished in 5.3 seconds.

Whats next?

From here one can adapt these tricks to higher bit-width vectorization instructions so long as one can be confident the target platform has them available.

There are two other places to go with this that will certainly give even better performance if the strings or number of string to process are large enough. One, is breaking this up into threads either within the function or in the functions that call this function. The other is to resort to offloading the task to the GPU or other more drastic hardware solutions.

EDIT
Here is an SSE2 approach adapted to work with the null terminator. The input still needs to be 128-bit aligned, but special logic could easily be added to the function to handle that. It finishes in 5.8 seconds, so it's only marginally slower than the version that does not perform a null check which finished in 5.3 seconds.

__forceinline void StrToLowerCaseSSE(const char* src, char* dst)
{
    __m128i const *src128  = (__m128i const*)src;
    __m128i       *dst128  = (__m128i*)dst;
    for (;;)
    {
        __m128i const c16  = _mm_load_si128(src128);
        __m128i const null = _mm_cmpeq_epi8(c16, _mm_set_epi32(0, 0, 0, 0));
        if (_mm_movemask_epi8(null))
            break;
        ++src128;
        __m128i const abv  = _mm_sub_epi8(_mm_set_epi32(0x40404040, 0x40404040, 0x40404040, 0x40404040), c16);
        __m128i const blw  = _mm_sub_epi8(c16, _mm_set_epi32(0x5B5B5B5B, 0x5B5B5B5B, 0x5B5B5B5B, 0x5B5B5B5B));
        __m128i       msk  = _mm_and_si128(abv, blw);
        msk                = _mm_and_si128(msk, _mm_set_epi32(0x80808080, 0x80808080, 0x80808080, 0x80808080));
        msk                = _mm_srli_epi16(msk, 2);
        msk                = _mm_or_si128(msk, c16);
        _mm_store_si128(dst128++, msk);
    }
    src = (const char*)src128;
    dst = (char*)dst128;
    while (*src)
    {
        const unsigned char c = *src++;
        *dst++ = (unsigned char)(((((unsigned char)0x40 - (c)) & ((c)-(unsigned char)0x5b) & (unsigned char)0x80) >> 2) | (c));
    }
    *dst = '\0';
}

And here is similar null check adaptation of the 64-bit code. It finishes in 6.4 seconds where the original 64-bit version took 6.3.

__forceinline void StrToLowerCase64(const char* src, char* dst)
{
    unsigned const __int64 *src64 = (unsigned const __int64 *)src;
    unsigned       __int64 *dst64 = (unsigned __int64 *)dst;
    for (;;)
    {
        const unsigned __int64 x  = *src64;
        if ((x - 0x0101010101010101) & 0x8080808080808080)
            break;
        ++src64;
        *dst64++ = (((0xC0C0C0C0C0C0C0C0 - x) & (x + 0x2525252525252525) & 0x4040404040404040) >> 1) | x;
    }
    src = (const char*)src64;
    dst = (char*)dst64;
    while (*src) {
        const unsigned char x = *src++;
        *dst++ = (unsigned char)(((((unsigned char)0x40 - (x)) & ((x)-(unsigned char)0x5b) & (unsigned char)0x80) >> 2) | (x));
    }
    *dst = '\0';
}


What about this query:

SELECT COUNT(*) + 1 as user_rank
    FROM olympia_punkte_alle p
    WHERE markt_id = 1
    GROUP BY fb_id
    HAVING
        MAX(punkte) > (SELECT MAX(punkte)
            FROM olympia_punkte_alle
            WHERE markt_id = 1
            GROUP BY fb_id
            HAVING fb_id = 2950)

We are getting the count of users that have better score then users with id 2950.
The count of better users + 1 is rank of your user.


Invoke-WebRequest in a loop until NotFound

You appear to have some incorrect logic. The until expression will never get evaluated in the case of a 404 exception. It will get skipped over. So it's kind of pointless.

So let's replace the repeat ... until with a while ($true). That is, an infinite loop. This works the same as what you already had, but the logic is clearer. I added a comment at the top, too, to let the reader know that a 404 exception will break the loop:

while ($true) {
    # Will throw 404 exception when finished.

    $Path = "/universes?offset=$offset&limit=$limit"

    $response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
    ($response | ConvertFrom-Json).universes.universe

    $offset += $limit
}

Now, in general it's not good to use exceptions for normal program control flow. They should normally be used for exceptional cases only. But sometimes—such as in this case it would seem—we do have to use them. In such cases the usual pattern is to catch the exception and then examine it to see if it's a normal control flow exception or if it's a true exception, and respond accordingly.

So let's do that. If we catch a 404 exception, then we will just ignore it. If it's anything else, then we will rethrow it:

try {
    while ($true) {
        # Will throw 404 exception when finished.

        $Path = "/universes?offset=$offset&limit=$limit"

        $response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
        ($response | ConvertFrom-Json).universes.universe

        $offset += $limit
    }
}
catch [System.Net.WebException] {
    $statusCode = $_.Exception.Response.StatusCode.Value__

    if ($statusCode -eq 404) {
        # Normal end case. Do nothing.
    }
    else {
        throw
    }
}


Writing a utility class for converting between datetime and timestamp

Let's examine the code:

#!usr/bin/python

you don't need to execute the code directly, so why this line?

class datetimeutil:
    @staticmethod

why a class with static methods? Keep it simple, write global functions. You already have the module which encapsulates the functions.

    def strtodt(text):

I don't like too much the names of these functions. I know that also python uses ugly names (words without any separator) but I think you could improve this... for example: str_to_dt or str2dt seem better to me.

About the functionality. Managing dates is a quite difficult task. The python library in my opinion makes a great job in distinguishing naive and aware datetimes. Your wrapper module simplifies this by considering each naive datetime as a localtime (if I understand it correctly). I think it is not good to hide this decision in your code. Explicit is better, even if it could me more verbose.

Also I think you missed the timedelta.total_seconds function, which could be used in your code.


Use this:

if (list.size() <= 1) {
    return list.size();
}

list.get(1) refers to the second element in the list, not the first. Either rename the variable or use list.get(0). With that change, you don't need to use a list size of 1 as a special case.

Only being able to do the job on ArrayList is quite useless. Your method can take an argument of type List instead.

No, it is no need to use else if in this case.

Rewriting with Iterable

You currently check the first item in the list twice. If your code would accept an Iterable<Integer>, you would support even more data types (You still support ArrayList also).

The only thing you need is the Iterator from the iterable. When you have that, you can first see if it contains at least one item. If it doesn't, return 0. Otherwise, you do similar to what you are already doing, but with different code.

public static int range(Iterable<Integer> numbers) {
    Iterator<Integer> iterator = numbers.iterator();
    if (!iterator.hasNext()) {
        return 0;
    }

    int firstElement = iterator.next();
    int max = firstElement;
    int min = firstElement;
    while (iterator.hasNext()) {
        int elementValue = iterator.next(i);
        if (max < elementValue) {
            max = elementValue;
        }
        if (elementValue < min) {
            min = elementValue;
        }
    }
    return (max - min) + 1;
}

Happy coding!


Ensuring if an object is Assignable from a class type

private Object ensureType(Class<?> expectedClass, Object value) {

Your names could be slightly better, given that this function does not only ensure something, but also converts it.
private Object convert(Class<?> targetClass, Object value) {

    throw new ClassCastException(
            "argument " + value + " of type " + valueClass + " cannot be converted to " + expectedClass);

Given that the function converts, I find the ClassCastException inappropriate. An IllegalStateException or IllegalArgumentException might be better fitting.

What you're doing here is complex, and there is not really an easier way to do it either. You have n classes that you want to map to m classes, so the complexity will always be there in one way or another. The best thing you can do is make it more readable. For example with extracting the converting parts into functions:
    // ...

    if (targetClass.isAssignableFrom(String.class)) {
        return convertToString(value);
    }

    if (targetClass.isAssignableFrom(Date.class)) {
        return convertToDate(value);
    }

    if (targetClass.isAssignableFrom(Integer.class)) {
        return convertToInteger(value);
    }

    // ...

That is as readable as it gets, in my opinion.
If you like classes, you can always extract the conversion into a single class for each mapping, and then iterate over that:
public interface Converter {
    public Class<?> getTargetType();
    public Object convert(Object value);
}

// ...

List<Converter> converters = new ArrayList<>();
converters.add(new StringConverter());
converters.add(new DateConverter());
converters.add(new IntegerConverter());
// ...

// ...

for (Converter converter : converters) {
    if (targetClass.isAssignableFrom(converter.getTargetType())) {
        return converter.convert(value);
    }
}

This, however, has the downside to split everything over many classes. A possible remedy to that might be to use single functions in the same class, like this:
HashMap<Class<?>, Function<Object, Object>> converters = new HashMap<>();
converters.put(String.class, this::convertToString);
converters.put(Date.class, this::convertToDate);
converters.put(Integer.class, this::convertToInteger);
// ...

// ...

for (Entry<Class<?>, Function<Object, Object>> converterEntry : converters.entrySet()) {
    if (targetClass.isAssignableFrom(converterEntry.getKey())) {
        return converterEntry.getValue().apply(value);
    }
}

That might be one of the easier readable and maintainable variants.
There is another, completely insane option, actually, which I feel to need to point out. You can use the above setup, with a method for every conversion, and reflection to build this list dynamically. Something along these lines:
private Integer convertToInteger(Object value);
private Date convertToDate(Object value);
private String convertToString(Object value);

// Pseudo-Code follows:

for (Method method : getClass().getDeclaredMethods()) {
    if (method.getName().startsWith("convert")) {
        if (targetValue matches method return type
                && value matches first method parameter) {
            return method.invoke(this, value);
        }
    }
}

But that should be an absolute last resort, as it is not quite easy to maintain without knowing what you've got at your hands there.


A Tour of Go, problem #56 - error handling

I would name the error ErrSqrtNegative instead of ErrNegativeSqrt.

Sqrt(0) should not be an error.

In case of error, I would use math.NaN(), ErrSqrtNegative(f) as the return values.


Erlang handling errors in concurrent programs

In your code you're calling spawn_monitor/1 like this:

spawn_monitor(proc()),

where proc/0 is a local function, but this doesn't do what you think it does. First it calls proc/0, which blocks in a receive until it gets a message. Normally it would return the value of receive, but your receive calls exit/1 so there's no return. So, what happens is that the first call into proc/0 blocks until it receives a message, at which point it exits, and since it was running not in a spawned process but in the calling process — the process where the caller is running — the caller exits too. Nothing ever gets spawned or monitored. (This same problem exists in your second code example too.)

What spawn_monitor/1 wants is a function, so you should be calling it like this:

spawn_monitor(fun proc/0),

If you make that change everywhere, then the code works, but there's one other thing: your start_and_monitor(0) function clause should not be calling spawn_monitor before calling receive, otherwise Int+1 rather than Int processes will be spawned and monitored.

As for the second code example, monitors and processes are cheap, so there's no point in trying to bundle them together into a single monitoring point.

And finally, you might consider solving this problem not with monitors but rather with links. A monitor allows a process to watch an unrelated process, but if one process is spawning another, then they're related, so links are a viable approach.


You can write this simpler:

if(winners.length === 1){
    return winners[0];
}
winners.sort();
return winners[winners.length - 1];

Like this:

winners.sort();
return winners[winners.length - 1];

Because if winner contains one element, winners.sort() will do nothing anyway.

vObj is a poor name for a map of vote counts per name.

It could be a good idea to decompose the implementation to smaller functions with a single responsibility:

Build a map of vote counts
Find winners
Find the single winner


If you just want to do the where for every non-empty value. You can do the following:

public static function allRejUserByProv($prov = '', $gender = '', $dist = '', $ttc = '')
{
    $fields = [
        'gender' => $gender,
        'p_district' => $dist,
        'p_province' => $prov,
        'ttc_name' => $ttc
    ];

    $result = self::where('decision', '3');

    foreach ($fields as $attr => $value) {
        if(! empty($value)) {
            $result = $result->where($attr, $value);
        }
    }

    return $result->count();
}

This way you will remove the multiple ifs.

If you will always use number_format to format the return value why not just adding it to the function:

return number_format($result->count());

Hope this helps :)


@spec_2d[@spec] = map [ $spec[$_] ], @spec;

but judging from the subject I think you want this,

my @spec_2d = map [ $_ ], @spec;


K&R - The C programming language Exercise1-12

To get a historically correct impression of programming in C, K&R is probably the best book available. In addition to that book, you should also get a more modern book about C since K&R doesn't teach you anything about function prototypes and buffer overflows (one of the main reasons that software written in C is often unreliable).

For example, the page you linked has a solution containing char buffer[1024];. That solution will fail with unpredictable behavior as soon as you pass it a file containing very long words, as the buffer will overflow and the C program will not reliably crash but is free to do anything it wants, including crashing or making daemons fly out of your nose. This is called undefined behavior.

There's not much to improve about your code. To make it modern, you simply have to replace one line:

main()              // before
int main(void)      // after

After that, you should tell your editor to format the source code. This will indent the innermost line c = getchar() a bit more, so that it is clearly inside the while loop.

// before:
while(c == ' '|| c == '\t' || c == '\n')
 c = getchar();

// after:
while (c == ' '|| c == '\t' || c == '\n')
    c = getchar();

Some other reviewers will say that you must always use braces in the if and while statements, but I disagree. It's enough to let your editor or IDE format the source code automatically, this will make it obvious when your code is indented wrongly.


Is translator really a translator? IMO a better name could be dictionary.

I also don't understand an idea to create variables like dot and dash.
{'a', ".-"} would be much clearer.

Don't use misleading function names. The function getUserInput does much more than getting something from user! It also translates the text and prints it. So, in Main, I'd write:

input = getUserInput();
morse = translate(input);
PrintOnScreen(morse);

Be consistent in naming: now some functions have names starting with capital letter, some not.


Force Stop by Error in httpClient.execute(httpPost);

You should remember this.

  From Android 3.x Honeycomb or later, you cannot perform Network IO on
  the UI thread and doing this throws
  android.os.NetworkOnMainThreadException. You must use Asynctask
  .

You have to put your getXmlFromUrl(..) code inside Asynctask method

For more Information Refer this Link
http://developer.android.com/reference/android/os/AsyncTask.html


Given a monetary amount, calculate the equivalent change

Without loops or similar "advanced" structures, there isn't much you can do to simplify this.

You could save the duplication in extra variables. It might look like this:

int hundred = valueIntegral / 100;

int remainderHundred = valueIntegral % 100;
int fifty = remainderHundred / 50;

int remainderFifty = remainderHundred % 50;
int twenty = remainderFifty / 20;

int remainderTwenty = remainderFifty % 50;
int ten = remainderTwenty / 10;

[...]

You have to decide if it's more readable. It's certainly less complex (and mistakes/typos are easier to catch), but it might take away some clarity.

Misc

you have a bit too much vertical space. Not every line needs its own paragraph.
your comments don't add all that much value. The variable names already tell me all the comments do.


I would recommend reading this article by Eric Lippert

You'll definitally want an extension method for this... let me hit the google real quick.... Using some inspired code from this SO post I wrote this.

static class Extensions
{
    private const HashSet<Type> NumericTypes = new HashSet<Type>
        {typeof(decimal), typeof(byte), typeof(sbyte), typeof(short), typeof(ushort),
        typeof(int),typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double)};

    /// <summary>Determines whether the specified object is numeric.</summary>
    public static bool IsNumeric(this object obj) { return NumericTypes.Contains(obj.GetType()); }
}

Now in your code you can just say

if(!row[columnName].IsNumeric())
    throw new Exception();

However, now I will review your code in general.

You should not throw Exception, you should always be specific with your exception throwing. In this case I probably would throw an ArgumentException, but really this seems like a specific case where you should define your own.
I'm a bit confused by your declaring isNumeric outside the loop, when you don't use it outside that scope.
instead of saying if (isNumeric == false) just say if(!isNumeric)
I don't see why you nested this function inside your loop. its not taking full advantage of the fact that it is nested, and could just aswell be a function outside. Plus why declare it if you might be throwing an exception.. might as well wait. And while you're waiting, lets just take this one liner and make it a statement instead. (My thoughts jumped around there a bit)

In the end your code could just look like.

public static double GetColumnAverage(DataTable dt, string columnName)
{
    foreach (DataRow row in dt.Rows)
        if (!row[columnName].IsNumeric())
            throw new ArgumentException("-Something meaningful here-");
    return dt.AsEnumerable().Where(x => x[columnName] != DBNull.Value).Average(x => x.Field<dynamic>(columnName));
}


Your link should look like this:

Permalink

In your php code, you can grab the selected quote id like this:

$q_id = $_GET['q_id'];

To check if the q_id has been set:

if (array_key_exists('q_id', $_GET)) {
    // the q_id was specified
}

To check that the q_id is numeric (important to do before plugging it into a mysql query):

if (is_numeric($_GET['q_id'])) {
    // q_id is a number
}

To fetch that single quote:

$result = mysql_query("SELECT * FROM sheet1 WHERE q_id = " . $q_id);

Deprecation of mysql_ functions

  PHP functions that start with mysql_ have been deprecated as of PHP 5.5.0. If you are in a position to do so, please consider updating your code to use the MySQLi or PDO extensions instead.


As long as you are using re.sub() to handle the spaces, you may as well use it to perform the entire task.  Note that I've added entries to codes that maps triple-space to a space, and space to nothing.  Also, since codes contains one entry per line, I prefer to put a comma after every entry, including a superfluous comma after the last one, to make it easy to add or remove entries.

import re

codes = {
    '.-': 'A',
    '-...': 'B',
    '-.-.': 'C',
    …
    '--..': 'Z',
    '   ': ' ',
    ' ': '',
}

with open('morse.in') as f:
    print(
        re.sub(
            '[.-]+|   | ',
            lambda match: codes[match.group()],
            f.read()
        ),
        end=''
    )


Filter out non-alphabetic characters from a list of words

Since Python strings are immutable, appending one character at a time using += is inefficient.  You end up allocating a new string, copying all of the old string, then writing one character.

Instead, clean() should be written like this:

def clean(word):
    return ''.join(letter for letter in word.lower() if 'a' <= letter <= 'z')

Note that Python supports double-ended inequalities.

The name of your word_count_engine function poorly describes what it does.  In fact, the function doesn't print or return anything, so it's all dead code.  If I had to rewrite it, though, I'd say:

words = [word for word in map(clean, document.split()) if word]

Also consider replacing all of this code with a simple regular expression substitution.


The code is relatively neat and appears to work properly, so you seem to be well on your way to mastering C.  Here are some things that may help you on that road.

Strings are automatically terminated

The code currently includes these two lines:

char s1[] = "I am a test.\0";
const char *s2 = "AE\0";

However, the explicit '\0' at the end of these strings is not necessary.  A C string is automatically terminated with an implicit '\0' character, so these lines would normally be written as:

char s1[] = "I am a test.";
const char *s2 = "AE";

Move function bodies to avoid declaration

Modern C no longer requires function declarations before every function definition.  As long as, reading from top to bottom, each function definition does not refer to anything not yet defined, the function declarations may be omitted.  So in this program, if you put the function definitions in the order toUpper, contains, squeeze and main, you can omit the declarations.  This is handy because it means you only need to maintain the function signature in one place rather than two.

Use bool instead of int where appropriate

The contains function returns 1 if the value is found or 0 otherwise.  That is, it's essentially returning a boolean value.  You can make that more clear by using #include <stdbool.h> and writing the function as:

bool contains(char toCheck, const char *toRemove) { /* ... */ }

Then the return statements can be return true; and return false;  As documented here, bool has been standard C since 1999.

Use standard functions

I know this is a learning exercise and you're just starting, but it's generally encouraged to use standard functions rather than duplicating them.  For instance, toupper has been part of the standard since 1989.

Avoid creating unneeded variables

The variable c in the contains() routine is not really needed.  Instead of this:

if ((c = toUpper(toCheck)) == toRemove[index]){

You can write this:

if (toUpper(toCheck) == toRemove[index]){


Checking if a file exists then do something if it's not a directory

You can actually omit fs.exists(). The fs.stat() will return an error when the item you are testing is not there. You can scavenge through the err object that fs.stat() returns to see what error caused it. As I remember, when fs.stat() stats a non-existing entry, it returns an ENOENT, no such file or directory error.

And so:

var fs = require('fs')
  , filename = process.args[2]
  ;

fs.stat(filename, function(err, stats) {
  if(err){
    //doing what I call "early return" pattern or basically "blacklisting"
    //we stop errors at this block and prevent further execution of code

    //in here, do something like check what error was returned
    switch(err.code){
      case 'ENOENT':
        console.log(filename + ' does not exist');
        break;
      ...
    }
    //of course you should not proceed so you should return
    return;
  }

  //back there, we handled the error and blocked execution
  //beyond this line, we assume there's no error and proceed

  if (stats.isDirectory()) {
    console.log(filename + ": is a directory");
  } else {
    console.log(filename);
  }
});

So essentially, we reduced the number of indents caused by callbacks and also reduced it by restructuring if-else statements


Design

Is there a need for IEventDispatcher? Defining it as an abstract base class doesn't provide much utility if there's only ever going to be one derived class.
Is there any requirement for EventDispatcher::eventListeners to be of type std::multimap<EventType, EventHandler>? It doesn't seem like the ordering of elements has much relevance, so a std::unordered_multimap<EventType, EventHandler> might provide better performance. But: The current code doesn't even use any std::multimap specific functionality, so the easiest solution might actually be a std::unordered_map<EventType, std::vector<EventHandler>>.
There is no way to remove a specific EventHandler, only all EventHandlers registered for an EventType.
There's no way to pass arguments to an event handler. This might be necessary for some use cases, e.g. to indicate what changed.

  There's no easy way to provide both general event dispatching (handling multiple different EventTypes) and event-specific parameter passing (different parameter types for different events). Some solutions:

  Redefining the scope of EventDispatcher: Instead of handling multiple events in each EventDispatcher instance each instance is only responsible for handling one specific EventType. The parameter types can then be taken as template parameters.
  Make EventType a base class and inherit from it when parameters need to be passed (so more like EventArgs in C#). Requires EventType instances to be passed as references or pointers, and EventHandlers need to downcast internally to the concrete derived class. Many possible ways to get this wrong, and the compiler might not be able to help much.

Implementation issues

EventDispatcher::dispatch iterates over all entries in EventDispatcher::eventListeners. Why not use std::multimap::equal_range to then only iterate over all entries that match?

  This would be \$\mathcal{O}(k + \log n)\$ on average instead of \$\mathcal{O}(n)\$ (where \$n\$ denotes the number of all elements in the container, and \$k\$ denotes all elements for the relevant key), or \$\mathcal{O}(k)\$ on average for std::unordered_multimap.

  The proposed replacement std::unordered_map<EventType, std::vector<EventHandler>> would also have complexity \$\mathcal{O}(k)\$ (\$\mathcal{O}(1)\$ to find the vector, \$\mathcal{O}(k)\$ to iterate it) - even in the worst case.

Rule of Five violation: A custom destructor is declared for EventDispatcher, but no custom copy constructor, copy assignment operator, move constructor and move assignment operators are declared. This prevents the compiler from providing default implementations for those (or soon will, it currently is deprecated for compilers to do so in case of copy constructor and copy assignment operator).

  It would be easiest to just use the default compiler-provided destructor.

Inconsistent naming: IEventDispatcher.h has file extension .h, whereas EventDispatcher.hpp has file extension .hpp.
In EventDispatcher, all member functions inherited and overridden from IEventDispatcher lack the override keyword.
EventDispatcher::dispatch could be const.


The difference averages to .2 microseconds per number checked.
To see if its the inner loop, try unrolling it in the second program:
...
for i in range(5, ceiling+1, 6):
    # test only against factors less than the square root
    # just use the sqrt of the bigger number to avoid another call to sqrt
    root = math.sqrt(i + 2)

    # tests 6k - 1
    for j in prime:
        if j > root:
            prime.append(i)
            break
        if i % j == 0:
            break

    # tests 6k + 1
    i += 2
    for j in prime:
        if j > root:
            prime.append(i)
            break
        if i % j == 0:
            break
    ...


Array of immutable objects initialized at compile-time

I would suggest an enum: they're made to encapsulate a set of distinct values known at compile time. For example, this might be the code you have as a result:

public enum CameraInformation {

    First(14_123, 30_123, "http://google.com"),
    Second(14_922, 40_123, "http://google.com"),
    Third(14_815, 41_123, "http://google.com"),
    Fourth(14_300, 40_123, "http://google.com");

    private final int min, max;
    private final String address;

    CameraInformation(int min, int max, String address) {
        this.min = min;
        this.max = max;
        this.address = address;
    }

    public int getMin() {
        return min;
    }

    public int getMax() {
        return max;
    }

    public String getAddress() {
        return address;
    }
}

The main reason for doing this is because I don't like the 0-based array index with the 1-based cameras: lutBounds[3] refers to camera 4 instead of 3, thus losing some expressiveness even for people familiar with this.

Using an enum also takes care of you having to choose a place to create those boundary values and passing them around: the enum is created once, stores its values in a central place and can be used anywhere you want.

Usage is easy:

int min = CameraInformation.Third.getMin();


Vectorized crosstabulation in Python for two arrays with two categories each

Algorithm
If you look at your code, and follow the if-elif part, you see that there are 4 combinations of i and j

i      j     : result
True,  True  : A
False, True  : B
True,  False : C
False, False : D

If you use the tuple (i, j) as key, you can use a dict lookup
{
    (True, True): "A",
    (False, True): "B",
    (True, False): "C",
    (False, False): "D",
}

Or simpler:
{
    (True, True): 3,
    (False, True): 1,
    (True, False): 2,
    (False, False): 0,
}

The choice of numbers is deliberate, since when you use True as 1 and False as 0, you can do
def crosstab2(label, presence):
    for i, j in zip(label, presence):
        yield i * 2 + j

c = collections.Counter(crosstab2(label, presence))
print('A:',c[3],'B:',c[1],'C:',c[2],'D:',c[0])

This is not faster than your original solution, but this is something you can vectorize
label = np.array([True, True, False, False,False, False,True, False, False, True, True, True, True, False])
presence = np.array([True, False, False, True, False, False, True, True, False, True, False, True, False, False])
c = collections.Counter(label * 2 + presence)
print('A:',c[3],'B:',c[1],'C:',c[2],'D:',c[0])

Which is significantly faster, even if you account for the few seconds of overhead for the creation of the numpy arrays
Formatting
Try to follow pep8.

spaces around operators (=, +, ...)
spaces after a ,

naming
I try to give collections of elements a plural name. In this case, I would use labels., so if you ever need to iterate over them, you can do for label in labels, which is a lot more clear than for i in label:
list
The extra call to list in  zip(list(label),list(presence)) is not necessary. zip takes any iterable, and doesn't modify it in place.


Terser way of generating deeply nested hash

Recursion perhaps?

def nested_hash(levels)
  return if levels <= 0
  { "children" => [ nested_hash(levels - 1) ].compact }
end

Or it could be

def nested_hash(levels)
  return nil if levels <= 0
  array = nested_hash(levels - 1)
  { "children" => array.nil? ? [] : [array] }
end

if you prefer handling the nil upfront, instead of removing it with compact

In either case, nested_hash(3) will get you

{"children"=>[
  {"children"=>[
    {"children"=>[]}
  ]}
]}

Note that unlike yours, these ones will return nil when levels is zero or less. So you'll want to do the {} fallback elsewhere, e.g. hsh = nested_hash(x) || {}.


Adjoin-set for an ordered set representation

Calling element-of-set? from adjoin-set introduces unnecessary redundancy.  One may incorporate this test within the adjoin-set function (in your case, rec should be the main body of your function, with an = test added):

(define (adjoin-set x set)
  (cond
    ((null? set) (cons x set))
    ((= x (car set)) set)
    ((< x (car set)) (cons x set))
    (else (cons (car set) (adjoin-set x (cdr set))))))

This function performs fewer steps since it does not call element-of-set?.  However, its complexity is still O(n), which is the same as your implementation's complexity, as well as the complexity of element-of-set?.


I am guessing indexOf is O(n). A faster way may be to add all the characters of a string to a set. Then call contains for each character of the second string (I would imagine that contains is on average O(1) for a hash set or O(lg(n)) for a tree set.)

private static boolean hasCommonSubString(String shorter, String longer)
{

    Set<Integer> set = shorter.chars()
                              .boxed()
                              .collect(Collectors.toSet());

    return longer.chars().anyMatch(set::contains);
}


Dockerfile to install Python and React in Linux container

Your dockerfile is generally correct. Every RUN instruction in the Dockerfile writes a new layer in the image. Every layer requires extra space on disk. In order to keep the number layers to a minimum, any file manipulation like moving, extracting, removing, etc, should ideally be made under a single RUN instruction. So, you should try to minimize number of RUN command in your file (eg. try to merge installing requirements into one command) You can check size of you layers using cmd:

  docker history

But there is question - Why do you want to have react and python in one container?

From this dockerfile I don't understand why you are adding node/react to your container. If you need python, because you have to prepare some data for react or run some script before start your node app, then you could think about use Multi-Stage Builds. Example:

FROM python:3.6-slim

# here build/do what you want to do
WORKDIR /myapp
COPY myscript.py .
RUN python myscript.py > data

FROM bayesimpact/react-base

# run your react application
WORKDIR /myapp
COPY react_app .
CMD ["./react_app/app", "data"]

So, when you are using Muli-Stage Builds you can:

  You can selectively copy artifacts from one stage to another, leaving
  behind everything you don’t want in the final image.

Also, there is possibility to use prepared earlier image with node and python, it should be smaller, but you have to also check this. (e.g beevelop/docker-nodejs-python)


Implement a generic Fibonacci sequence in Rust without using Copy trait

You can use Clone instead of Copy. This requires adding .clone() calls where the compiler did a copy when the Copy bound was present.

extern crate num;

pub mod fib_trait {
    use num::traits::*;
    use std::ops::Add;

    #[derive(Clone, Copy)]
    pub struct Fibonacci<T>
        where T: Zero + One + Add + Clone
    {
        curr: T,
        next: T,
    }

    impl<T> Fibonacci<T>
        where T: Zero + One + Add + Clone
    {
        pub fn new() -> Fibonacci<T> {
            Fibonacci {
                curr: T::zero(),
                next: T::one(),
            }
        }
    }

    impl<T> Iterator for Fibonacci<T>
        where T: Zero + One + Add + Clone
    {
        type Item = T;

        fn next(&mut self) -> Option<T> {
            let c: T = self.next.clone();
            self.next = self.next.clone() + self.curr.clone();
            self.curr = c;
            let n: T = self.next.clone();
            Some(n)
        }
    }

    #[test]
    pub fn fib_test() {
        let mut f: Fibonacci<u32> = Fibonacci::new();
        assert_eq!(f.next(), Some(1));

        let mut next_val = 1;
        let mut curr_val = 0;
        for i in Fibonacci::<u32>::new().take(4) {
            let c = next_val;
            next_val = curr_val + next_val;
            curr_val = c;
            assert_eq!(i, next_val);
        }
    }
}

We can eliminate the clones on the addition by requiring and using addition on references instead of direct values. for<'a> introduces a higher-rank trait bound – we need this because we want &'a T to implement Add<Output=T>, whatever the lifetime 'a is.

extern crate num;

pub mod fib_trait {
    use num::traits::*;
    use std::ops::Add;

    #[derive(Clone, Copy)]
    pub struct Fibonacci<T>
        where T: Zero + One + Clone,
              for<'a> &'a T: Add<Output=T>
    {
        curr: T,
        next: T,
    }

    impl<T> Fibonacci<T>
        where T: Zero + One + Clone,
              for<'a> &'a T: Add<Output=T>
    {
        pub fn new() -> Fibonacci<T> {
            Fibonacci {
                curr: T::zero(),
                next: T::one(),
            }
        }
    }

    impl<T> Iterator for Fibonacci<T>
        where T: Zero + One + Clone,
              for<'a> &'a T: Add<Output=T>
    {
        type Item = T;

        fn next(&mut self) -> Option<T> {
            let c: T = self.next.clone();
            self.next = &self.next + &self.curr;
            self.curr = c;
            let n: T = self.next.clone();
            Some(n)
        }
    }

    #[test]
    pub fn fib_test() {
        let mut f: Fibonacci<u32> = Fibonacci::new();
        assert_eq!(f.next(), Some(1));

        let mut next_val = 1;
        let mut curr_val = 0;
        for i in Fibonacci::<u32>::new().take(4) {
            let c = next_val;
            next_val = curr_val + next_val;
            curr_val = c;
            assert_eq!(i, next_val);
        }
    }
}

Also, note the stylistic changes I made above:

line break before where
indent where clause
no space before :


Retrieving values from Entity Framework DbContext to render in a ListBox

You might as well just use LINQ to project the collection to SelectListItem

return db.Physicians.Select(new SelectListItem { Value = p.Id.ToString(), Text = p.Name });

As far as lists and arrays are concerned there is actually only one main difference betwen them: arrays cannot change its size. Use what is more conveninet. If you have fixed collection of items the I'd probably use an array an in all other cases I guess I'd chose a list.

Alternatively you can use ICollection<T> as a return type and since most collections implement this interface it doesn't matter what the underlying type is.


Proxy using socket, doubts on multithreading and connection closing

First off, you need to do some error catching with the socket functions. All of them can possibly fail, it's better to be safe and do some error catching.

Here is what I mean:

try:
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('', serv_port))
    server.listen(5)
except socket.msg as error:
    print("Recieved error #%d: %s\n" % (error[0], error[1]))
    sys.exit(-1)

And, with socket.accept too:

try:
    conn, addr = server.accept()
except socket.error as error:
    print("Recieved error #%d: %s\n" % (error[0], error[1]))
    sys.exit(-1)

When there is an error with a socket call, a tuple is returned containing the error code (returned from the socket syscall) and an error message to go along with it.

I added a sys.exit to the code that will close the program with exit code -1, which usually means to external that there was an error while running the program. To use this, you will have to import sys.

In this part of a line

threading.Thread(target=cthread, args=(conn,))

I don't think there should be a comma after conn in the tuple for args.

According to the python docs on socket.settimeout,

  The value argument can be a nonnegative float expressing seconds, or
  None.

You aren't passing in a float value when you call settimeout.

Also, I believe that you should allow more time before a timeout. Reading in 4096 bytes of data might take more than 1 second.

Maybe 3 seconds would work.

Indentation isn't as strict in python 2 as it is in python 3, but you still want it to be perfect.

In your while loop of cthread, your indentation is messed up:

 def cthread(conn): # extra space
    #set timeout
    conn.settimeout(1)
    #receive data until null data is received or socket times out
    req = b''
    while True:
        try:
              req_pack = conn.recv(4096) # extra 2 spaces (1/2 tab)
            if not req_pack:
                break
            else:
                req += req_pack
        except socket.timeout:
                      break # extra 10 spaces (2 1/2 tabs)

   print req #print request to stdout # missing space

   #send a sample response
   conn.send(b'HTTP/1.1 200 OK\n\n<h1>Hello</h1') # missing space

   conn.close() # missing space

Either indent lines with 1 tab or 4 spaces.

Now for your questions.

I'm a little confused by this question. Right now in your code, when you recieve a connection, you do handle the recieving and the sending in a separate thread. This is fine, and is a good idea.
After you close a connection, there is no connection to slow down. And yes; this is fine. Since your server isn't going to do anything more after it has sent it's response, then there is no point in keeping the connection. It'll just bog your server down in the long-run.


A couple minor comments:

start_board is defined as a string with spaces, then only used once with the spaces split. This means that you can completely remove the variable and do start_game_state = GameState(['_','_','_','O','_','_','_']), which the would be better formatted over multiple lines to make the layout clear:

GameState(['_','_','_',
           '_','O','_',
           '_','_','_'
         ])

The functions min_play, max_play, and minmax are near duplicates of eachother and should be merged into one with a second argument.
All three of those functions could be made clearer with a generator expression/list comprehension
Your comments should be written using the comment operator rather than the multi-line string operator, which should be used only for multiline comments and docstrings
The function get_next_state could be simplified using a ternary operator.
Get_possible_moves could also be simplified with a list comprehension.
Instead of checking if all nine squares are filled in is_gameover, you could check if no squares are free, which is faster as it only does one pass through the loop.
lambda x:x[1] should be replaced with operator.itemgetter(1), which is faster.
is_gameover and evals are near duplicates of eachother and should be merged

Fixed code:

#Tic-Tac-Toe Minimax Program by Peter

#Tutorial found at: http://giocc.com/concise-implementation-of-minimax-through-higher-order-functions.html
from operator import itemgetter

class GameState:
    def __init__(self,board):
        self.board = board
        self.winning_combos = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
    def get_winner(self):
        '''returns None if the game is still going, otherwise scores from computer's point of view (1=win, 0=tie, -1=win)'''
        if self.board.count('_') == 0:
            return 0
        for combo in self.winning_combos:
            if (self.board[combo[0]] == 'X' and self.board[combo[1]] == 'X' and self.board[combo[2]] == 'X'):
                return 1
            elif self.board[combo[0]] == 'O' and self.board[combo[1]] == 'O' and self.board[combo[2]] == 'O':
                return 0
        return None
    def get_possible_moves(self):
        '''returns all possible squares to place a character'''
        return [index for index, square in enumerate(self.board) if square == '_']
    def get_next_state(self, move, our_turn):
        '''returns the gamestate with the move filled in'''
        copy = self.board[:]
        copy[move] = 'X' if our_turn else 'O'
        return GameState(copy)

def play(game_state, our_turn):
    '''if the game is over returns (None, score), otherwise recurses to find the best move and returns it and the score.'''
    score = game_state.get_winner()
    if score != None:
        return None, score
    moves = ((move, play(game_state.get_next_state(move, our_turn), not our_turn)[1]) for move in game_state.get_possible_moves())
    return (max if our_turn else min)(moves, key=itemgetter(1))

def pretty_print(board):
    '''prints a list by 3 chars, joined by spaces'''
    print(' '.join(board[:3]))
    print(' '.join(board[3:6]))
    print(' '.join(board[6:9]))

#Interpreting and printing board
start_game_state = GameState(['_','_','_',
                              '_','O','_',
                              '_','_','_'
                            ])
pretty_print(start_game_state.board)
#Finding best possible move and score
move, score = play(start_game_state, True)
#Displaying move and outcome
if score == 0:
    word = 'TIE'
elif score == 1:
    word = 'WIN'
else:
    word = 'LOSS, who rigged the board?!?'
print('X should go at index #',move, 'Which will always result in a ' + word)
start_game_state.board[move] = 'X'
pretty_print(start_game_state.board)


First ever unit test. Am I headed in the right direction?

If your Person was initialized with a name other than "fetus", your test would fail.. but your test has several reasons for failing and that's what makes it not-so-good: that same test would also fail if a Person was "born" with a child (!) or if age defaulted to 1, or if the welcome to this world string was different.

I've never written a unit test with JS, but I believe the following would apply:

Name your test method so that anybody (including non-technical) reading it (the name) knows exactly what is being tested.
Arrange the dependencies of your SUT (that's System Under Test). Set up /configure your mocks, define what the expected outcome should be.
Act upon your SUT (i.e. call the method you want to test). Pass in your mock dependencies, retrieve the "actual" result.
Assert - verify that you get expected results, i.e. make the test pass, or fail.

In this particular case, I'm not sure what's being tested exactly - you're merely verifying that the person object was initialized with the expected default values? I guess it's ok.

Unit tests should be testing that the code does what it's supposed to be doing.

As I said I've never written a test with JS, so this example is C#:

    [TestMethod]
    public void ShouldReplaceCommaWithEmptyStringInProductDescription()
    {
        // arrange
        var testDescription = "Product,Description";
        var data = GetValidMockRecord();
        var values = data.Split(',');
        values[11] = testDescription;
        data = string.Join(",", values);

        if (!testDescription.Contains(",")) Assert.Inconclusive("testDescription must contain at least one (1) comma (,).");

        var sut = new EdiParser();
        var expected = testDescription.Replace(",", string.Empty);

        // act
        var result = sut.Parse(data);
        var actual = result.ProductDescription;

        // assert
        Assert.AreEqual(expected, actual);
    }

I don't think the language is a barrier: as you can see I'm asserting in my arrange section and making the test inconclusive if the test data would make the test, well, inconclusive. Then in the actual assert section I'm only testing one thing, and this is what unit testing is really about.


I would wrap the entire part of analyzing in a function:

def analyze_twees(tweets):

Then you could pass in content, from whichever source. It doesn't matter, whether the input comes from sys.stdin or a string, which you just generated. This makes the function easier to test, since you do not need passing a file into your function.
As 200_success said,

for i in range(0, len(tweet)):

is considered poor style in Python. According to (1) you should iterate over the tweets as suggested:

for tweet in tweets.

Your variable naming is very obscure. Think of future you coming up in 6 Months fixing a bug - do you understand your code at first glance? I doubt that.

n6.strip().lower()

One can only guess, what this is about. But if you wrote something like

tweeted_text = re.split("\s+", tweet.strip().lower())

one could imagine, what you intended to do.
You should split your concerns:

you are going to read a file line by line. So that should be one function.
you are printing something to the console. That would be another function.
you are analyzing the tweeted text. That would be the third function.

def print_tweet_analysis(dataset):
    for row in dataset:
        console_out(analyze(row))

That would be your complete algorithm in three lines of code.
If you come in 10 years from now back to your code, you unterstand, what this script is about: it takes data, analyzes it and puts the result to the console.
If you want to know, what analyze means, you look at the function and will see.
The same goes for your analyze function. You could fine grain your logic into small pieces, each sitting on the top of the other and if you read the code, you drill down as far as necessary to understand the code and maybe finding later on bugs and fixing those.

Instead of using a dictionary for your algorithm, I would recommend namedtuple. You could easily define your analysis-tuple as

Analysis = namedtuple("Analysis", "word charcount longword title uppercase")

and return simply:

return Analysis(tweet, len(tweet), len(tweet)>7, tweet.istitle(), tweet.isupper())

And you are done.

If you wrote your code like this, everybody including future you would know, what this is all about.

One thing, I still do not understand is:

You are defining tweet as

tweet = re.split("\s+", n6.strip().lower())

iterating over it and checking for

tweet[i].isupper()

Am I overseeing something or does this make no sense only to me?


Method getXDifference and getYDifference are very similar, you can convert this into a single method that accepts two variables.
you could also inline the return statement as the method name is sufficient to tell what it is returning.
Instead of calculating pastX and pastY, you can write methods to return the computed value.

boolean isPastX(variables...){
    // logic to calculate pastX and return it.
}

and the if statement will turn into if( isPastX() && isPastY()).
This will also help in short-circuiting the condition in case calculating pastX or pastY is very expensive(it isn't in this example, just a suggestion).
Curly braces {} should always be used after conditional statements or loops, even it's just a single line. It may avoid confusion in some scenarios.

if (getPath().size == 0){
    return;
}


Instead of case x == true you can use boolean expressions directly,
and write simply:

case x:

The same regex is written twice here.
What's worse is that the pattern matching is also evaluated twice:

case match("^/hello/([^/]+)$", route) == true:
    var re = regexp.MustCompile("^/hello/([^/]+)$")

I'm not sure if there's an elegant solution for this situation in Go.
But at the minimum you could move the regex pattern into a variable to avoid typing it twice.

Another alternative is to create a matcher structure,
with a match function that will not only match a pattern and return a boolean,
but at the same time also store the sub-string you want to extract.

type matcher struct {
    value string
}

func (m *matcher) match(pattern string, route string) bool {
    var re = regexp.MustCompile(pattern)
    matches := re.FindStringSubmatch(route)
    if len(matches) < 2 {
        return false
    }

    m.value = matches[1]

    return true
}

With the help of this, you could rewrite the route function as:

func route(w http.ResponseWriter, r *http.Request) {
    route := r.URL.Path
    m := &matcher{}
    switch {
    case route == "/":
        home(w, r)
    case route == "/hello" && r.Method == "GET":
        hello(w, r)
    case m.match("^/hello/([^/]+)$", route):
        helloName(w, r, m.value)
    default:
        notFound(w, r)
    }
}


Global "variables"

I would not worry about global variables. Assuming that this code will be properly placed inside its own module, those would probably not be global anyway.

Use of parentheses

Some parentheses are superfluous. For example, the whole body of the second rotStr equation is enclosed in parentheses and those can be removed.
Regarding the other cases, you can probably avoid parens (and get slightly easier to digest code) if you define subexpressions in a let or where clause.

Argument parsing

I'm not sure what you mean by that. If you mean the getArgs part, that looks OK.

Here are some other notes about the code:

The rotStr 0 s = s line is superfluous. You can remove it and everything will work just fine. I assume it is just an optimization, so that's OK.
It might not be obvious for small inputs, but the performance of the code can be improved. Things like elemIndex c alnum and alnum !! run in linear time in the size of alnum. This means that the expression elem c alnum = alnum !! (mod (r + fromJust (elemIndex c alnum)) anlen) will go through the list 2 times. Again, this might not matter much, but you could use Data.Maps for lookup in order to get better performance.

Here's a possible implementation using Maps:

import Data.List
import Data.Maybe
import qualified Data.Map as M (Map, empty, insert, lookup)

alnum = ['A' .. 'Z'] ++ ['a' .. 'z'] ++ ['0' .. '9']
anlen = length alnum

indices = foldr add M.empty $ zip alnum [0..]
  where add (c, i) m = M.insert c i m

charsByIndex = foldr add M.empty $ zip alnum [0..]
  where add (c, i) m = M.insert i c m

rotChar :: Int -> Char -> Char
rotChar r c = case M.lookup c indices of
                   Just i  -> fromJust $ M.lookup (newIndex i) charsByIndex
                   Nothing -> c
              where newIndex i = (i+r) `mod` anlen

rotStr :: Int -> String -> String
rotStr r s = map (rotChar r) s

Also note that the last line can be reduced to:

rotStr = map . rotChar


Inputting multiple strings and finding their length

num_of_items = int(input("How many items in your list? "))

For one thing, what if the user typed alpha?  You would have a nasty error throwing itself at the user.  Why are you asking anyway?  You should be able to handle any number of items without asking.  Just keep asking input and printing output until the user decides to end with exit.  Even as it is, your item_list() function will print only the first four and if num_of_items is, say, three ... IndexError.

num_of_items ...
def item_list(x):
    ...

That's a little squooshed.  I would add at least one blank line and probably two between the num_of_items definition and the item_list() definition.  Well, actually I would put the num_of_items definition below the function definition.  Usually, constants are defined first; then functions and classes; then variables.

item = input("Enter list %r: " % (i+1))

% formatting is not officially deprecated, but it is preferred to use .format()

I wouldn't create a list of strings whose sole purpose is to be displayed to the user.  There are some things such as get_accuracy(user) where you might not use it elsewhere, but it makes sense to use it programmatically.  In this case, you are returning strings that couldn't be read by your program very easily.  Your item_list() function should not return strings that are formatted just for the reader.  It should return something that you can format however you like elsewhere.  My modified program looks like this:

def get_items():
    while True:
        item = input("Enter string: ")
        if item.lower() == "exit":
            raise StopIteration()
        yield item, len(item)

for item in get_items():
    print("The length of string '{0}' is {1}".format(*item))

get_items() is now a generator function that yields tuples of each item and its length.  Since it raises StopIteration when the user types exit, the for loop will stop.


this is my realloc version, is it good ? any suggestion are welcomed

#include <stddef.h>
#include <stdlib.h>

void    *ft_realloc(void *old_ptr, size_t old_size, size_t size) {
    if (size == 0 && old_ptr != NULL)
    {
        free (old_ptr);
    }
    else if (old_ptr == NULL)
    {
        if (old_ptr = malloc(size))
        {
            ft_memset(old_ptr, 0, size);
            return (old_ptr);
        }
    }
    else
    {
        void *new_ptr;
        if (new_ptr = malloc(size))
        {
            ft_memset(new_ptr, 0, size);

            if (size >= old_size)
                ft_strncpy (new_ptr, old_ptr, old_size);
            else
                ft_strncpy (new_ptr, old_ptr, size);

            free (old_ptr);
            return (new_ptr);
        }
    }
    return (NULL);
}

My insightful observation: OP's code has redundancies.
My answer: I removed some redundancies, which makes the code possible faster and easier to maintain.


Light weight C++ Signals/Slots or Event System

Sink arguments (objects we want to make a copy of and store internally) are generally passed by value, then moved into place, so the add function can take its parameter by value rather than const&.
We could perhaps make fp public with a name like Function, and use it for the add function parameter.
raise will make unnecessary copies of the arguments. We can avoid that with perfect forwarding.
We don't need to copy the weak_ptr in the raise lambda, we can use a const&. We also don't need to specify the return value.

.

#include <forward_list>
#include <functional>
#include <memory>

template <class... FuncArgs>
class Signal
{
public:

    using Function = std::function<void(FuncArgs...)>;
    using Listener = std::shared_ptr<Function>;

    Listener add(Function cb) {
        auto const result = std::make_shared<Function>(std::move(cb));
        listeners.push_front(result);
        return result;
    }

    template<class... Args>
    void raise(Args&&... args) {
        listeners.remove_if([&args...](std::weak_ptr<Function> const& e) {
            if (auto f = e.lock()) {
                (*f)(std::forward<Args>(args)...);
                return false;
            }
            return true;
        });
    }

private:

    std::forward_list<std::weak_ptr<Function>> listeners;
};

#include <iostream>

struct Noisy
{
    Noisy() = default;

    Noisy(Noisy const&) { std::cout << "copy\n"; }
    Noisy& operator=(Noisy const&) { std::cout << "copy assign\n"; return *this; }

    Noisy(Noisy&&) { std::cout << "move\n"; }
    Noisy& operator=(Noisy&&) { std::cout << "move assign\n"; return *this; }
};

int main()
{
    {
        auto s = Signal<int>();
        auto const l = s.add([] (int v) { std::cout << "value: " << v << std::endl; });
        s.raise(5);
    }
    {
        auto s = Signal<Noisy const&>();
        auto const l = s.add([] (Noisy const&) { });
        auto const n = Noisy();
        s.raise(n);
    }
}


Your code does loop 700 000 multiplied by 65 000 multiplied by the number of elements in each cluster. That is a lot of iterations, and not very useful.

The better approach would be to read the smaller file into memory, and then read the larger file line by line. In addition as you iterate over each row in the smaller file, matching each of the keys, it makes sense to switch from a dict with cluster as key, and the different keys as values, to actually using the keys as keys, and list all the clusters it belongs to.

This approach would leave the lower memory footprint, but should be rather efficient to work with. Here is some code to start you off with. You might need to adjust a little related to splitting on space or tabs, but I get your wanted output using this.

from collections import defaultdict

def build_cluster_dict(filename):
    """Return a dict of keys with all the cluster the key exists in."""

    result = defaultdict(list)
    with open(filename) as infile:
        for line  in infile:
            elements = line.strip().split()

            cluster = elements[0]
            for key in elements[1:]:
                result[key].append(cluster)

    return result

def build_output(cluster_dict, filename, output_filename):

    with open(filename) as infile, open(output_filename, 'w') as outfile:
        for line in infile:
            key, text = line.strip().split()

            if key in cluster_dict:
                for cluster in cluster_dict[key]:
                    outfile.write('{}\t{}\t{}\n'.format(cluster, key, text))

def main():

    cluster_dict = build_cluster_dict("cluster.txt")

    print (cluster_dict)

    build_output(cluster_dict, "file2.txt", "output.txt")

if __name__ == '__main__':
    main()

Note that I've left out the use of numpy, as I don't see the need for it in this context. I've also used a double with statement to open both the in- and out-file at the same time in the same context. I left the print (cluster_dict) in there just to see the intermediate list it generates. For your test files this gave the following output (somewhat formatted):

defaultdict(<type 'list'>,
            {'AA': ['CL1', 'CL2'],
             'SS': ['CL1'],
             'YY': ['CL1'],
             'XX': ['CL1'],
             '3_b': ['CL2'],
             'ZZ': ['CL1']})

Addendum: Locate erroneous input line

In comments OP said their was a problem in the key, text line, and to detect this these lines:

       for line in infile:
           key, text = line.strip().split()

can be replaced with:

        for line_number, line in enumerate(infile):
            try:
                key, text = line.strip().split()
            except ValueError:
                print("Error on line {}: {}".format(line_number, line))
                ## Option a) Use empty text
                #key = line.strip()
                #text = ""
                # Option b) Continue with next line
                continue

This code will catch the error situation, and as it stands it will display an error message with the offending line. I've set it to use option b), that is continue with next line. If you want to use an empty string and write the output to file file, uncomment option a), and comment out option b).


From top to bottom…

#include <stdio.h> appears to be left over from development, and can be removed.
swap() is not part of your library's interface, and should be declared static.
To give your library a sense of unity, I'd rename initState() → rc4InitState() and crypt() → rc4Crypt().  The latter renaming is also important so as not to clash with the traditional Unix crypt(3) function.  Also for consistency, I'd make Rc4State *state the first parameter of each function.
Assertions are not really an appropriate mechanism for parameter validation.  The use of assert() in initState() is marginal.  You should assert conditions that you know to be true, rather than conditions that you hope to be true.  Alternatively stated, assertion failures should arise from programmer errors, not user errors.

Change int keylen to uint8_t keylen, and most of the validation problem goes away anyway.  (In C, i % 0 has undefined behaviour.)
On the other hand, you could add an assert((byte)(S[i] + 256) == S[i]) to put to rest your concerns about overflow.
Calling crypt() to encrypt a byte at a time is inefficient.  The function should accept a byte array and length.  A compiler might inline a function, but if you're writing this as a library, the linker can't optimize away a function call.
*i and *j are a bit unconventional for my taste.  Here's how I would express it:

static byte rc4CryptByte(Rc4State *state, byte plainText)
{
    byte *S = state->S;
    byte i = ++(state->i);
    byte j = (state->j += S[i]);

    swap(&S[i], &S[j]);
    byte t = S[i] + S[j];
    byte k = S[t];

    return plainText ^ k;
}

void rc4Crypt(Rc4State *state, byte text[], size_t len)
{
    for (size_t i = 0; i < len; i++)
    {
        text[i] = rc4CryptByte(state, text[i]);
    }
}


Memory leak in Java's stack implementation

Memory leak

No, there's no memory leak in your program.
If you changed the underlying data type from int to an object type,
then you would have, loosely speaking, a memory leak in this method:

public int pop() {
    if(top == -1)
        throw new NoSuchElementException("Stack is empty.");
    int data = stack[top];
    top--;
    return data;
}

If stack was of type Object[], then the element you popped, would still be referenced. Even though it's no longer intended to be used, the popped element would stay referenced in there, until the array slot is overwritten. The remedy is simple, just null out the unused array slot:

public int pop() {
    if(top == -1)
        throw new NoSuchElementException("Stack is empty.");
    int data = stack[top];
    stack[top] = null;
    top--;
    return data;
}

This doesn't apply to your solution. There is nothing to "null out" (null is not a valid value for an int), there's nothing to be garbage collected.

And it would be a memory leak only loosely speaking. Due to the objects not garbage collected, you might experience reduced performance due to the increased memory footprint, and paging to disk (if you run out of memory).

Usability

You made the parameterless constructor private, and thus forbidden. At the minimum, you should add a comment to the constructor body to explain why it is forbidden.

And really, why is it forbidden? Users of this stack are forced to think about a suitable capacity, but very often there is no good way to anticipate the needed capacity, and then users will end up picking something arbitrary. Granted, anything that you pick will be arbitrary too, but at least you don't make your users think.

Supporting other types

Although your specs are asking to store int values, you could make your implementation work with any type, at negligible cost. So I urge you to do that. If the assignment requires a usage without type parameters, you could create a wrapper class that specializes on the desired type, for example:

class MyStack<T> {
    // ...
}

public class MyIntStack extends MyStack<Integer> {}

Another "cost" of course of the generalization is that you would have to watch out for memory leaks, and null out the popped element as explained earlier.


Reversing a string in-place - recursion or iteration?

First some clean-up is needed on your code. The iterative method first:

do not call System.out.println("iteration result: "+in); as this will do a toString() on in and you will get something like iteration result [C@b312fca6. Use the following instead:  System.out.println("iteration result: " + Arrays.toString(in));
start and end are not great names because, after the first loop, they no longer represent the start and end positions. Consider left and right as alternatives.
In this case, a double-value for loop is a good candidate for readability:

for (int left = 0, right=in.length - 1; left < right; left++, right--) {
    swap(left, right, in);
}

alternatively, a single value iteration could be useful:

for (int i = (in.length - 1) / 2; i >= 0; i--) {
    swap(i, in.length - 1 - i, in);
}

in the recursive call, you have some other problems:

The character array is passed in, and modified in place. There is no reason to return it as well. The method should return void.
you should simplify the condtitional statement to make the tail-recursion obvious... since the true part of the if condition returns from the method, there is no need for an else block
you should not be modifying the actual start and end values 'in place' as this requires some extra work. In the recursive call you can simply do start + 1 instead of ++start.
I prefer using the final keyword on recursive components to make sure you only modify what you should be....

Consider the recursive method:

    public static void reverseRecur(final char[] in, final int left, final int right) {
        if (left >= right) {
            return;
        }
        swap(left, right, in);
        reverseRecur(in, left + 1, right - 1);
    }

Now the 'tail' part is obvious.

As for whether tail-call optimization is performed, I don't know. I expect that the compiler may completely re-write this recursive function as an iteration..... which leads on to the next question: Which one is better?

In this case, the iterative solution is best. It has the least impact on resources (stack space), and will be fastest. It is also the most intuitive (readable).

Your iterative solution would be preferable


FileBulkLoad isn't an ideal name for a method - it's a noun, and nouns should be used for naming types - method names should be verbs, because they do something.

The fact that it's static is also worrying - less so than that static Helpers, but worrying nonetheless: you're coupling your application logic with a specific data access strategy, which means you have no way of writing a unit test for your application logic without actually hitting the database and, in this case, the file system.

Consider this alternative:

public interface IFilePersistenceService
{
    bool LoadFromDelimitedFile(string path, string separator, int columns);
}

Now you can implement this interface with a class that will use Helpers.BulkInsert with ADO.NET, or one that uses a UnitOfWork and Entity Framework, or NHibernate, or whatever: the point is that bulk insert is a mere implementation detail that the rest of your code doesn't need to care about - that's why having it in the method's name doesn't really bring anything to the table.

Your client code would be written against this IFilePersistenceService abstraction, and then you could inject a fake implementation of that interface into your application logic, and write tests that don't hit the file system or a database.

I said Helpers was worrisome; the name doesn't convey anything but "stuff that serves some purpose, somewhere" - after a while it becomes a dumping ground for any code that doesn't quite belong elsewhere, or for anything that you need to access from anywhere - and that's how spaghettification begins.

Consider killing that (static?) class, with fire.

The implementation itself isn't half bad: you are disposing of disposables, using using blocks - it doesn't get any better than that IMO.

The problem is at a higher level: you're returning true on success, false on failure - and once the client code knows the operation failed, it doesn't know anything about the failure, that was all swallowed by the called method.

I'd much rather return void and have code that either works or blows up.

The Boolean return value is more hurtful than anything, it's the client code that knows how to handle an exception (e.g. display a message to the user about a permission issue, or email tech support with exception details, whatever): it's the client code that should wrap this method call with a try/catch block. Or the method should log the exception details and then rethrow.

I would expect a "load" method to fetch data from a data source, and return that data to the application. Perhaps this would be more appropriate:

public interface IFilePersistenceService
{
    void ImportFile(string path, string separator, int columns);
}

Right? You're importing data into a database, from a file.


Updating single view on change of a model in backbone

First of all, Backbone views already have a cached version of $(this.el) in this.$el so you should use this.$el instead of $(this.el).

I find that things work better when views only touch their own el and leave it up to someone else to put that el into the DOM. In your case, that would mean that you shouldn't do this:

$('#showit').append($(this.el));

in the sub-view, it would be better to say:

render: function() {
    var output = this.template({'book':this.model.toJSON()});
    this.$el.html(output);
    return this; // <----------------- this is common behavior, you'll see why in a moment
}

and then in the parent view, you say this:

el: '#showit',
render: function() {
    this.collection.each(function(model) {
        var pustakView = new BookView({model: model});
        this.$el.append(pustakView.render().el);
    }, this);
    return this;
}

The parent adds the child using the child's new return value from render:

this.$el.append(pustakView.render().el);
// ---------------------------------^^

Also note the second argument to this.collection.each to make this inside the iterator function the parent view.

Now we don't need renderOne in BookView at all, you can bind render to the appropriate event. You can also leave the re-rendering up to Backbone. When you say this:

this.model.set({likes: ++likes_count});

you will trigger a 'change' event on this.model. If you bind to that in initialize:

initialize: function() {
    this.listenTo(this.model, 'change', this.render);
}

then Backbone will call render for you when the model changes.

Back to BookListView. A view's initialize will copy the collection property out of its options just like it will copy model:

  constructor / initialize new View([options])

  There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName, attributes and events.

so your BookListView should look more like this:

var BookListView = Backbone.View.extend({
    initialize: function() {
        this.render();
    },
    //...

and you should instantiate it like this:

var myBookList = new BookListView({ collection: myBookCollection });

Notice that I have removed collection: ... from the view declaration. The collection and model properties should be instances and they should be bound per-view-instance so you almost never want collection or model to appear when defining a view, you only want to see those in the view's argument list when you instantiate a view.

Furthermore, I notice that you're not using var to declare your variables. That means that you are creating accidental globals all over the place and that's never a good idea. Always use var to declare variables so that you can control the scope.


A minor remark: your test is named testCreateNotExistingEmail. The @Test annotation already indicates that this is a test so it doesn't have to be repeated in the methodname itself.

Adding to that: I like to structure my tests in the format [UnitOfWorkName]_[ScenarioUnderTest]_[ExpectedBehaviour].

It is hard to tell what exactly your test does when I look at the code because the methodname indicates something about a nonexisting email, which leads me to think about an exception handled somewhere.

But when I look at the code I see no assertions like that at all. In fact, I only see an email being used once in a seemingly irrelevant context.

Some type of clarification is needed: a better method name. Something along the lines of createUser_WithNonExistingEmail_ShouldReturn_StandardCitiesAndCategories

Now when the test fails amongst a big group of tests, you can pinpoint more closely what scenario is going wrong exactly before you dig into it.


Your allChunks is a List. The Linq query to get the chunk with the right coordinates is going to scan the entire list, and check each chunk. This is a linear process, and the performance depends on the number of chunks in the list. As the list grows, the performance decreases.

The solution is to index the chunks in a way that makes the lookup performance a constant-time operation (not dependant on the number of chunks).

The logical data structure for this is to use a Dictionary, and key the Dictionary on a value that is the coordinate. Thus, given a coordinate, you can easily find the Chunk.

Your chunks are indexed using int values for the X and Y coordinate. I would recommend using a long-value as the key, and to simply shift the X and Y coordinates in to the Dictionary... for example:

Dictionary<long, Chunks> indexChunks = ....

// merge both coordinates in to one unique key
// the y-coordinate is in the high-32-bits, the x-coord in the low 32 bits.
// this should probably be in a function.
long key = xChunk + ((long)yChunk << 32);

if (!indexChunks.containsKey(key)) {
    indexChunks.Add(key, new Chunks(.....));
}

Chunks currentChunk = indexChunks[key];

The Dictionary will convert the lookup process to a faster, scalable mechanism.

If you want to, you can create a more complicated key mechanism, but I would recommend that you keep the key as simple as possible.


I would not open a stream instead use IO.readlines and enum methods:

puts File.readlines("decimals.txt").reduce(0) { |total, line| total += line.chomp.to_i.to_s(2).count("1") }


Simply, in this case, there's no real reason to use the worksheet function if you're not putting the function into the cell.

Flawed Worksheet_Change structure
This here -

ActiveCol = Left(ActiveCell.EntireColumn.Address(False, False), InStr(1, ActiveCell.EntireColumn.Address(False, False), ":") - 1)

Only works on the worksheet change, so if you don't go directly to the next cell (vertically), you get the wrong column. Try it -
ActiveCol = Left(ActiveCell.EntireColumn.Address(False, False), InStr(1, ActiveCell.EntireColumn.Address(False, False), ":") - 1)
MsgBox ActiveCol

It's the column wherever the current cell is selected, since the change doesn't occur until you leave the cell, not where the target cell was. Not sure why you need the letter, so just get the column number -
ActiveCol = Target.Column
MsgBox ActiveCol

This works on your target that changed, not where your cursor ended up. Small, but important.
This also matters for your TabToTake using ActiveCell, are you sure you want to take the next cell's value, which best case scenario, will be on row 4?
That's why you pass Target into the function - to use it as a variable. I know that seems pretty obvious when I point it out, but I also know how confusing Target can be if you're just starting out, so don't sweat it.
If Not Intersect(Target, Rows(3)) Is Nothing Then
    targetSheet = Sheets(Target.Value)
    activeColumn = Target.Column

You haven't qualified everything -

For Each CellsCnt In Range("E4:E2500").Cells

I imagine that should be on the current sheet, but tell me that.

Let's break down the meat of your sub
Set ID = Sheets(TabToTake).Range("A:A")
Set Amount = Sheets(TabToTake).Range("Q:Q")
For Each CellsCnt In Range("E4:E2500").Cells
    If Not IsEmpty(CellsCnt) Then
        Cells(CellsCnt.Row, ActiveCol).Value = Application.WorksheetFunction.SumIfs(Amount, ID, Cells(CellsCnt.Row, "E").Value)
    End If
Next CellsCnt

First, For every cell in column E on targetSheet, if it isn't empty THEN
targetSheet, of that cell, in the ActiveCol (which is not target) =
Application.WorksheetFunction.SumIfs(targetSheet.Range("Q:Q"), targetSheet.Range("A:A"), ActiveSheet.Cells(CellsCnt.Row, 5)).Value

So what are we doing here, exactly.

Summing all of targetSheet.Columns("G") if all of targetSheet.Columns("A") = current cell. FOR ALL OF COLUMN E.

Assuming that a lot of column E changes when something in row 3 changes, you essentially do a sum of vlookups yeah? Hm, why do that so much? Not knowing how your cells are linked up in your sheet, makes it more difficult to really optimize this, but here's a try
Const LOOKUP_COLUMN As Long = 5
Const LOOK_IN_COLUMN As Long = 1
Const SUM_COLUMN As Long = 17
Dim lookupVector As Variant
Dim lookinVector As Variant
Dim sumVector As Variant
Dim lastRow As Long

lastRow = ActiveSheet.Cells(Rows.Count, LOOKUP_COLUMN).End(xlUp).Row
lookupVector = ActiveSheet.Range(Cells(4, LOOKUP_COLUMN), Cells(lastRow, LOOKUP_COLUMN))

lastRow = targetSheet.Cells(Rows.Count, LOOK_IN_COLUMN).End(xlUp).Row
lookinVector = targetSheet.Range(Cells(1, LOOK_IN_COLUMN), Cells(lastRow, LOOK_IN_COLUMN))
sumVector = targetSheet.Range(Cells(1, SUM_COLUMN), Cells(lastRow, SUM_COLUMN))

Now everything is in arrays and you can perform your calculations behind the scenes, much faster -
Dim resultVector() As Double
Dim result As Double
ReDim resultVector(LBound(lookupVector) To UBound(lookupVector))
Dim index As Long
Dim targetIndex As Long
For index = LBound(lookupVector) To UBound(lookupVector)
    result = 0
    For targetIndex = LBound(lookinVector) To UBound(lookinVector)
        If lookinVector(index) = lookupVector(index) Then result = result + sumVector(targetIndex)
    Next
    resultVector(index) = result
Next

Once you're done, you just put that resultVector back in your lookup_column.

Variables
Give your variables meaningful names. When I see Amount in code, I don't assume it's a Range I assume it's a Value. Make that clear, it's easier on future you. You can see my examples of changes in the code above.
Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names.

Dim ActiveCol

You didn't give this variable a type so it was declared as a variant. You don't need a variant, just a simple long.

Indenting
It's good practice to indent all of your code that way Labels will stick out as obvious.

Error Handling
This

On Error Resume Next

What error is that handling? What can go wrong? For instance, when you were using the selection instead of the target, you wouldn't see that it didn't do what it was supposed to do. Handle your errors specifically so you know what can go wrong, how it goes wrong and how to prevent it.

Working on the sheet
Working with the ranges instead of arrays - it just slows the code down by needing to fiddle with the spreadsheet while doing everything else behind the scenes. There's a good question on StackOverflow addressing this. The same logic applies here.

Comments
Comments - "code tell you how, comments tell you why". The code should speak for itself, if it needs a comment, it might need to be made more clear. If not, the comment should describe why you're doing something rather than how you're doing it. Here are a few reasons to avoid comments all together.

Dim Amount As Range 'the range i want to sum
Dim ID As Range 'criteria range
Dim Arg3 As Variant 'the criteria

You telling me in comments what ranges do what, that was your first indication that your naming could be improved, right?

Method
Like I said, I don't know the exact structure of your sheets, but maybe Worksheet_Change isn't the best way in which to do these calculations. Think about what changes and when it changes and see if there's a more efficient way to do it instead of every time there's a change.
Honestly, maybe your best bet is actually using the SUMIFS function, like
 =IFERROR("",SUMIFS(Sheet1!A1:A31,Sheet1!Q1:Q25,Sheet2!E7))


Consider removing tags with

sed 's/<[^>]*>/ /g'