Disable button when required inputs are not filled in

Sure you can DRYfy you code in several ways.

The most obvious point is that you're using 3 times the almost identical sequence of statements, so it should be factorized.

var isValid = true;
 $('input,textarea,select').filter('[required]:visible').each(function() {
  if ( $(this).val() === '' )
     isValid = false;
});
// then do something with "isValid"

Having isolated the sequence, we can already both simplify and improve its "core":

$(this).val() can be simpler and faster: this.value
but as pointed by @Tushar, it should be secured: this.value.trim();
on the other hand, yes we might stop looping as soon as false (returning false rather than with break;, since each() is not a loop), but there can never be a significative lot of inputs so personally I'll give up, for the sake of readability
and finally the whole condition $(this).val() === '' can be yet simplified: !this.value.trim()

Now it's time to look at how to really factorize, i.e. make this sequence usable each time we need it to work.

But at the same time we may also think about how to make it of more general use. The idea here is to be able to work independently (while automatically) upon all or some of several forms.
It may be achieved by wrapping the sequence in a handler:

fired on any input element
looking for valid state of all input elements in its own form

So the whole sequence becomes a function like this:

function checkForm() {
  // here, "this" is an input element
  var isValidForm = true;
  $(this.form).find(':input[required]:visible').each(function() {
    if (!this.value.trim()) {
      isValidForm = false;
    }
  });
  // then do something with "isValidForm"... not stated yet
}

At this step we must decide how to make this handler be launched.
It worth mention that change is not a good choice, because it fires only when the element value had changed AND the element lost focus.
So for example, based on a full valid form, if user empties a required input the submit button remains enabled till navigated to another element!

It's why I suggest using keyup event instead (nevertheless if checkboxes or radios should also be involved, you'll have to also use change event).

For the sake of simple usage, I suggest affecting a distinguishing class to the submit button of each form you want to be involved, say monitored-btn.
So the way to make monitoring active will be:

$('.monitored-btn').closest('form').find(':input[required]:visible').keyup(checkForm);

This way, we know that our handler will be fired each time an element value changes.
So it's time to add what we want the handler to do depending on the form state, so it becomes:

function checkForm() {
  // here, "this" is an input element
  var isValidForm = true;
  $(this.form).find(':input[required]:visible').each(function() {
    if (!this.value.trim()) {
      isValidForm = false;
    }
  });
  $(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
}

Now, each time an element value changes the involved submit button is enabled or not depending on the whole form state.
But when page was just loaded, the buttons are always all enabled regardless of anything else.
It's why we must immediately fire the handler as soon as it has been bound:

$('.monitored-btn').closest('form').find(':input[required]:visible')
  // bind the handler
  .keyup(checkForm)
  // immediately fire it to initialize buttons state
  .keyup();

Last point, regarding your care of user-hacking with Firebug (a bit strange, from my point of view, since if user can suppress the disabled attribute he can also do almost anything he wants, including directly submit through the console).

A simple way to also monitor that is to fire the same handler on form submit event, with two slight changes:

the handler expects this to be an input element, so we must call it like if it was a simple function (not a handler): checkForm.apply($(this).find(':input')[0]);
apart from enabling/desabling button, the handler should now return isValidForm, so we can use it to prevent defaut

It actually results in this final whole version:

function checkForm() {
  // here, "this" is an input element
  var isValidForm = true;
  $(this.form).find(':input[required]:visible').each(function() {
    if (!this.value.trim()) {
      isValidForm = false;
    }
  });
  $(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
  return isValidForm;
}

$('.monitored-btn').closest('form')
  // indirectly bind the handler to form
  .submit(function() {
    return checkForm.apply($(this).find(':input')[0]);
  })
  // look for input elements
  .find(':input[required]:visible')
  // bind the handler to input elements
  .keyup(checkForm)
  // immediately fire it to initialize buttons state
  .keyup();

Here is a working example where I used two forms with distinct "required" exigences:

const inputSelector = ':input[required]:visible';
function checkForm() {
  // here, "this" is an input element
  var isValidForm = true;
  $(this.form).find(inputSelector).each(function() {
    if (!this.value.trim()) {
      isValidForm = false;
    }
  });
  $(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
  return isValidForm;
}
$('.monitored-btn').closest('form')
  // in a user hacked to remove "disabled" attribute, also monitor the submit event
  .submit(function() {
    // launch checkForm for the first encountered input,
    // use its return value to prevent default if form is not valid
    return checkForm.apply($(this).find(':input')[0]);
  })
  .find(inputSelector).keyup(checkForm).keyup();
form {
  border: 1px solid #000;
  margin: 10px;
}

  <form action="#myForm">
         Name * <input name="myForm-name1" placeholder="required" required>

         Surname * <input name="myForm-surname" placeholder="required" required>

         Age <input name="myForm-surname" placeholder="not-required">

         <button id="myForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
  </form>
  <form action="#otherForm">
         Name * <input name="otherForm-name1" placeholder="required" required>

         Surname * <input name="otherForm-surname" placeholder="not-required">

         Age <input name="otherForm-surname" placeholder="required" required>

         <button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
  </form>


Code Improvement/Insight: Should I have approached these functions differently? Animations using Javascript

You can reduce this code down to one function by using default arguments.

function ani(p, reverse=false){
    let element = p.target.id;
    let scale = 2;
    if (reverse)
        scale = 1;
    anime({
        targets: '#'+ element,
        scale: scale,
    })
    return element;
}

Also, don't forget your semicolons ;-P


You want Replace Conditional with Polymorphism : "Move each leg of the conditional to an overriding method in a subclass. Make the original method abstract."

Your conditional from the example could then look like this :

digPosition.startDig()

digPosition being an instance of an interface DigPosition which has three implementations : BottomDigPosition, RightDigPosition and LeftDigPosition.


CreateView set foreign key from URL parameter

There's no need to add the ipsum instance to the template context unless it's used in the template. Adding things to self is the cleanest way.

Using get_object_or_404 is appropriate if we require the ipsum instance to exist in order to save a lorem.

You should end up with something like this:

# urls.py

from django.urls import path

urlpatterns = [
    path('lorem/create/ipsum/<int:ipsum_id>/', LoremCreateView.as_view(), name='create'),
]

# views.py

class LoremCreateView(CreateView):
    model = Lorem

    def dispatch(self, request, *args, **kwargs):
        """
        Overridden so we can make sure the `Ipsum` instance exists
        before going any further.
        """
        self.ipsum = get_object_or_404(Ipsum, pk=kwargs['ipsum_id'])
        return super().dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        """
        Overridden to add the ipsum relation to the `Lorem` instance.
        """
        form.instance.ipsum = self.ipsum
        return super().form_valid(form)


I'll propose an alternate implementation, because dictionaries are good at storing key-value pairs and you don't care about the value:
def first_duplicate(given_list):
    seen = set()
    for value in given_list:
        if value in seen:
            return value
        seen.add(value)
    return -1

A set will buy you basically the same behaviour as the "keys of a dictionary" for these purposes.


Assert

I personally dislike using asserts. The problem for me is that they do different things in production and debug code. I want the same action in both.

  pos_type seekpos(pos_type const pos, ::std::ios_base::openmode const which) final
  {
    switch (which)
    {
      case ::std::ios_base::in:
      case ::std::ios_base::out:
      default:
        assert(0);
    }

    return pos_type(off_type(-1));
  }

So in this code if we get to the default action; the debug version will assert (and stop the application) while production code will return -1.

In my opinion if you get to a point where your code should not then throw an exception that should not be caught. That will cause the application to exit (in a controlled way).

But in this case I think the expected behavior is not to throw but to return -1. So I would make the default action a no-op.

seekpos which

The which in your seekpos() has basically three settings. You only check for two of the three.

    switch (which)
    {
      case ::std::ios_base::in:
      case ::std::ios_base::out:

      // You forgot this case
      case ::std::ios_base::in | ::std::ios_base::out:

      // it means set the position of the input and output stream.
      // since this is the default value of `which` I would expect
      // this to happen most often (and would assert in your code).

      default:
        assert(0);
    }

    return pos_type(off_type(-1));
  }

xsgetn/xsputn eof

I think you return result of these functions can be incorrect. You should only return eof if you did not get/put any values. You return eof if you have filled/emptied all the data.

  ::std::streamsize xsgetn(char_type* const s,
    ::std::streamsize const count) final
  {
    // If there is no data to get then return eof
    if (egptr() == gptr()) {
        traits_type::eof();
    }

    auto const size(::std::min(egptr() - gptr(), count));

    ::std::memcpy(s, gptr(), size);

    gbump(size);

    return size; // return the number of bytes read.
  }

Overall Design

The input and output use the same buffer but are not linked together. If you have not written anything into the buffer I would not expect you to be able to read from the buffer (as there is nothing to read).

When you do write I would only expect you to be able to read only what has written (no more).

int main()
{
    memstream<1024>   buffer;

    if (buffer.write("abcdef", 6))
    {
         std::cout << "Write OK\n";
    }

    char data[100];
    if (buffer.read(data, 10))
    {
        auto c = buffer.gcount();

        std::cout << "Count: " << c << "\n";
        std::cout << std::string(data, data+10) << "\n";
    }
}

Result:

Write OK
Count: 10
abcdef

So I wrote 6 characters. But I managed to read 10 characters. What were the last 4 characters?

Circular Buffer

Once you have linked the two buffers correctly. You could get more from the buffer by making it circular. That means as you get to the end of the write buffer you can circle around and start writing at the beginning again if you have been reading from the buffer and there is space.

Inheriting from the buffer

template <::std::size_t N = 1024>
class memstream :
  public memstreambuf<N>,    // This is unusual
  public ::std::istream,
  public ::std::ostream
{
public:
  memstream() : ::std::istream(this),
    ::std::ostream(this)
  {
  }
};

Normally I have seen this as a member object rather than inheriting from the buffer. Though this technique saves a call to setbuffer. I can live with it.

BUT: if you are going to inherit from it then I would use private inheritance.

template <::std::size_t N = 1024>
class memstream :
  private memstreambuf<N>,    // Note the private
  public ::std::istream,
  public ::std::ostream
{
public:
  memstream() : ::std::istream(this),
    ::std::ostream(this)
  {
  }
};

This is because I don't want my object to behave like a stream and a stream buffer to people who use it. That could be confusing. So hide the buffer properties from external users (by using private). They can always get a reference to the buffer using the method rdbuf().

pragma once and include guards

There is no point in using both:

#ifndef MEMSTREAMBUF_HPP
# define MEMSTREAMBUF_HPP
# pragma once

....

#endif

I would use the header guards because not all compiler support #pragma once.

Note the space between # and the word is non standard. Most compilers may be forgiving about it but not all so I would not do it.

# define MEMSTREAMBUF_HPP
 ^  // extra space.


Modularized program to find circumference, diameter, and area from a circle's radius

Many little comments here to make things simpler,shorter,more pythonic :

PEP 0008 gives some coding guidelines for python. Among other things, it gives a naming convention. Also, you don't need the "my" prefix everywhere.
You can use math.pi instead of repeating our own definition of pi everywhere. (Isn't it the reason why your import math in the first place)
Most of your function just need to return a value and updating the parameter probably shouldn't be their responsability.
Most of the variables are not really required.
there's no point to define a main function in your case.

After taking these comments into accounts, your code looks like this :

import math

def get_radius_from_user():
    return float(input("Enter your radius: "))

def get_diameter(radius):
    return radius * 2

def get_circumference(radius):
    return 2 * math.pi * radius

def get_area(radius):
    return math.pi * radius * radius

def show_results(radius):
    print("The Diameter is",get_diameter(radius))
    print("The Circumference is",get_circumference(radius))
    print("The Area is",get_area(radius))

show_results(get_radius_from_user())


Returning result and error status for number type conversions

I don't like the idea of using an all-in-one struct. You will have to do more maintenance: every time you create a function that returns different values, you have to create a new struct.

Further, I think the struct return value will confuse the user. Everyone is familiar with the basic types, so they will immediately know how to use a function just from it's signature. When you introduce non-opaque structs, the user also has to look up the documentation for that, on top of the documentation for the actual function.

Think about when a function has a multiple value result - you can't give meaningful names to the two members without creating a new struct for every function (even with the same types).

e_two_doubles_type ret = get_two_doubles();
// Was it ret.retval1 or ret.retval2 that I nedded?

My preferred way to signal status is to return a constant #defined in a header. For an example look at the API of SQLite. It's a library I've used in projects, and it has worked really well. I also use this pattern for my own code. The results of the functions are returned through pointer parameters. This strategy is simple and will feel intuitive to users since it's so common.

int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);

The standard C library uses a "global variable" for error status. It is nowadays actually a macro, because globals simply aren't thread safe. If you want your API to be able to be used by multiple threads at the same time, global state is a no-no. There is no way to know which call generated the error code if you can't know the exact order of operations. I fear implementing your own errno as a thread-local macro will be more trouble than it's worth.

  Originally this was a static memory location, but macros are almost always used today to allow for multi-threading, such that each thread will see its own error number. (Wikipedia)

When re-reading your question I think you might have meant to use the actual errno global. This is feasible, but might surprise users. Normally, errno is only ever used by the standard library. I've seen one system implement their own version, but I don't see any advantages over returning the value directly.

The "return special value" approach can work in some cases. You need a value that is not a valid result, and must thus either artificially limit the domain of the function, or use a wider type than otherwise necessary. The obvious case is the NULL pointer, which is handy if there is only a single type of error, or if you don't need to know why the call failed.

"Pass address of error status" is similar to my proposed solution, it's just the other way around. The problem with this is that you can only return one value. There will only ever be one status, in contrast to results, so why not return the status instead?

You mention keeping status and result together. I don't agree with this goal, they are very different things and should be kept apart. The status is needed right after the call, but the result could live on for the rest of the program. Tightly coupling these will make continued use of the result awkward.

Consistency is key to making a great API. Make the user feel at home when using it, let their presumptions about your function's signatures be right. To achieve this, you need a consistent way to return status and results of functions. That's where "return status, reference results" shines, because it can be adapted to all situations - no matter how many results or of what types, the same basic principle is there.

When it comes to the status values themselves, you've pointed out two, and I've mentioned one approach above.

I don't like the idea of reusing standard errno values. Those values are specialised for system calls and most values probably won't be usable by your API. Here is a chart of values defined for several platforms. Note that different constants are available for different platforms. Imagine for instance that you want to use EMSGSIZE (Message too long). This would work fine for all platforms except for Microsoft's compiler (MSVC). Now you need to check for #ifdef _WIN32 and define it yourself. This is even more work than just coming up with your own suite of constants.

Extending the standard values is also bad. What if a platform you didn't think of has used this identifier already? Your library and this platform will be incompatible until you change it. Always try to avoid clashing with platforms, even if you don't think you want to support it today.

  Names beginning with a capital ‘E’ followed a digit or uppercase letter may be used for additional error code names. (GNU libc manual)

Further, errno values are not very readable. Their names are dense and hard to remember. I think EACCES is a great example, or rather a horrific one. They've intentionally misspelled "access" - that has thrown me off a couple of times.

Now we've ruled out that one, there are two left. You've decided to create your own constants, but should they be #defined enum-erated? I think both are good choices, but I'll go over the pros and cons of them below.

With macros, you have to specify each value by hand. This is both a strength and a weakness. It's dangerous because you can mistakenly #define two macros to the same value, without any compile time errors or warnings (I tried this with gcc -Wall). In effect, this bug can be hard to find.

#define LIB_OUT_OF_RANGE   86723
#define LIB_INVALID_STRING 86723

int status = string_to_double(str, &dbl);

if (status == LIB_OUT_OF_RANGE)
    fprintf(stderr, "Too large, try again\n");
else if (status == LIB_INVALID_STRING)
    fprintf(stderr, "Please input a number\n");

The second if-statement will never ever be executed, because LIB_OUT_OF_RANGE == LIB_INVALID_STRING. The compiler will probably even optimize the second if statement away.

The advantage is that you will always know what value a certain constant has, as opposed to enum constants. Try counting all prior constants to get the value in an enum with 50+ values.

Knowing the values is useful for debugging and logging: you can just print %d the values and check them against your header.

If you decide to go with enums, there are three different ways to do it. They are list below in order of transparency.

enum { ... };
int function();

enum lib_error { ... );
enum lib_error function();

typedef enum { ... } lib_error;
lib_error function();

I like to be upfront with what the user is getting. The enum/typedef is explicit with how values of them are to be interpreted, but not with the underlying type. I like to know what's an int and what's something else, but you might differ. I think any of these are fine.

In summary, use either macros or enums. Both are fine and each have their pros and cons.

PS. If you want to read up on a nifty way to pair integer constants with their string representation, check out this article on X Macros.


Negating an argument is somewhat counterintuitive. Consider passing them as multicast and local instead.

I would seriously consider defining
  UNIVERSAL = 0x01
  MULTICAST = 0x02

and pass them as a single argument, is in
      random_mac(UNIVERSAL | MULTICAST)

Using both randint and randrange feels odd. I would stick with randrange.

First octet needs a special treatment anyway. That said, consider
  def random_mac(special_bits = 0):
      octets = [randrange(OCTET_VALUE) for _ in range(N_MAC_OCTETS)]
      octets[0] = fix_octet(octet[0], special_bits)
      return ":".join(f"{octet:02X}" for octet in octets)

with
  def fix_octet(octet, special_bits):
      return (octet & ~0x03) | special_bits


I don't like how you've mixed the concerns of calculating with output. I know that right now you only want to output to a file, but what if you decide later that you want to work with this data in some other program? Writing to the file system is expensive and slow. Why write to a file and then read it back in.

I would modify this to be in two parts. One to generate the names from the dictionary and one that uses that class to output to a file. This leaves things open to writing the output to Standard IO, some other UI, or for another program to simply work with the data. The idea is that each class should do one thing and do it well.

On this note, each of your comments indicates a missed opportunity to extract a well named method that does one and only one thing.

#Parsing the commandline arguments and suchlike
syllable_separator = (/-d./ === ARGV[-1]) ? ARGV.pop[2..-1] : ''
name_count = (/\d+/ === ARGV[-1]) ? ARGV.pop.to_i : DEFAULT_NAME_COUNT
file = ARGV.join ' '

This is just begging to be a method called parse_cmd_args. It should return some object that represents those three values in some sensible and well named way.

I apologize that I've left s critique without any code examples. Normally I would provide some, but it's been a while since I've written any Ruby. It's better in this case that I leave you to attempt a clean up yourself.

Try to:

Write methods that do one and only one thing.
Create useful abstractions by the way of classes, even if they're just simple data structures to hold information.
Add some vertical whitespace around logic that's too trivial or too intertwined to be its own method.


1

I would declare <E extends Comparable> void sort(ArrayList<E> arr) as <E extends Comparable<? super E>> void sort(ArrayList<E> arr)

2

void sort(int left, int right, ArrayList<E> arr) {
    ...
}

I suggest you make it public and reorganize the arguments like this:

void sort(ArrayList<E> arr, int fromIndex, int toIndex)

where fromIndex corresponds to left in your version, and toIndex corresponds to right + 1: these are the conventions in JDK's sort algorithms, so that toIndex is an exclusive upper bound.

3

I would make the three-parameter version public since sometimes people want to sort only a subrange of an array (or ArrayList in our case).

4

Declare the constructor as private:

private Quicksort() {}

Hope that helps.


Extracting watermark from a video using Python

Best practices

A collection of general best practices for Python code can be found in the infamous Style Guide for Python Code (also called PEP8). While your code looks quite reasonable, there a two major points from the Style Guide I would like to point out to you.
First, add documentation to your functions (and maybe choose a more descriptive name than main, more on that shortly). Future-you will be very grateful for this.
Second, always use a single whitespace before and after = when assigning to a variable (no whitespace if used as keyword arguments in a function ! Relevant section of PEP8 here). The code is also generally better to read if you add a trailing whitespace after , like so: main(obr1, obr2) instead of main(obr1,obr2).

Another thing that I would consider a Python best practice, is to wrap code that is to be executed in a "scripty" manner in a if __name__ == "__main__": clause (also see the official documentation on that topic). That would allow you reuse/import the function currently named main into other functions without running the while loop. Therefore, I would like to suggest the following coarse code-level structure:

# imports would go here ...

def compare_images(filename1, filename2):
    """Compare two images and store the comparison to file"""
    # function logic would go here

def main():
    """Process arguments from command line"""
    imglist = sys.argv[1:]
    z = 0
    while imglist != []:
        # ...

if __name__ == "__main__":
    main()

I would also recommend to give some of the variables a more descriptive name (what do obr1 and obr2 stand for?). Also keep in mind that most of the people reading your code (including me) do not speak your mother tongue, so it's always nice to translate console output to English before posting it here.

Efficiency

.load() should probably not be necessary as per the documentation (this assumes your actually using Pillow fork and not the old and crusty PIL).

The most striking point in terms of efficiency is that Python is often terribly slow at loops. So the easiest way to gain performance is to get rid of them. But how? NumPy to the rescue! NumPy does all those pesky loops in C and is therefore orders of magnitudes faster compared to looping over array data in Python "by hand".

So what you would generally do to benefit from this is to get your image data as NumPy array (see this SO answer for a hint) and then work on those NumPy arrays with array operations, like masking. I will try to convey what I mean by that in a short example, maybe I can fully adapt it to your example later.

im1_np = ... # get data as numpy array, see SO post
im2_np = ... # get data as numpy array, see SO post
result = np.zeros_like(im1_np)   # same dtype and shape as input
matching_pixels = im1_np == im2_np   # boolean mask with true where pixels match exactly
result[matching_pixels] = im1_np[matching_pixels]   # this is your if clause

As you can see, there a no "manual" loops involved, everything is done by NumPy in the background.

Now to the else path. First, I think there might be some errors here, feel free to comment if I'm wrong. What (I think) you basically want to do, is to compute the difference between corresponding pixels and set them to a certain color if they are below a given threshold. Mathematically this would be expressed similar to this:

$$ \sqrt{(r_1-r_2)^2 + (g_1-g_2)^2 + (b_1-b_2)^2} < 200 $$

Your code does the following at the moment:

$$ \sqrt{r_1^2 + r_2^2 + g_1^2+g_2^2 + b_1^2+b_2^2} < 200 $$

When working from my definition above, the code becomes as follows:

dist_mask = np.sum(im1_np-im2_np, axis=2) < threshold
# remove pixels already set in the if clause
dist_mask = np.logical_and(dist_mask, np.logical_not(matching_pixels))
# remove all-zero pixels
dist_mask = np.logical_and(dist_mask, np.sum(im1_np, axis=2) > 0)
dist_mask = np.logical_and(dist_mask, np.sum(im2_np, axis=2) > 0)
# set color in result image as mean of both source pixels
result[dist_mask] = (im1_np[dist_mask]+im2_np[dist_mask]) / 2.

I leave threshold as variable since I'm not sure your original computation works the way you expect it and the threshold as chosen by you is meaningful. (Note: You can simply leave out the sqrt if you square the threshold value).
Apart from that, the code is a relatively strict transformation of your original conditions, it's just that instead of looping over the images pixel by pixel, everything is done in array operations.

Under the assumption that you actually want to assign the average pixel value of both source images, this can be optimized further, since the if condition of exact pixel equality is a subset of distance < threshold. This would save you a mask computation (matching_pixels would not be needed anymore) and the negation/and operation with the dist_mask. In case of exact equality, summing both values and dividing them by two should leave you with the original value (Warning: Watch out for quirks with floating point values and/or range-limited integer values).

To be fully compatible with your original code you would then have to go back to PIL to store the image to disk. This should also be described in the SO post linked above.

Other things

You are sometimes using string formatting in a weird way. If you just want make sure that a variable is a string, pass it to str(...) instead of using string formatting. If you really need string formatting such as where you create the output filename, it is often recommended to use .format(...) (Python 2, Python 3) or f-strings (Python 3) to format string output. There is a nice blog post here that compares all ways of doing string formatting in Python I mentioned.


This is a very interesting task. Good work on doing it. Here are some criticism.

print('If your integer is a negative, the script will ask.')
print("DO NOT GIVE -X integers for input!!!")
print('Script will output multiple - symbols for a negative integer transformation')

Do not use both double quote
("") and single quote ('') strings. Pick one. I personally prefer "".

while 0 == 0:
  ask = input('Enter an integer from a subset-sum instance sequentially.')

It's considered a best practice to indent using 4 spaces instead of 2.
Also it would be better to move actual transform functionality to a new function.
Also it's better to use while True instead of while 0 == 0 to indicate a endless loop.

Reason: This is more readable.

  askStr = str(ask)
  res = list(map(int, str(askStr))

You are converting ask twice to a string. This is redundant.
Since input() returns a string you don't need to convert this at all.
It is also a better to use python conventions for names. Ex: ask_str or value

  x = (res)

You don't need parenthesis here.
There is also no need to assign to x you can directly use res.

  if asktwo == str("y"):
     twinkle = str('-')
  else:
     twinkle = str(" ")

You don't need to convert a string literal to a string again.
You can directly use "y" as a string.
twinkle is not a good name. Use something like sign.


HTML form enable one list of options or another

Possible problem of the current solution

If you check one of the checkboxes, it gets activated and the select-element becomes enabled. If you click the same checkbox again, you only uncheck it, but the select-element stays enabled. I'd say there are two possibilities here:

disable the select-element as well
don't let the user uncheck the input-element

In the following examples I went with the first option.
As requested in the comments, I've updated the review to work for the second option.

Reduce the number of DOM queries and cache selectors

You didn't say how many of those groups are present or how often a user is going to make this decision. But you do a lot of the same DOM queries in your event handler over and over again.

At first let's store the "group-selector" in a string, to make it re-usebale. Then select all groups:

const selector = '[data-form-group]';
const groups = $(selector);

You can stick to classes if you like. I tend to use data-*-attributes to couple JavaScript.

As we also often need the input- and the select-element in each group, let's store them as well:

groups.each(function() {
    const group = $(this);
    group.data('checkbox', group.find('input'));
    group.data('select', group.find('select'));
});

Now we can access the form elements anytime, without re-querying the DOM.

The actual event handler

Attach the event handler to each input-element, the checkboxes radio-buttons. Then test, whether the current group is "enabled", i.e. the input-element is checked:

If it is checked already

do nothing and simply return

If it is not checked

enable the select-element
run through all other groups and disable them

The final code could look like this:

const selector = '[data-form-group]';
const groups = $(selector);

groups.each(function() {
  const group = $(this);
  group.data('toggle', group.find('input'));
  group.data('options', group.find('select'));

  group.data('toggle').on('change', function() {
    const selectedGroup = $(this).closest(selector);

    if (!selectedGroup.data('toggle').is(':checked')) {
      return;
    }

    selectedGroup.data('options').prop('disabled', false);

    groups.each(function() {
      const current = $(this);

      if (selectedGroup[0] === current[0]) {
        return;
      }

      current.data('toggle').prop('checked', false);
      current.data('options').prop('disabled', true);
    });
  });
});

Try it yourself


You should abstract the code to avoid duplication. Also, use a counter with O(n) performance:

module Enumerable # or require 'facets/enumerable/frequency'
  def frequency
    each_with_object(Hash.new(0)) { |item, counter| counter[item] += 1 }
  end
end

def anagrams?(s1, s2)
  frequency = proc { |s| s.gsub(/\s+/, "").downcase.chars.frequency }
  frequency.(s1) == frequency.(s2)
end

if ARGV.size != 2
  $stderr.puts("Need two words")
  exit(1)
elsif anagrams?(*ARGV)
  puts("Anagrams")
else
  puts("Not anagrams")
end


Time Limit Exceeded for CodeChef Easy problem - STRQ (Chef and Strings)

Here is an efficient algorithm that requires O(n) time for initialization and O(1) time per query.

Let's fix a pair (start letter, end letter)(there are only 12 such combinations).
Now we can precompute the following value: count(len) - the number of strings that start with the start letter, end with the end letter and are located inside the prefix of length len. Here is a pseudo that does it:

for start_letter <- letters:
    for end_letter <- letters:
        if start_letter != end_letter:
            start_letter_count = 0
            strings_count = 0
            for i <- 0 ... s.lenght() - 1:
                if s[i] == start_letter:
                    start_letters_count++
                else if s[i] == end_letter:
                    strings_count += start_letters_count
                count(i, start_letter, end_letter) = strings_count

The answer to a (left, right, start_letter, end_letter) is
count(right, start_letter, end_letter) - count(left - 1, start_letter, end_letter) - count_letter(left, right, end_letter) * count_letter(0, left - 1, start_letter), where count_letter(left, right, c) is the number of occurrences of a char c between left and right inclusively(it can be done in O(1) time with O(n) preprocessing using prefix sums).  Why does this formula work?
We can take all string that end before right. Now we need to subtract the number of strings that end before left. We also should subtract the number of such strings that start before left but end between left and right.

The time complexity is O(n + q) because we traverse the given string once for each pair of start and end letters, and then we use one formula that is computed in O(1) to answer each query.


If you care about performance, you should have a look at LPeg. It makes it way easier to handle large numbers of string matching and substitution rules.

For example, you could define patterns and their substitution values like this:

local lpeg = require 'lpeg'

local p = lpeg.P
local bad_word =
   p"bad" / "good" +
   (p"dumb" + p"stupid") / "$#&*"

local sanitize = lpeg.Cs( (bad_word + p(1))^1 )

print(sanitize:match("this is a bad word"))
print(sanitize:match("python is dumb!"))

Which makes it much easier both to add new entries and to eventually move them into a table or even a separate file.


I'm not sure why this is async.

Unless you have a good reason for write to the file asynchronously, this is wasted effort.

If you lock properly, this will work fine.  Your locker variable should be marked static.  You can then get away with something like this:

using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace test
{
    public class Writer
    {
        public string Filepath { get; set; }
        private static object locker = new Object();

        public void WriteToFile(StringBuilder text)
        {
            lock (locker)
            {
                using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read))
                using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))
                {
                    writer.Write(text.ToString());
                }
            }

        }
    }
}

This assumes you don't have some other reason for making this async.


If I were Alice, the most optimum strategy, well, there are two. The binary search, or in Python is the bisection method, or I would use the Fibonacci method, which is mathematically superior and faster than the binary search method.

Anyway, that would be what Alice would have to do to get to the number in the least number of guesses.

Bob, on the other hand, should make the number a floating point, say with four of five decimal places. Your original question did not state either integer or floating point.

Trying to guess a floating point number is harder. Try to figure out what the \$\sqrt{32}\$ is. It is not an even square, so in math, without a program or calculator, you really need to use the brute force method. However, unlike guessing a number between 1 to 200, here you can get a good starting point.

You know the number has to be between the \$\sqrt{25} = 5\$ and \$\sqrt{36} = 6\$. Since 32 is close to the midpoint, you can start at 5.5 (\$5.5^2 = 30.25\$), which still makes it difficult, as you will need to go to at least 4 decimal places for the right answer (\$\sqrt{32} = 5.6569\$).

Bob's strategy will be to make sure the number has some decimal places in it.

This way, Alice may use the binary or Fibonacci method to get to the integer, but will have to start over for the decimal places. She can get to it quick enough, but not as quickly as with just an integer.

Now Alice, if she knows the number can be a floating point, may want to start her guesses with a .5 or .25 at the end of every number. This will shorten the guesses for when she gets \$5.25 \gt i\$, but \$5.5 \lt i\$.

You can find the Fibonacci method and algorithm here. I could not find a corresponding Python function, but it is similar to the binary search, except you use just the Fibonacci numbers to narrow down your search.

What I was going to say about Bob picking a fractional number (floating point) instead of just an integer, he doesn't have to lie when Alice guesses 5 and Bob says GT and when she says 6 he says LT. Now it is up to Alice to realize she's dealing in decimals.

Bob maximizes his chances by using decimals. However, if Alice suspects this, she can always start off with a .5 or .25 at the end of every number. She can still minimize her guesses this way, as she needs to get to the integer first. With adding a decimal to it, she has a head start at guessing the decimal number.

Edited on 2/8/2017:
I though more about your question and about looking at how, if I were Bob, I could optimize my chances to maximize my costs without violating bullet point #2.

Besides using decimals, or even if just using integers, Bob could give more details that would not only be true, it could be misleading Alice as well.

Let's say Bob picks 30 as his number, and Alice starts her guess with 100, the midpoint in a Binary search pattern.

If Bob believes that she is using this, instead of saying her guess was greater than the number, he could say it is greater than by at least 10! This is not a lie, but if Alice decides to stick to the Binary search, it Change her next mid-point guess.

Instead of guessing 50, which she would if he had just said her guess was greater than, she knows his number is between 1 and 90. Instead, she guesses 45.

You may think that oh, no, she's actually closer, but it now all depends on what Bob now says. He has a choice, but what ever he says next will in no way be in conflict nor even contradict what he has said before. And can increase the number of guesses she makes, which is his goal.

If I were Bob, I would want Alice to make her next guess far enough away from his number that her third choice will be what optimizes his chances.

Bob can say, Guess is greater than. He's not obligated to say anything more and in no way is in conflict with what he as said so far.

Now is where Alice is on the hook. She has to guess a number between 1 and 44.

If she just got the GT or LT answers, her guesses would be 100, 50, 25.

Now she, if she sticks with the binary method, has to go with 22, and that is 3 away from her normal guess of 25.

Now, if you can see how this plays out, Bob can say her guess is less than, and see if he gets her to make more guesses if he adds to what he says.

This is a simplistic approach, but with some more thought, Bob could probably anticipate this, find the right number that would be far enough away to cause Alice to make one or more guesses than she would normally have. Becaus there will come a time where she will guess in increments of one, and Bob needs her to have extra guesses due to his word manipulation.

Without working on a formula and computer program, which I can do, I could show how this would play out and find that one or more magic numbers, probably a prime number (just a guess right now but sounds logical) that will increase Alice's cost and optimizes Bob's costs.

Let me know if this does it for you, or if anyone else has improvements on or another way Bob can perform his optimization.

Let me know if you want me to work on a program.

Edited on 02/17/2017: My original formula in the comments was just a starting point. It failed when a second or more guess was given.

After writing a few formulas into a computer program and executing them, along with manual calculaton, the following formula shows that no matter what answer Bob gives, there is always a relationship given to Alice between his chosen number and her guess.

And while Alice may not be able to use this formula to get the answer quickly, according to the rules set in the question, there is no misunderstanding of the rules, which states that Bob can give any answer as long as it does not conflict with any others given prior.

I believe that I demonstrated that in word/pseudo form that by giving Alice not only a GT/LT/EQ answer, he can add a hint that minimizes his payout, and still gives Alice a truthful answer.

In addition, if Bob qualifies his answer by saying "your guess is at least 30 greater than," if Alice was to guess a number that was 35 less than her last one, and it is still greater than Bob's number, Bob would not be in conflict if he said Alice's second guess was still greater than. The reason is he said "at least." That could mean his number is 100 less than Alice's guess. There is no conflict there, as Alice should be familiar with Number Theory and even Mathematical Logic.

Regardless of Bob's number of Alice's guess, I have come up with this formula that will always show that Bob always gives the relationship to his number based on Alice's guess.

It is expressed as (Total Numbers - Bob's Number - Bob's misdirection) is equal to (Total Numbers - Alice's Guess - Bob's misdirection)±X

In this simple equation, Alice's Guess ±X will always be the inverse of Bob's number, and when added to Alice's guess will equal Bob's number.

Formula: (T-N-B)=(T-G-B)±X

Let's run some examples: T=200, N=44, B=0. G=150.

(200-44-0)=(200-150-0)±X
156=50±X
X=106
G-X=N
150-106=44

Of course, we can simplify the formula using algebra as: N=G±X

N=47, G=50
47=50±X
X=-3

Done with the full formula:

(200-47-0)=(200-50-0)±X
47=50±X
X=-3
47=50-3
47-47

Regardless of the number picked and the guess, a relationship with each number is always established.

One last where Bob says that Alice's guess is greater than by 25. Bob guesses 12. Alice guesses 60.

(200-12-25)=(200-60-25)±X
163=115±X
163=115+48
163=163

Now, to get to Bob's answer, since he said Alice's guess is greater than, we need to SUBTRACT X from G.

G-X=N
60-48=12

Any answer Bob gives, whether or not he adds an addition, which by the rules set in this question is perfectly legal, always shows the relationship between the number selected and the guess made.


Successful Encoder and Decoder for messages

Concept

Interesting idea to use the pseudo-random number generator seed as an encryption key.  Note, however, that there's no guarantee that the PRNG implementation will be consistent from release to release of Python, or that it will act identically across platforms.  The same goes for the shuffle() function.

As you probably know, you should never try to implement your own cryptography for any meaningful usage, and this substitution cipher is trivially crackable by letter frequency analysis.  I'll treat this as nothing more than a fun programming exercise.

Correctness

In the decoder, the call to lower() is missing parentheses.  The return statement is incorrectly indented.

In the encoder, the letter iteration dummy variable shadows the letter array defined earlier.  In effect, the code becomes:

def Encoder(user_input,SEED):
    user_input = user_input.lower()
    letter = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    Letter_code = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}
    code = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',]
    n = []
    seed(SEED)
    shuffle(code)
    for letter in user_input:    # Note: This letter variable shadows the previous letter
        let = letter             # Originally… for let in letter:
        if letter != " ":
            if True:             # Originally… if letter == let:
                first = Letter_code[let]
                n.append(code[first])
        else:
            n.append("~")
    return ''.join(n)

That happens to mostly work!  The only thing that breaks was that you had intended to filter out unencodable characters, and now it will raise a KeyError if user_input contains anything other than letters or spaces.

If you dig deeper for a root cause of your bug, you can blame it on a proliferation of variables, causing confusion.  See if you can eliminate some variables, and name the remaining ones better.

Efficiency

In the encoder, your if letter != " " should be put between the outer and inner for-loops.  The decoder does it right.

Nested for-loops are a sign of poor efficiency.  Lookups should be done using a dictionary.  A dictionary would be more efficient (constant-time access rather than a scan through 26 list items), and it would look cleaner in the code.  (If you were doing serious cryptography, you would need all operations to be constant-time, to thwart attacks based on analyzing timing.)

Style

Naming conventions:

Encoder(user_input, SEED) → encode(user_input, seed) because it's a function, not a class.  You want a verb, not a noun.  SEED is not a constant.
Decoder(user_input, SEED) → decode(user_input, seed) for the same reasons.
letter → LETTER because it's a constant.
Letter_code → LETTER_CODE because it's a constant.
n → encoded or n → decoded because n has the connotation of being a number.

Prefer list comprehensions to loops: If you ever want to transform one list into another list, use a list comprehension instead of a for-loop if it's at all possible.  It's one assignment statement, and it forces you to express yourself using higher-level functions rather than step-by-step procedural code.
Work smarter, not harder: Save yourself some error-prone typing — let the computer generate your lists of letters and their corresponding codes.
Symmetry: The decoder is just the inverse of the encoder, so there's no reason why it should be any more complex.
If-else: Whenever you have an if-else construct, prefer to put the branch with the shorter body first to reduce mental workload.  For example, write the decoder this way:

if let == "~":
    n.append(" ")
else:
    for Ke in key_list:
        if let == Ke:
            a = key_code[Ke]
            n.append(final[a])

Proposal

from collections import defaultdict
from random import seed, shuffle

def encode(plaintext, key):
    """
    Performs a toy-grade substitution cipher on plaintext using the key.
    Any characters other than letters and spaces in plaintext will be discarded.
    """
    LETTERS = [chr(ord('a') + i) for i in range(26)]
    seed(key)   # influences shuffle()
    code = LETTERS[:] ; shuffle(code)
    # letter_code maps LETTERS to a copy of LETTERS that is scrambled using the key;
    # unrecognized characters map to the empty string.
    letter_code = defaultdict(str, zip(LETTERS, code))
    letter_code[' '] = '~'
    return ''.join([letter_code[c] for c in plaintext.lower()])

def decode(ciphertext, key):
    """
    Performs the inverse of encode().
    Any characters other than letters and spaces in ciphertext will be discarded.
    """
    LETTERS = [chr(ord('a') + i) for i in range(26)]
    seed(key)   # influences shuffle()
    code = LETTERS[:] ; shuffle(code)
    # The inverse of letter_code in encode()
    code_letter = defaultdict(str, zip(code, LETTERS))
    code_letter['~'] = ' '
    return ''.join([code_letter[c] for c in ciphertext.lower()])


An if in a tight loop is usually a performance killer. At least worth trying is something along the lines of

    len = min(args[0].Length, args[1].Length);
    for (j = 0; j < len; ++j) {
        Console.Write(args[0][j]);
        Console.Write(args[1][j]);
    }
    WriteRemainingsOfLongerString();

As mentioned in the comments, it could also be more performant to build a string and Console.Write it at once.


if word in korean_data.keys():
    return korean_data[word]

This is better written as:

trans = korean_data.get(word)
if trans:
    return trans

This:

elif len(get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)) > 0:
    word = get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)[0]
    return korean_data[word]

calls for a few changes. Firstly, you don't need an elif, simply an if - because the previous block returned. Also, you should avoid re-issuing that entire get_close_matches call, and instead write a temporary variable:

words = get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)
if words:
    return korean_data[words[0]]

This:

return "Word does not exist."

is not really good practice. It's "in-band error information", i.e. you're mixing valid data with an error message. Instead, you should be raise-ing an exception, catching it in your calling code, and outputting an error message there.

  What other challenges would you recommend that incorporates both JSON and python?

Download or scrape a real Korean-English dictionary dataset, either incorporating it into your application or setting up a REST client to contact a translation server somewhere. If local, save it as a format more efficient than JSON - perhaps compressed pickle, or SQLite. There are many ways to store a local database, and each has its advantages and disadvantages, but that's a topic for another question.


Finding closest points without duplicates and given distance threshold

Style

Remove unneccessary parentheses

You don't need parentheses around the condition for the WHILE
loop.  You can just write WHILE @counter > 0.

Also, the extra sets of parentheses around the random numbers are
superfluous.  If you leave them off, the line will be a bit less
daunting.

Don't break the line in the middle of a concept

That is, in the SELECT @RandomLatitude line, the statement breaks
just before the * operator.  As it has a higher precedence than
the +, this can be a bit misleading.  Either don't break, use
parentheses (if really unavoidable) or break before the +:

SELECT @RandomLatitude = ( @UpperLatitude - @LowerLatitude - 1 ) * RAND()
                         + @LowerLatitude;
SELECT @RandomLongitude = ( @UpperLongitude - @LowerLongitude - 1 ) * RAND()
                          + @LowerLongitude;

Merge variable declaration and initialisation

Where possible, declare a variable just before it is used, and
initialise it there as well:

DECLARE @LowerLatitude FLOAT = -90;
DECLARE @UpperLatitude FLOAT = 90;
DECLARE @LowerLongitude FLOAT = -180;
DECLARE @UpperLongitude FLOAT = 180;

DECLARE @Counter INT = 1000;
WHILE @Counter > 0
  BEGIN
    DECLARE @RandomLatitude FLOAT = ( @UpperLatitude - @LowerLatitude - 1 ) * RAND()
                                    + @LowerLatitude
    DECLARE @RandomLongitude FLOAT = ( @UpperLongitude - @LowerLongitude - 1 ) * RAND()
                                     + @LowerLongitude
    -- ...

Performance

You mention that the indices are already set. I assume that means that
it is not possible to add a Spatial Index, or a primary key.
Although I would strongly suggest adding a primary key constraint to
the temp table in this example:

CREATE TABLE #Points1
    ( PointId INT IDENTITY(1, 1) PRIMARY KEY
    , Point GEOGRAPHY NULL
    );

Unfortunately, without a Spatial Index or changes to the result
requirements (you'd need a TOP n clause and an ORDER BY on the
STDistance column), there is no choice but to check each point against
all others, which will give a large join of which I don't know how to
improve the performance.

Small point: you may gain a smaller result (only in number of rows) if
you leave out the distance from each point to itself:

INNER JOIN Points1 AS Points2 ON Points1.PointId < Points2.PointId

but that might not fit your requirements.


Displaying filtered user data using Ajax and PHP

The fact that you  are making three separate trips to the server stands out as an obvious refinement opportunity.
We don't know exactly where your performance bottleneck is, but you can be sure that best practice is to reduce your total trips to ...well, anywhere.
Think about it like this:

Your mother tells you to go to the shop and get a dozen eggs.
You get on your bicycle and make 12 trips to the shop and deliver one egg to your mother per trip.
Your sister shakes her head disapprovingly.
Your mother tells the neighbors that she loves you because you are "special".

If you know that the full flow of this task is to write data to the db ...then get some data from one table ...then get some data from another table, then the sensible thing is to dictate this flow entirely on the server side then only return to the client-side when everything is finished.
Effectively, I recommend using a single ajax request (with POST instead of GET because you are writing data to your database).
The dedicated server-side receiving script should execute the database writing query, then immediately execute the database fetching queries, then generate a single json string which contains all of the necessary user and usergroup data to satisfy your client-side processes.
If the bottleneck is isolated to the database interactions, then we don't have enough information to assist with optimizing the schema.

General advice:

Don't use mysqli_query() when you have a project that provides querying helper methods.  You whole application should use consistent techniques.

Only use concatenation when necessary.  '/users' + '/id' should be '/users/id'

When sending data to the server to fetch/read data from the db, use $_GET.  When sending to write/insert/update/delete data, use $_POST. There are exceptions, but this is the rule.

Use consistent spacing and tabbing in your code so that it is easier to maintain.

Don't use old school comma-join syntax -- use JOINs.

This is weird:
$i = 0;
if ($usergroups->num_rows != 0){
  foreach ($usergroups as $usergroup) {
    $ids[$i] = $usergroup;
    $i++;
  }
} else {
  $ids[$i] = 0-1;

}

Why declare a counter?  Why subtract 1 from 0?  You should probably trash most this section of code, and maybe entertain something closer to...
foreach ($usergroups as $usergroup) {
    $ids[] = $usergroup;
}

$data = \DB::table('grupo')
    ->whereNotIn('grupo.idgrupo', $ids ?? -1)
    ->get();

Never omit curly braces in an attempt to reduce the size of your code.  If you have a simple condition and like ternary expressions, use those instead.

Try to avoid declaring single-use variables.

If type dictates location, then don't send both parameters to the next function scope.  Generate location conditionally when you get there.


Removing the word "NULL" from a single column in Excel using VBA

Static Code Analysis

I took your code and ran it through Rubberduck (an open-source VBIDE add-in project I manage) code inspections - here's what came out of it:

Implicit references to ActiveSheet

When they're not qualified with an actual Worksheet object instance, members Range and Rows (and Columns, Names and Cells) implicitly refer to the ActiveSheet. These implicit references make the code frail, and harder to debug. Consider making these references explicit when they're intended (e.g. ActiveSheet.Range instead of just Range; ActiveSheet.Rows instead of just Rows), and prefer working off object references (e.g. DataSheet.Range, DataSheet.Rows).
Procedure RemoveNull is implicitly Public

Module members are public by default, which can be counter-intuitive (especially if you're coming from other programming languages). Consider specifying explicit access modifiers to avoid ambiguity. e.g. Public Sub RemoveNull() instead of just Sub RemoveNull().
Instruction contains multiple declarations

Dim c, count, r

Declaring multiple variables in the same instruction is legal, but should be used sparingly. Consider declaring variables closer to their usage, in a single instruction per declaration.
Implicit Variant variables

Variables c, r, and count are all implicitly Variant, because they're declared without an As clause. Consider specifying an appropriate data type for all variables (e.g. String for strings, Long for row numbers, etc.), and use an explicit Variant where Variant is intended. Note that there's a common beginner trap here:

Dim c, count, r As Long ' only r is a Long, c and count are both Variant

Use meaningful names

c, r, and x are poor names. Prefer using names that convey usage and meaning, e.g. activeColumn, activeRow, and currentRow. Avoid disemvoweling, numeric suffixes, Systems Hungarian prefixes and 1-2 character identifiers.
Undeclared variables

Variable x isn't declared, which means it's an implicit Variant, declared on-the-fly by the VBA runtime. If your code can compile and run, it means Option Explicit isn't specified either.
Option Explicit not specified

VBA will happily compile a typo: use Option Explicit to prevent successfully compiling a program that doesn't explicitly declare every single variable it's using.

Future versions of Rubberduck will also highlight that Step 1 is the default step for a For loop, and therefore redundant.

Redundancies

Static code analysis is nice, but can't pick up everything. Like this:

c = ActiveCell.Column
c = GetLetterFromNumber(c)

You have the Column number already - there's absolutely no need to work out what column "letter" that number is referring to. Simply change how you're accessing the cell - instead of this:

[ActiveSheet.]Range(c & x).Clear

Use Cells:

[ActiveSheet.]Cells(x, c).Clear

Notice how much easier that is to parse, with meaningful names:

[ActiveSheet.]Cells(currentRow, activeColumn).Clear

So, remove GetLetterFromNumber, you don't need it at all. Ever.

Static code analysis also won't pick up (for now, anyway) that Range.Value has a non-zero possibility of containing an error value - in which case a comparison with any non-error type will raise run-time 13 / Type Mismatch:

If Range(c & x).Value = "NULL" Then ' possible error here

The loop body is pulling the same cell twice, and in order to validate whether it's an error or not, you'd need to pull it a third time: consider extracting a local variable.

Dim currentCell As Range
Set currentCell = [ActiveSheet.]Cells(x, c)

If Not IsError(currentCell.Value) Then
    If currentCell.Value = "NULL" Then ' comparison is now safe
        currentCell.Clear
    End If
End If

The last thing you want is the possibility of throwing a run-time error *while Application.ScreenUpdating is turned off. For this reason, whenever you need to toggle that setting, consider introducing some minimal error handling:

Public Sub DoSomething()
    On Error GoTo CleanFail
    Application.ScreenUpdating = False

    'code...

CleanExit:
    Application.ScreenUpdating = True
    Exit Sub
CleanFail:
    Debug.Print Err.Description
    Stop ' we don't know what happened; break here and debug
    Resume CleanExit
End Sub

Performance

Range is an object collection - the fastest way (by a lot) to iterate it is with a For Each loop. But, if all you need out of a Range its its Value, you can iterate the values even faster by dumping the range into an array, and iterating the array with a For...Next loop:

With ActiveSheet

    Dim lastRow As Long
    lastRow = .Cells(.Rows.count, c).End(xlUp).Row

    Dim values As Variant ' a variant array
    values = .Range(.Cells(1, 1), .Cells(.Rows.Count, lastRow)).Value

End With

There are plenty of Stack Overflow Q&A's about the best ways of turning that 2D array into a 1D array, I'll leave that bit of research up to you.

Once you have a one-dimensional array, you can iterate and modify it in-memory:

For x = LBound(values) To UBound(values)
    If Not IsError(values(x)) Then
        If values(x) = "NULL" Then values(x) = vbEmpty
    End If
Next

And then you can convert back the 1D array to a 2D array, and dump it onto the worksheet in one single write:

ActiveSheet.Cells(1, activeColumn).Resize(UBound(values)) = Application.Transpose(values)

And with one single read and one single write from the worksheet, and the iteration and actual work being done in-memory at lightning speed (as opposed to one cell at a time with Excel repainting itself every time, if not recalculating the whole worksheet too), there shouldn't even be a need to switch off Application.ScreenUpdating now - toggling it off won't make a difference anyway.

I suspect the result will be so fast, you won't even need that MsgBox call to wake the user up.


Deserializing JSON in an expression-bodied member

We can of course try to optimize it but this would be only an ugly workaround trying to minimize the flaws of the current design.

There are more questions then answers:

Why is the the parameter dynamic?
Are you trying to parse json? JObject suggests you are and I'm pretty sure this is the wrong way to do it.
Why do you use such a crazy syntax for a method? The expression bodied members are meant for one-liners and not for such huge blocks.
Why don't you deserialize the object with JsonConvert.Deserialize?
Why don't you decorate the properties like SoftwareVersion with the appropriate attribute like [JsonProperty(PropertyName = "swVersion")]

You should rethink the entire parsing process and not just this helper method.


Delete node from linked list, using offsetof to set the tail pointer

Can be simplified

You chose to use a "pointer to pointer" technique to find and delete your node, but this led to using an offsetof macro in order to back up your tail pointer to the previous node.  If you instead used a "previous pointer" technique, your code would be much simpler to read and you wouldn't have to use any strange pointer subtraction tricks in order to find the previous node.  Here is how it would look like:

lrsll_node *lrsll_delete(lrsll_list *list, const char *data)
{
    lrsll_node *prev = NULL;
    lrsll_node *node = list->head;

    while (node != NULL && strcmp(node->data, data) != 0) {
        prev = node;
        node = node->next;
    }

    if (node == NULL)
        return NULL;

    if (prev == NULL)
        list->head = node->next;
    else
        prev->next = node->next;

    if (node == list->tail)
        list->tail = prev;

    return node;
}

Addendum: Linus Torvalds' comments

Apparently this whole code was motivated by something Linus Torvalds wrote about using pointers to pointers.  Here is the example demonstrating what he meant, taken from this blog post:

Given this list type:

typedef struct list_entry {
    int val;
    struct list_entry *next;
} list_entry;

This is the "wrong way" to delete a node:

list_entry *entry = head; /* assuming head exists and is the first entry of the list */
list_entry *prev = NULL;

while (entry) {
    if (entry->val == to_remove)     /* this is the one to remove */
        if (prev)
           prev->next = entry->next; /* remove the entry */
        else
           head = entry->next;      /* special case - first entry */

    /* move on to the next entry */
    prev = entry;
    entry = entry->next;
}

And here is what Linus considered the "correct way":

list_entry **pp = &head; /* pointer to a pointer */
list_entry *entry = head;

while (entry) {
    if (entry->val == to_remove)
        *pp = entry->next;

    pp = &entry->next;
    entry = entry->next;
}

And I will agree with Linus that for this case, the "double pointer" solution is better than the "prev pointer" version.  But there is an important difference between this example and the OP's code, which is that the list in this example has no special List structure containing a head and tail pointer.

Because you may need to set the tail pointer to the previous node, the benefit of using the double pointer disappears, because now you need to convert the double pointer back into a node pointer using the awful offsetof trick.  So for the particular data structure used by the OP, I would argue that the "prev pointer" solution is preferable.

In other words, you shouldn't always use the double pointer solution just because Linus said to use double pointers.  You should consider whether or not your code would benefit from using double pointers and then use them if they provide a net benefit.


In order of significance for performance

Don't use array to store prime numbers. You only need one previous
prime to remember. And even if you ever do this, don't remove
elements from its middle, as shifting array contents is very costly.
Store number from expensive Math.sqrt(), don't re-calculate it every iteration. Basically, this is rule for every loop - precalculate limits if possible.
There is only one even prime number: 2. It gives you great opportunities to quickly remove some edge cases:
If gap is odd, only 2 can be a first number. This condition is worth checking at the very start of your function
If number is greater than 2, it can be prime only if it is odd. This allows you to skip half of testing numbers by increasing counter by 2 each iteration, not just ++
Prime testing can be further improved by using 6k ± 1 pattern. It saves you one extra check every 3 odd numbers
You are testing prime numbers in loop. Create a function for this, isPrime or something

function gap(gap, start, end) {
  //cut off odd gaps
  //bitwise AND can test least significant bit
  //odd numbers have 1, even have 0
  if (gap & 1) { //is it odd?
    if (start > 2 || end < gap + 2) return null; //check if 2 is in range
    return isPrime(gap + 2) ? [2, gap + 2] : null; //check additionally the other part
  }
  var previous = null; //no initial value
  //loop over odd numbers to check for primes
  for (var current = start | 1; //set last bit to 1: /odd numbers stay same, even numbers become next odd
       current <= end;
       current += 2 // skip any even number
      ) {
    if (isPrime(current)) {
      if (current - previous === gap) //is it a match?
        return [previous, current];
      //no need for "else" here as the other branch has "return"
      previous = current; // anyway, save it
    }
  }

  return null; //no early return from loop = nothing matches

  /**
    Tests if n is prime
  */
  function isPrime(n) {
    if (n <= 6) //cut away small primes explicitly
      return n === 2 || n === 3 || n === 5;
    //cut away small divisors (2 and 3) explicitly
    if (n & 1 === 0 || //using bitwise AND for even numbers
        n % 3 === 0) return false;

    var limit = Math.floor(Math.sqrt(n)); //precalculate loop limit
    // loop is checking every divisor using 6k ± 1 pattern
    for (var t = 5; //start with 5, first 6k - 1 number
         t <= limit;
         t += 6 //step by 6
        ) {
      if (n % t === 0 || //6k - 1
          n % (t + 2) === 0) //6k + 1
        return false;
    }
    return true;
  }
}
console.log(""); //this makes console output timestamp
console.log("gap(8,3000000,4000000)", "->", gap(8,3000000,4000000)); // ~5ms
console.log("gap(120,3000000,4000000)", "->", gap(120,3000000,4000000)); // ~600ms

Working fiddle. I submitted it on CodeWars, it passes :)


Creating a list of new areas for patches of conserved land within a watershed

The problem is that random.randrange(len(parcel_areas)-1) most of the times returns an area which fails the min_size <= parcel_areas[rand_index] <= max_size test. Therefore it is logical to restrict the random selection to the set of areas which satisfy the requirements beforehand, and eliminate the inner loop completely.

Sort the list of areas by size. Once you determined min_size and max_size, find corresponding bounds (with binary search), and select randomly within these bounds.


Removing final elements of a path to a file

First, have in mind what @Daerdemandt suggested in comments (using os.path.relpath - even though I think this is returning the matches but I might be wrong)

From the docs:

  Return a relative filepath to path either from the current directory
  or from an optional start directory. This is a path computation: the
  filesystem is not accessed to confirm the existence or nature of path
  or start.

  start defaults to os.curdir.

  Availability: Unix, Windows.

After some reading of the os module, I don't think this is possible either. Sincerely, it is an unusual path manipulation which leads to the reason of not having it in the above mentioned module.

Apart from this, we can cut down you method and make it straight-forward:

import sys

def pathbase(path1, path2):
    try:
        if path1.endswith(path2):
            return path1[:-len(path2)]
        raise TypeError
    except TypeError:
        print('Main path does not end on sub-path')
        sys.exit(0)

path1 = '/foo/bar/spamm/eggs'
path2 = 'spamm/eggs'

print(pathbase(path1, path2))

There's not much to say about this. I just simplified your code by removing the while part which didn't make too much sense to me. I also removed the else part and raised a TypeError which I used in an try-except block.

Some minor style things

you could've call your method: get_base_path()
you could've name your arguments: main_path and sub_path

In the end, everything would look just like:

import sys

def get_base_path(main_path, sub_path):
    try:
        if main_path.endswith(sub_path):
            return main_path[:-len(sub_path)]
        raise TypeError
    except TypeError:
        print('Main path does not end on sub-path')
        sys.exit(0)

main_path = '/foo/bar/spamm/eggs'
sub_path = 'spamm/eggs'

print(get_base_path(main_path, sub_path))

The above returns:

  /foo/bar/


Determine if an input is an integer, a double or a String

I don't like the throwing and catching of Exceptions

This can be made much cleaner with the use of a Scanner. It might not be the most performant way, but it's fast and easy to use.

try (Scanner scanner = new Scanner(x)) {
    if (scanner.hasNextInt()) doFoo(scanner.nextInt());
    else if (scanner.hasNextDouble()) doFoo(scanner.nextDouble());
    else doFoo(x);
}

However, if this is going to be called hundreds of thousands of times, the try catch method might be faster, though you should encapsulate those into their own functions. You'd need to profile to be sure which is faster, but I believe it would be this because Scanner.hasNextFoo uses regular expressions:

public static boolean isInteger(String str) {
    try {
        Integer.parse(str);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

Also, your function is doing multiple things: printing/reporting, and parsing/forwarding to doFoo. This is not a good thing. I'd recommend removing those and handling them where it's more appropriate:

public static void testString(String val) {
    String x = val.trim();

    try (Scanner scanner = new Scanner(x)) {
        if (scanner.hasNextInt()) doFoo(scanner.nextInt());
        else if (scanner.hasNextDouble()) doFoo(scanner.nextDouble());
        else doFoo(x);
    }
}

That was much shorter. Now if you wanted the same functionality, it would look like so:

public static void testTestString(String val) {
     System.out.print("Original '" + val + "'  ");
     testString(val);
}

// ...

public static void doFoo(int i) {
    System.out.println("It's an integer: " + i);
    // ...
}

If you want your code to be extremely extensible, there is another way. Notice how the new function I suggested still does multiple things:

It detects the type of the string
It parses the value from the string
It forwards the value on to another function

We can separate these into their own components.

This is only really worth it if you can foresee adding types to be a common feature, but especially if the "another function" you forward to should be selectable by the user (say, if you packaged these functions as member functions of an object):

// Class is the easiest type we can return
private static Class<?> determineType(String val) {
    try (Scanner scanner = new Scanner(val)) {
        if (scanner.hasNextInt()) return Integer.class;
        if (scanner.hasNextDouble()) return Double.class;
        return String.class;
    }
}

private static final Map<Class<?>, Function<String, ?>> parsers = new IdentityHashMap<>();
private static final Map<Class<?>, Consumer<Object>> functionSwitch = new IdentityHashMap<>();

static {
    parsers.put(Integer.class, Integer::parseInt);
    parsers.put(Double.class, Double::parseDouble);
    parsers.put(String.class, Function.identity());

    // Note that, due to limitations in the type system,
    // i is of type Object, so we need to cast it to the appropriate
    // class before forwarding on to the function.
    functionSwitch.put(Integer.class, i -> doFoo((Integer) i));
    functionSwitch.put(Double.class, d -> doFoo((Double) d));
    functionSwitch.put(String.class, str -> doFoo((String) str));
}

public static void testString(String val) {
    val = val.trim(); // This could even be part of the parser's responsibility
    Class<?> stringType = determineType(val);
    Function<String, ?> parser = parsers.get(stringType);
    functionSwitch.get(stringType).accept(parser.apply(val));
}


I think you did a pretty good job overall.

You can simplify your code by making CounterService.make not return an effect since you only call ZIO.succeed in it. make can return directly a CounterService and that way no need to call unsafeRun in your main app.

I also think that the HttpRoutes class is not really necessary since it only has a single method counterRoutes that you call once. You could just put this function inside an object and ditch the intermediate class. The values that are already implicit (execution context, runtime) can be passed implicitly as well.

def counterRoutes(interpreter: GraphQLInterpreter[zio.ZEnv, _])(
  implicit ec: ExecutionContext, runtime: Runtime[zio.ZEnv]): Route = {
    path("graphql") {
      AkkaHttpAdapter.makeHttpService(interpreter)
    }
  }

routes.counterRoutes(graphQl.interpreter)


Obtaining prediction bands for regression model

There is a nice discussion about confidence/prediction bands in the documentation for the excellent kmpfit module. You need to include the convariance matrix from the fit in the calculation of the bands, which I don't see in your code. There is an example in the link that walks through it.

Here is their implementation:

def confpred_band(x, dfdp, prob, fitobj, f, prediction, abswei=False, err=None):
   #----------------------------------------------------------
   # Return values for a confidence or a prediction band.
   # See documentation for methods confidence_band and
   # prediction_band
   #----------------------------------------------------------
   from scipy.stats import t
   # Given the confidence or prediction probability prob = 1-alpha
   # we derive alpha = 1 - prob
   alpha = 1 - prob
   prb = 1.0 - alpha/2
   tval = t.ppf(prb, fitobj.dof)

   C = fitobj.covar
   n = len(fitobj.params)              # Number of parameters from covariance matrix
   p = fitobj.params
   N = len(x)
   if abswei:
      covscale = 1.0  # Do not apply correction with red. chi^2
   else:
      covscale = fitobj.rchi2_min
   df2 = numpy.zeros(N)
   for j in range(n):
      for k in range(n):
         df2 += dfdp[j]*dfdp[k]*C[j,k]
   if prediction:
      df = numpy.sqrt(err*err+covscale*df2)
   else:
      df = numpy.sqrt(covscale*df2)
   y = f(p, x)
   delta = tval * df
   upperband = y + delta
   lowerband = y - delta
   return y, upperband, lowerband


You're not listing your base class, but because of the override and the method's signature in the derived type, I'm assuming something like this:

public abstract class EntityBase : ICloneable
{
   //...
   public abstract object Clone();
}

Here's what MSDN says about ICloneable (emphasis mine):

  An implementation of Clone can perform either a deep copy or a shallow
  copy. In a deep copy, all objects are duplicated; in a shallow copy,
  only the top-level objects are duplicated and the lower levels contain
  references. Because callers of Clone cannot depend on the method
  performing a predictable cloning operation, we recommend that
  ICloneable not be implemented in public APIs.

From that perspective, it's better to consider that "cloning" operation as nothing more than construction of a type - passing this to a constructor, and returning the created instance, sounds like a better plan.

Now, given that a FMSUser can be constructed from another instance, I don't really see a need for the Clone method to even exist at all. On top of it all, it returns an object, and you should avoid exposing System.Object in your public interfaces.

Consider this:

var clone = new FMSUser(existing); // "clone" is FMSUser.

Versus this:

var clone = existing.Clone(); // "clone" is System.Object, requires a cast to get a FMSUser.

Side note:

var CloneUser = base.Clone() as FMSUser;

CloneUser should be named cloneUser, or simply clone. By using PascalCase, you're breaking the naming convention for locals and parameters, which should be camelCase.


Sorting an array of numbers in Java with an algorithm

Im impressed that you used selection sort. The standard bubble sort method would be slower. Have a look at the bubble sort method anyway.

int n = arr.length, r;
for (int i = 0; i < n; i++)
{
    for (int (j = i + 1); j < n; j++)
    {
        if (arr[i] > arr[j])
        {
            r = arr[i];
            arr[i] = arr[j];
            arr[j] = r;
        }
    }
}

You could also have used the default Arrays.sort method

Arrays.sort(arr);

You are creating an applet. In this case, it would probably be good to declare the main method as static

When you are importing the packages, why have you imported the individual classes after importing them by wildcard character '*'; There is no need for it.
That is redundant and the computer wastes time re-importing and garbage-collecting. Just do:

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

Also, printing mistake here:

String input_1 = JOptionPane.showInputDialog(frame, "How many numbers do you want to sort with SSSP ?");

Consider setting bounds to the buttons and text boxes in your mainframes, to make the locations more exact. That way, it will be easier to add a new GUI component to the window when you want to add it.
The command goes:
<name of object>.setBounds(//x-axis from left, //y-axis from top, //width, //height)
For example:

t2 = new JTextField("Here are your sorted numbers : " + Arrays.toString(arr2));
t2.setBounds(20, 40, 75, 10);
main_frame.add(t2);

JButton buttonEnd = new JButton("Close application");
t2.setBounds(95, 40, 75, 10);
main_frame.add(buttonEnd);

JButton buttonRetry = new JButton("Try again !");
t2.setBounds(180, 40, 75, 10);
main_frame.add(buttonRetry);

WHY have you named your class AWTCounter? That makes me think you are counting numbers with certain properties or words in a sentence. Won't AWTSorter be better?

Great program though, especially if it's your first!


Link

 $('.listsToToggle').hide();

 $('.linksToWatch').bind('click', function() {
   var id = $(this).attr('id');
   $('#' + id + '-list').toggle();
 });

May be, something like this?


Python also has no C-style for-loop.  A lot of Python novices write clumsy while-loops as a result.  However, once you learn the Pythonic idioms for looping, you'll wonder why other languages aren't more like Python.

The trick is to get to know…

the range() built-in function, which looks a lot like the stride(through: by:) that you suggested
the enumerate() built-in function, for when you need to iterate over a list and also increment a counter at the same time
the itertools library for more complex situations

If I had to translate your Swift code to Python, I would do it using itertools.count() to generate the infinite sequence [7, 37, 67, 97, …], and itertools.takewhile() to terminate it.

from itertools import count, takewhile

def is_prime(value):
    if value < 2: return False
    if value % 2 == 0: return value == 2
    if value % 3 == 0: return value == 3
    if value % 5 == 0: return value == 5
    if value == 7: return True

    for divisor in takewhile(lambda d: d * d <= value, count(7, 30)):
        if value % divisor == 0: return False
        for offset in [4, 6, 10, 12, 16, 22, 24]:
            if value % (divisor + offset) == 0: return False
    return True

Kevin Ballard has posted a proposal on the swift-evolution mailing list to introduce a takeWhile() to the standard library.  I think that a rich library for manipulating sequence types would make a good replacement for C-style for-loops.


Use the properties of a BST

In a BST, if the value being search for is less than the key of the current node, then it is in the left subtree and if the value is greater than the key of the current node, then it is in the right subtree.  Your code always searches the left subtree first and then searches the right subtree if needed.  This code only searches one subtree:

def pathToNode(node, path, k):
    path.append(node.key)
    if node.key == k :
        return True

    elif k < node.key:
        if node.left and pathToNode(node.left, path, k):
           return True

    else:
        if node.right and pathToNode(node.right, path, k):
           return True

    path.pop()
    return False

The same applies to getlevel().

distance() determines the path from the root to each node. Then determines the common prefix of each path. This can be simplified as observing that if both nodes are in the same subtree, then the root of the current tree isn't on the path between the nodes.

def distance(node, x, y):
    if x < node.key and y < node.key:
        return distance(node.left, x, y)

    elif node.key < x and node.key < y:
        return distance(node.right, x, y)

    else:
        path1 = []
        pathToNode(node, path1, x)
        path2 = []
        pathToNode(node, path2, y)

        return len(path1) + len(path2) - 2

Note: you don't actually need the path of a node, just it's depth.


I think you input routine is not really safe. maybe add an explicit break?

while (true) {
    cin >> num;
    if (cin.fail)
        break;
    vect.push_back(num);
}

What happens when unsorted_vector is empty. You check for size == 1 maybe turn that into size <= 1
Stuff like this is hard to read:

std::vector<int> sorted_vect, first_half, second_half, first_temp, second_temp;

I would definitely suggest to put every name onto its own line and add the explicit type. Its not that you are saving trees here.
Do not use else after an early exit.

if(unsorted_vector.size() == 1) {
    return unsorted_vector;
} else {
// Stuff
}

Is equivalent to:

if(unsorted_vector.size() == 1) {
    return unsorted_vector;
}
// Stuff

However with less indentation and easier control flow.
You should definitely reserve memory in your merge function:

vector<int> sorted_vect;
sorted_vect.reserve(first_vect.size()+second_vect.size());

Use descriptive names. This is purely subjective, but whenever I see vect and friends i cringe. What do you really save from ommitting "or"?


while your code runs, personally I would change the formatting to start with

I noticed your search area div has a mistake in it, your H1 encloses the Anchor tag and the image but you close the H1 tag before closing the anchor tag, which is syntactically incorrect.  I also noticed that you were missing quotation marks around the value of one of your anchor tags in the gmailimages,
I will make these changes in the suggestions I post below.

Some things like your anchor tags inside of your divs could be on new lines to make the code more readable, let me show you what it looks like when I move the tags to their own lines.

        About
        Store

        Gmail
        Images

        <form method="GET">
            <input type="text" id="searchbar"></input>

            <input type="submit" value="Google Search" class="searchbuttons"></input>
            <input type="submit" value="I'm Feeling Lucky" class="searchbuttons" id="imfeelinglucky"></input>
        </form>

United Kingdom

        Advertising
        Business
        How Search Works

        Privacy
        Terms
        Settings

The next thing that I would suggest is to look into HTML5, there are nice tags for things like

Navigation Menus
Headers
Footers
etc.


HTTP scraper efficiency with multiprocessing

Reading File

Here is a tip, while reading, the r is optional

f = open(r'\h.csv',"r")

can be written as

f = open(r'\h.csv')

Your whole reading block can use context managers (blocks using the with keyword).

with open(r'\h.csv', encoding='utf8') as f:
    cont = f.read()

If you are dealing with a huge text file, you might do:

with open(r'\h.csv', encoding='utf8') as f:
    for ip in f:
        ip = ip.rstrip('\n')
        .. verify

String

Using string formatting i.e. .format() can give a better idea of what's going on. It also eliminates the use of str() each time.
We can change this

print(list[k] + " MGMT" + ": " + str(ports[i]) + "  " + str(k))

to that

print("{} MGMT: {}  {}".format(list[k], ports[i], k))

and as from 3.6+, adding an f

print(f"{list[k]} MGMT: {ports[i]}  {k}")

Loop Iteration

In many other languages, you need the index while looping to have the element at this index. Python provides a nice and intuitive way to loop over elements

The current implementation:

ports = [443, 4433, 444, 433, 4343, 4444, 4443, 4434]
portlen = len(ports)
for i in range(portlen):
    print(ports[i])

But the pythonic way is:

ports = [443, 4433, 444, 433, 4343, 4444, 4443, 4434]
for port in ports:
    print(port)

port here gives you the element directly.
If ever you still want the index, you do:

for i, port in enumerate(ports):

where i is the index.

Miscellaneous

Here:

cpu = int(multiprocessing.cpu_count())

No need to cast to int as multiprocessing.cpu_count() already returns an integer. You can verify for int by type(multiprocessing.cpu_count())

Normally with .start(), you must include a .join(), as this allows all child processes to terminate before exiting.

for ...:
   ... .start()

for ...:
   ... .join()


Aliases
The alias names SEE, SPE and COEP are not descriptive. It's often tempting to make acronyms for tables and use those as aliases. It's all well and good for people who are already familiar with the structure of the database, but when you show this code to an "outsider" those aliases become a bit of an obstacle in understanding the code.
I think something like this would read a lot better:
FROM Snapshot.EmployeeElection AS EmpElecs --was SEE
  JOIN Snapshot.PersonEmployee AS Emps --was SPE
    ...
  JOIN CaseOpenEnrollmentPeriod AS Periods --was COEP

Execution plan
An update after you posted the execution plan.
See that RID Lookup (Heap) operation on SnapshotPersonEMployee? That to me indicates that the SQK engine could not use the index for that query, see Identifying Key and RID Lookup Issues and How to Resolve by Aaron Bertrand on the DBA.SE site. Quoting him:

These lookups occur when an index does not satisfy the query (non-covered query) and therefore additional data needs to be retrieved from the clustered index or the heap. Non-covered queries can be a problem because, for every row in the index, the additional column(s) must then be fetched; this can have a significant impact on large data sets and impact overall performance.

If hard to pinpoint the exact problem, I would suggest starting by looking at the columns in this join and see if they are indexed, if not that might be your problem right there. If not all those columns are indexed then it likely has to go lookup in the table itself as hinted by your execution plan.
  JOIN Snapshot.PersonEmployee SPE
    ON  SEE.EmployeeID = SPE.AssignedID AND
        SEE.ConfirmationID = SPE.ConfirmationID AND
        SEE.CaseOpenEnrollmentPeriodID = SPE.CaseOpenEnrollmentPeriodID AND
        SEE.LoadDateTime = SPE.LoadDateTime

You could either look into adding indexes, which will speed up performance for all queries that use them, use perhaps move the non-indexed columns to an HAVING clause at the end, which might move these matches to the result set instead of the initial lookup. (maybe).

Date conversions
You've mentioned that the code is meant for an EDI which accepts dates as string (in mm/dd/yyyy format), I have to deal with things like that pretty frequently, and chances are you probably cannot change the EDI itself (or not without significant effort/expense, at least) so that's understandable.
I was going to suggest casting the dates instead of converting, but then I realized that casting does not allow to pick the output format, it would come out as yyyy-mm-dd which is default SQL Server/T-SQL date format. Unfortunately, that's probably one of the most expensive set of operations in your query. There may not actually be a way to improve these, given the limitations.
Date-Time handling can be annoying, and more so when you have to convert between actual date-time values and string representations of them.


SynchronizedArrayList implemented using reader writer synchronization

My answer will try to cover some ground @JvR seems to have missed. (as he said concurrency is hard, 4 eyes see more than 2)

Question you didn't really ask, but actually probably the most important one :

Is this class thread safe?

No. If getInternal() throws an exception (say IndexOutOfBoundsException for instance) the readerCount is never decremented again. Result : Any writer will wait forever to be allowed to write.

Assume we fix it?

Thread safe? Yes, but now not effecient. Under high reader contention a writer may never get the chance to write, since a write lock request does not prevent new readers to acquire a lock. This can keep readerCount above zero indefinitely.

Another efficiency problem : you synchronize on this. If any 3rd party class locks on the list, it will no longer function correctly. Readers and writers will be blocked until that lock is released.

I concur with @JvR's answers to your three questions.

There can be many readers.

Yes.
There can only be just one writer.

Yes.
Fairness among writers. In other words, writers should be served in FIFO manner.

No. From Java Concurrency in Practice :

  intrinsic locking offers no deterministic fairness guarantees, but the
  statistical fairness guarantees of most locking implementations are
  good enough for almost all situations. The language specification does
  not require the JVM to implement intrinsic locks fairly, and no
  production JVMs do.

@JvR covers the solution you'd need to implement for the fairness problem quite aptly already.

Other improvements?

@JvR mentioned generics, but I'd like to broaden that remark to : You're not implementing the List interface. Ok you're not actually making a useful class, but learing about locks, so probably not that important.
addInternal() and getInternal() : too thin to be a private method : inline them.
initialization of the internal list : use the diamond operator. (if you're on 7+)

Here is the code I used to play with your list :

private static final int TASKS = 20; // if you don't see the high contention problem : increase this value.

static SynchronizedArrayList list1 = new SynchronizedArrayList();

public static void main(String[] args) {
    list1 = new SynchronizedArrayList();
    CountDownLatch start = new CountDownLatch(1);
    CountDownLatch ready = new CountDownLatch(TASKS);
    final ReadWriteLock lock = new ReentrantReadWriteLock();

    ExecutorService executorService = Executors.newFixedThreadPool(TASKS);

    executorService.submit(new Runnable() {
        @Override
        public void run() {
            ready.countDown();
            try {
                start.await();
                for (int i = 0; i < 50; i++) {
                    Thread.sleep(10);
                    list1.add(i, i);
                    System.out.println("             Written " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    });

    for (int i = 0; i < TASKS - 1; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                ready.countDown();
                try {
                    start.await();
                    boolean keepOnTrucking = true;
                    while (keepOnTrucking) {
                        keepOnTrucking = false;
                        try {
                            list1.get(49);
                        } catch (Exception e) {
                            keepOnTrucking = true;
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
    }

    try {
        ready.await();
        start.countDown();

        executorService.shutdown();
        executorService.awaitTermination(5, TimeUnit.MINUTES);

    } catch (InterruptedException e) {
        // just end
    }
}


Printing all the combination of indexes for 2 sum exact outcome

I guess that the relevant piece of code is the twoSumExactWithList method and for now I will ignore the rest...

I think that depending on the context, e.g. the principles used in the project that you intent to use, this code you could either fully embrace collections or stick to arrays... but your code does a combo of both where the arguments are naked arrays and the returns uses collections... so please choose between the two.

If you choose arrays a possible return type is int[][] where one of the two dimensions is 2. representing first vs second index of the pair. In practice int[2][] is potentially more efficient than int[][2] but perhaps the Jit may make it irrelevant. Perhaps you could have a IntPair[] where IntPair is a pair of ints struct-like class.

If you choose collections... then the arguments should be List<Integer> nums, int target. The result is kind-of fine... but don't commit to return an ArrayList but rather a List; don't give any details on the implementation that are not necessary. To encode the index pair, consider the use of a custom class IntPair again... List is correct but seems a bit overkill considering that we know is always two and exactly two elements.

As for the method body... The varible types should be a general as they can be... so map's type should be Map<Integer, Integer> rather than HashMap<...>, outerList's should be List rather than ArrayList and so forth...

I would declare complement within the loop as it is not used outside of it and is rewritten at every iteration. innerList would go within the if within the for.

Whenever possible I would declare variables as final to give an extra hint to the compiler/optimizer that indeed these are not going to be changed... eg. final int[] nums, final int target, final Map<Integer, Integer> map, final int complement.

I would rename map to something a bit more informative as to what it contains...
so perhaps indexByNumValue?

I think your code would read and look much better with some additional spaces e.g.:

List<Integer> innerList=null; to List<Integer> innerList = null;.

for(int i=0;i<nums.length;i++) { to for (int i = 0; i < nums.length; i++) {.

}else { to } else {.

if( to if (.

nums,int to nums, int.

etc...