More static types

One big improvement you could make would be to have the Penultimate.apply method provide the output type in its signature. For example, with your current code you can write this:

scala> val instance = Penultimate[Int :: String :: HNil]
instance: Penultimate[shapeless.::[Int,shapeless.::[String,shapeless.HNil]]] = Penultimate$$anon$1@2819ef2f

scala> instance(1 :: "" :: HNil)
res0: instance.Out = 1

But not this:

scala> val x: Int = instance(1 :: "" :: HNil)
<console>:14: error: type mismatch;
 found   : instance.Out
 required: Int
       val x: Int = instance(1 :: "" :: HNil)
                            ^

If you want to keep track of the output type statically, you have to do it by hand:

val instance = implicitly[Penultimate.Aux[Int :: String :: HNil, Int]]

val x: Int = instance(1 :: "" :: HNil)

Which works, but ugh. It's a lot easier to change your implementation of apply:

def apply[H <: HList](implicit ev: Penultimate[H]): Aux[H, ev.Out] = ev

Now this works just fine:

scala> Penultimate[Int :: String :: HNil].apply(1 :: "" :: HNil): Int
res1: Int = 1

…well, at least it works for hlists with two elements. When we add more things get weird:

scala> val instance = Penultimate[Char :: Int :: String :: HNil]
warning: there was one feature warning; re-run with -feature for details
instance: Penultimate[shapeless.::[Char,shapeless.::[Int,shapeless.::[String,shapeless.HNil]]]]{type Out = ev.Out} forSome { val ev: Penultimate[shapeless.::[Char,shapeless.::[Int,shapeless.::[String,shapeless.HNil]]]] } = Penultimate$$anon$2@49393eeb

scala> val x: Int = instance('a' :: 1 :: "" :: HNil)
<console>:18: error: type mismatch;
 found   : instance.Out
    (which expands to)  ev.Out
 required: Int
       val x: Int = instance('a' :: 1 :: "" :: HNil)
                            ^

This time apply is fine, but the method that provides inductive instances isn't. You can fix it by giving its result type the same kind of treatment:

implicit def inductive[H, T <: HList, OutT](
   implicit penult: Aux[T, OutT]
): Aux[H :: T, OutT] = new Penultimate[H ::  T] {
  override type Out = OutT

  override def apply(in: H :: T): Out = penult.apply(in.tail)
}

Now the following will work just fine:

val instance = Penultimate[Char :: Int :: String :: HNil]
val x: Int = instance('a' :: 1 :: "" :: HNil)

Now we have useful result types for instances (i.e. result types that track the output type statically), and an improved apply that lets us make use of them.

Point of style 1: DepFn1

This is a relatively minor point, but you could define your type class like this:

import shapeless.DepFn1

trait Penultimate[H <: HList] extends DepFn1[H]

This is essentially exactly the same (the Out and apply are still there—you're just getting them from DepFn1), but it's less verbose and clearer about the intent.

Point of style 2: infix vs. not infix

I'd personally avoid writing ::[H, T] in one place and H :: T in others—for a type with a symbolic name like :: I'd always use the infix version. If you prefer the non-infix version, that's also fine, I guess. Mixing them isn't fine, though. :)

Point of style 3: don't just stick the override keyword everywhere

This is again a matter of personal preference, but I'd drop the override keyword from both the type member and the apply implementations in the anonymous new Penultimate class definitions, since your implementations aren't actually overriding anything.

Point of style 4: consistent type parameter names

In several places you use H as a type parameter name for a head type parameter, but in the Penultimate trait definition itself you use it apparently to stand just for "hlist". I'd use L, which also has the benefit of being consistent with the L in the Aux type member.

Point of style 5: explicit apply

Now we're getting into super-nitpick territory, but in general if writing out x.apply(y) isn't necessary to avoid y looking like an explicit implicit parameter, etc., I'd just use x(y).

Point of style 6: import order

More nitpickery: : precedes H, so it's likely that if you're using something like Scalastyle it's going to complain about the import.

Point of style 7: trait vs. abstract class

For a type class like this that will almost certainly never need to be mixed in with another trait, I'd prefer to make it an abstract class, for the reasons given here.

Point of style 8: unique instance names

I'm not sure how strongly I'd be willing to stand by this one if pressed, but I've developed a distaste for type class instance names that I can't reasonably expect to be globally unique. It's very unlikely anyone will be importing the contents of the Penultimate type class here, but if they did, having something called inductive in scope is kind of unhelpful. At the very least I'd probably tack a Penultimate suffix on each method name. Maybe that's unreasonable. I don't know—it probably doesn't matter much either way.

Other than that it looks pretty good to me!


Extracting an IP address from a hosts file by hostname

You can probably get by with this:

ip = File.read(hostfile).match(/^\s*([\d\.]+)\s+\b#{hostname}\s*$/)[1]

A more "complete" way might be to do:

hosts = File.foreach(hostfile)
  .grep(/^\s*([\d\.:]+)/)
  .map { |line| line.strip.split(/\s+/).reverse }
  .to_h

Which gives you a { hostname => IP } hash for everything in the file (IPv6 included for good measure). I.e. you'd just do

ip_address = hosts[hostname]

to get the IP address.

For your current code:

  It seems a little ugly and long

It is a long line, but you can always break it up. You can chain off of the end keyword just as well as off of a }, so something like this would help readability:

File.foreach(hostfile).grep(/\b#{hostname}\b/) do |m|
  /^([0-9\.]*)\b.*/.match(m)[1]
end.first

In the 2nd approach above, I could've used grep to both match and map the lines, but I thought it nicer to separate the two.

  It also seems strange to me that I need to add .first on the end in order to get the IP address string out of the array returned by grep

grep is being called for each line, meaning it'll produce an array of matching lines. Hence why you need first. You're basically filtering and mapping every line in the file. After filtering there's (presumably!) only one line left, but it'll still be in an array.

You could use detect if you're only interested in the first matching line:

line = File.foreach(hostfile).detect { |line| line =~ %r[\b#{hostname}\b] }

That'll give you only the line containing the hostname you're looking for (or nil), which you can then parse further.


Your naming looks to be a little bit inconsistent

@Path("/reg")

userM.reg(email, pass)

First, reg seems to be short hand for something (registerUser?).  Unless there's some really compelling reason to leave it abbreviated, you should change the spelling so that the next person to read the code can figure out what you mean.

The inconsistency is that you seem to be using reg as a verb in the (again, poorly named) userM object, and also using it as a noun (@Path tells us that this is part of the URI, which would normally identify a resource).

Now, you will find those that argue, reasonably, that the characters in the URL don't make the link restful or not restful.  Nonetheless, there's some expectation that, if you are asking the server to insert an item into a collection, then the URL is a representation of the collection, rather than the act of inserting into it.

Assuming that your choice of POST is correct, meaning that clients should not expect the change being offered to be idempotent, then I would expect an endpoint like /users, or /registeredUsers (if there is more than one user collection).


It is a bad idea for a constructor to contain non-trivial code.
Constructors should assign values to fields or another simple actions.
If you need complex initialization, you should use factory object or factory method


Looping over a list, checking a boolean and return value

I'd change Boolean.FALSE to false and Boolean.TRUE to true. Using the constants objects from Boolean is rather unnecessary since the method returns with primitive boolean.


Python app-level document/record locking (eg. for MongoDB)

The above code will fail with multiple worker nodes (or processes).
To achieve atomic find-and-update, mongodb provides native solution (findOneAndUpdate, findAndModify, updateOne, updateMany).


Enable or disable sections of a model according to user input

Since we're using Bash, we can combine the echo and read by using -p (prompt) argument to read like this:

read -p 'Enable aggregation [on/off] ' agg

I slightly adapted the form of the prompt to be more like common conventions from other interactive programs.

It's a good idea to validate the user input.  If On is entered instead of on, then the user might be surprised to find it's equivalent to off!

unset agg
until [ "$agg" = on ] || [ "$agg" = off ]
do
    read -p 'Enable aggregation [ON/off] ' agg
    agg="${agg:-on}"
done

This also adds a default; that may or may not be appropriate here.

The multiple sed invocations could be combined into one:

sed -e "3s/^/!/" -e "4s/^/!/" -e "5s/^/!/" scm_code_ex.txt

Since we want to perform the same operation on a range of lines, we can use an address range (3,5), and we can write the output file in place of the original (-i):

sed -i -e '3,5s/^/!/' scm_code_ex.txt

(The form you tried didn't work, because you need to separate the { from the enclosed command inside the group - but since there's only a single command, we don't need a group.)

We probably don't want to be doing the in-place editing: it's better to have a pristine (read-only) source file, and always generate the output file starting from there (we can even prefix it with a "DO NOT EDIT" comment).  This makes it more amenable to generation by Make, as well as saving your bacon if you ever make a mistake in the script.

Instead of duplicating the commands for aggregation, one thing we can do is build the appropriate sed command using the options, then run it once.  I would do this using Bash array variables:

replacements=()
[ "$auto" = on ] || replacements+=( -e '3,5s/^/!/' )
[ "$agg" = on ] || replacements+=( -e '10,12s/^/!/' )

sed -e "${replacements[@]}" scm_code_all.txt >scm_code.txt

Now we no longer need all those if/elif/fi blocks, and we no longer double the code size each time we add a new option.

The remaining fragile element in these scripts is the line-number addressing; this makes it hard to see which lines will be enabled or disabled, and it's hard to keep track when we add or remove lines from the source file.  We can add some markers to this file (I'm assuming that ! begins a comment in that language):

code
code

!##BEGIN AUTO
code-auto
code-auto
code-auto
!##END AUTO

code
code

!##BEGIN AGG
code-agg
code-agg
!##END AGG

code
code

We can then use those lines for addressing:

[ "$auto" = on ] || replacements+=( -e '/^!##BEGIN AUTO/,/^!##END AUTO/s/^/!/' )
[ "$agg" = on ] || replacements+=( -e '/^!##BEGIN AGG/,/^!##END AGG/s/^/!/' )

We can reduce the amount of repetition if instead of using variables for auto and agg, we keep a list of features, and loop through them:

features=()
for i in auto agg
do
    while read -p "Enable '$i' feature? [YES/no] " f
    do case "${f,,}" in
           y|yes|on|true|'') features+=($i); break;;
           no|off|false) break;;
       esac
    done
done

replacements=()
for i in ${features[*]}
do
    replacements+=( -e "/^!##BEGIN ${i^^}/,/^!##END ${i^^}/s/^/!/" )
done

And we can combine the two loops into one, thus:

replacements=()
for i in auto agg
do
    while read -p "Enable '$i' feature? [YES/no] " f
    do case "${f,,}" in
           y|yes|on|true|'')
               replacements+=( -e "/^!##BEGIN ${i^^}/,/^!##END ${i^^}/s/^/!/" );
               break;;
           n|no|off|false)
               break;;
       esac
    done
done

With these changes, we no longer need to remove any intermediate temporary files, but I'll note that the wildcard used is rather broad and may catch the user's own temporaries.  Also, the temporaries are in the current working directory, not respecting $TMPDIR.  To fix both of those, I prefer to create a temporary directory with mktemp -d, and trap the EXIT signal to remove all temporaries:

tmpdir=$(mktemp -d)
trap 'rm -r "$tmpdir"' EXIT

I hope this answer gives some food for thought.  If you want a review of your code after considering the above, feel free to ask a new question with your amended code.


Yes/no handling
Don't repeat yourself or reinvent the wheel. There already exists a distutils.util.strtobool that does exactly what you're trying to accomplish:

Convert a string representation of truth to true (1) or false (0).
True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

You can convert the string to lowercase beforehand. Since strtobool raises a ValueError, your yes/no handling can be written succinctly like so:
while True:
    try:
        question=input('\033[0;0m' + "Would you like to play again? ")
        i = not strtobool(question)
        break
    except ValueError:
        print('\033[;1m' + "Please only enter yes or no. ")

Notice that strtobool returns 1 for truthy values, yet for some reason you have i == 0 represent "keep going", which is confusing. So I used not here, but I recommend either changing that or using proper bools here for readability.


Comments on Design
I like the idea in general but usually when I introduce a lock in a scope, the scope is usually the whole method so it does not look that ugly:
void MyClass::myMethod()
{
    lock_guard lock(sync);    // sync is an accessible mutex object
    do_protected_stuff();     // may throw, but the mutex is released regardless
}

But lets assume that you have situations that make your style worth while in using:
Now my problem is that you have situations where things are not as they seem:
with_lock_guard (sync)
    runit = boost::thread(get_it_yourself);
    cout << "Starting... ";
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    cout << "OK!  Z = " << zz << endl;

Only the first statement is inside the lock. Yet I get no compiler error (yes I know silly error but the idea is that you should design your class so that it is really hard to abuse even accidentally):
I would change the design slightly so that it used a lambda:
with_lock_guard(sync, []()
{
    runit = boost::thread(get_it_yourself);
    cout << "Starting... ";
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    cout << "OK!  Z = " << zz << endl;
});

This way it will be harder to abuse accidentally.
Comments on code:
If you are going to have operator bool() conversion method then at least make it explicit so it can not accidentally be abused. But since you are calling this from your own macro I would have a method that you explicitly call. This makes the code easier to understand.
https://stackoverflow.com/questions/6242768/is-the-safe-bool-idiom-obsolete-in-c11
// Prefer to use explicit on bool to prevent accidental usage:
explict operator bool() { bool ret = new_lock; new_lock = false; return ret; }

But I would do this:
#define with_lock_guard(SYNC)   for (with_lock_ lk_(SYNC); lk_.MakeSureWeRunOnceOnly(); )


Calculating set difference of lists with or without intermediate variables

I'd prefer

public void checkRetrievedIds( List<Integer> expectedIds, List<Integer> retrievedIds ) {
    Set<Integer> difference = Sets.difference(
        new HashSet<>( expectedIds ),
        new HashSet<>( retrievedIds )
    );

    createInvalidationEvents( difference );
}

You're right that your first version is somewhat verbose for the task.  However, there are some good reasons to separate out the difference calculation from the function call.  First, what if you wanted to do something else with the difference?  You'd immediately have to refactor to something like this version so as to have the difference to manipulate.

I'm also somewhat leery of a function that consists entirely of chained calls.  One has to sort of mentally unwrap it in order to get to the real meaning.  They often make a lot of sense when writing them, as you know exactly what you are trying to accomplish.  They can make a lot less sense six months down the road.

Separating the two allows us to basically have one line that calculates the set difference of two lists while the other line makes use of that difference.  That seems a reasonable division of responsibility.

Another possibility would be to change the signature of createInvalidationEvents to take two lists as input.  Then you wouldn't need checkRetrievedIds.  Of course, that wouldn't work if createInvalidationEvents is used elsewhere with the current signature.

A third possibility would be to calculate the set difference in whatever calls checkRetrievedIds.  This would also get rid of checkRetrievedIds.

As written, checkRetrievedIds is simply an alias for createInvalidationEvents with a different method signature.  Without other context, it's unclear why you need it.


use good variable names: If you use randomNumberinstead of rn and userNumber instead of number then the 'if'-statement changes to

if randomNumber == userNumber :

and your comment in this line becomes obsolete.

The current version of your program can be rewritten without any variables at all:

import random
if 1<=int(input("Guess a number, see if you're right!"))<=10:
  if random.randint(1,10) == 1:  # User succeeds, propability=1/10
      print("You got it.")
  else:  # user fails, propability=9/10
      print("Sorry.")
else: # this input number cannot succeed
    print("Sorry.")

use comments wisely: Don't comment to much. If you change your code then you have to change your comments, too. Otherwise the comments are contradictory to the code. So your comment in the first lines says that 'Yes' is a possible answer of your program, but this is not true.

A comment like

# Instruct user to guess a number.

is not useful. The purpose of the statement it described is immediate clear.

docstrings:
The text  in the first line of the module that describes the module (docstring) should be a '''-string  and not a #-comment.

user interface:

An  input text like

"Input an integer number between 1 and 10 and press <return>!"

would be more useful.

If the user enters a value that is not a number, e.g. the string 'a', an error message like

Traceback (most recent call last):
  File "python", line 5, in <module>
ValueError: invalid literal for int() with base 10: 'a'

is printed. This is not very user friendly. Maybe it is also useful to warn a user if he enters an integer less than 1 or greater than 10.

very pedantic: In accordance to the other output you print, if a user fails you should print Sorry. instead of sorry. Sorry! may me even better. The exclamation mark may be also appropriate here:

Guess a number, see if you're right!

Maybe you should ask he user again for input if invalid  input was entered.

don't use Magic Numbers:
 Use something like

MAX_NUMBER=10
....
random_number=random(1, MAX_NUMBER)

Also other  occurrences of 10 should be replaced by MAX_NUMBER, e.g. in the input text.

format: Placing an empty line after almost every line of code blows up the code but does not make  it more readable. Use empty line to structure the code. So I think it makes no sense to separate the 'if' and the 'else'-block of an 'if'-statement by an empty line, because they belong together.


What is the best to select a javascript object property at any depth?

From a once over:

getMappedDataProperty is a clumsy name, how about getProperty.
receiving a string is functionally the same as an array with 1 entry, so you could
map = (typeof map === 'string') ? [map] : map;
There is no need for the underscores for i and len, also, I would rather see length than len
the use of the temporary variable m is overkill, you could go straight for result = result[map[i]];

I would counter propose:

getProperty: function( o, map )
{
  map = (typeof map === 'string') ? [map] : map.slice();
  var result = o;
  while ( map.length ) {
    result = result[ map.shift() ];
  }
  return result;
}

I would love to know the context in which you use this, since I cannot see a good use case for it.


Read first column of a space delimited file with Java 8 stream

Your code will fail with a single-column input like:

one
two
three
four

Additionally, it will produce odd results with space-prefixed lines like:

normal line
   spaceprefixed line

The reason it will fail is because the Files.lines method trims the line terminators off of each line, so, the input to the regex will be just one, etc. Since there's no whitespace after the one, the match will fail, and the method will return null.

You should consider an alternative approach of doing a limited split, and returning the first value:

private final static Pattern pattern = Pattern.compile("\\s+");

public static String firstWord(String s) {
    return pattern.split(s, 2)[0];
}

This also changes the logic slightly because empty lines will return empty-string, instead of null.

Additionally, your code will match "     spaceprefixed" from "     spaceprefixed line" whereas my code will consider the leading space to be a separator (and not part of the first word), and will match the empty string "" from "     spaceprefixed line"

In other words, I disagree with some of the handling you have with edge cases.

I would handle the edge cases in a different way in the stream too:

List<String> x = Files.lines(Paths.get("/tmp/testfile"), Charset.defaultCharset())
            .map(line -> firstWord(line))
            .filter(word -> !word.isEmpty())
            .collect(Collectors.toList());


Proper implementation of generic repository

To get it to work, use IEnumerable<T> instead of List<T> as it's covariant:

public interface IRep<out T>
{
    IEnumerable<T> GetAll();
}

public interface IEntity
{
    int Id { get; set; }
}

public class Customer: IEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Product: IEntity
{
    public int Id { get; set; }
    public string Code { get; set; }
    public decimal Price {get;set;}
}

public class RepProduct: IRep<Product>
{
    public IEnumerable<Product> GetAll()
    {
        List<Product> list = new List<Product>();
        list.Add(new Product() {Id=1, Code = "burger", Price = 2.99M});
        list.Add(new Product() {Id=1, Code = "fries", Price = 1.99M});
        list.Add(new Product() {Id=1, Code = "pepsi", Price = 1.99M});
        return list;
    }
}

public class RepCustomer: IRep<Customer>
{
    public IEnumerable<Customer> GetAll()
    {
        List<Customer> list = new List<Customer>();
        list.Add(new Customer() {Id=1,Name="Fred", Age=44   });
        list.Add(new Customer() {Id=2,Name="Victoria", Age=13   });
        list.Add(new Customer() {Id=3,Name="Kiefer", Age=10 });
        return list;
    }
}

void Main()
{
    IRep<IEntity> rep = null;

    rep = new RepCustomer();
    Console.WriteLine(rep.GetAll());

    rep = new RepProduct();
    Console.WriteLine(rep.GetAll());
}


Calling a MySQL procedure with an arbitrary parameter on a GoDaddy website

As a rule of thumb in code security if you don't know what attacks you've secured your code from then it is not secure.  At least you're considering that your code might have issues and looking to remedy them when many don't.

Basically consider the ID 7254872364;drop table users;// or some variant - what SQL statement is that going to produce as a string and is it what you thought would get?  I should get that will get through real_escape_string quite nicely.

One thing that will help is to rewrite your code to use prepared statements.  They are not a magic bullet (nothing is) but they will give you code that is an order of magnitude more secure than you have today.

These questions on Security StackExchange should make for some interesting further reading:-

SQL injection — but why isn't escape quotes safe anymore?
Are prepared statements 100% safe against SQL injection?

[Edit: Sorry, missed that your host doesn't provide support for prepared statements.  GoDaddy do support it but you have to enable it in the control panel.  See Enable MYSQL-PDO in godaddy windows server and if you can't get it solved it might be best to tell GoDaddy where to go]

It's a good practice to assume that all user input is hostile until it you've established otherwise, which doesn't seem to be happening in this code.  Sanitize anything that comes from outside your system at every point of entry interaction including those pesky Url parameters, fields, cookies - at some point the odds are that it will be hostile.  If the ID's will take a certain form (x digits for example) then validate them and stop processing with an error if that validation fails.


Nested loop in lisp to process a 2d array - what's good style (with and/or without loop macro)?

A few comments about your code:

Why introduce a new variable n copy of another variable? If you want to be more concise you could use n and m insted of row and col (that I don't like because they are singular names, while they represent the number of rows and of columns).
Why define new-arr before the test and then assign it after the test of squareness? Don't by shy of use let as many times as you need, to introduce variables when they are really necessary.
Use assert instead of cond to check for correct parameters: in this way you give the user the opportunity of correct them, and produce a shorter and more readable code.
Why initialize the new array to a value nil which is immediately overwritten?
The fist do could return the result, so to avoid the last line of the function.
Use the primitive function 1+ instead of summing by 1.
Document the function with a comment about its scope as first form of the body of the function.

So, after this first set of comments, the function could be rewritten as:

(defun quarter-turn (arr)
  "rotate a square matrix 90° clockwise"
  (let* ((dim (array-dimensions arr))
         (n (first dim))
         (m (second dim)))
    (assert (= n m) (arr) "The argument is not a square array.")
    (let ((new-arr (make-array dim)))
      (do ((i 0 (1+ i)))
          ((= i n) new-arr)
        (do ((j 0 (1+ j)))
            ((= j n))
          (setf (aref new-arr j i) (aref arr (- n i 1) j)))))))

DO versus LOOP

As you have already noted, in this case do is more verbose than loop. I think that in a case like this they are more or less equivalent (just a personal opinion). I would prefer the loop form not only because it seems to me slightly more concise, but also because it is more “natural” for me to think of a classical nested loop for a bidimensional array in terms two nested loop forms:

(defun quarter-turn (arr)
  "rotate a square matrix 90° clockwise"
  (let* ((dim (array-dimensions arr))
         (n (first dim))
         (m (second dim)))
    (assert (= n m) (arr) "The argument is not a square array.")
    (let ((new-arr (make-array dim)))
      (loop for i below n
            do (loop for j below n
                     do (setf (aref new-arr j i) (aref arr (- n i 1) j))))
      new-arr)))


Validating an entity using a dynamic list of predicates

You can simplify your extension method a bit as so:

public static Boolean IsValidEntity<T>(this T entity, IEnumerable<Predicate<T>> predicates)
{
    return predicates.All(p => (bool)p.DynamicInvoke(entity));
}

This is a bit better for readability, and shouldn't have any cost in efficiency as LINQ short-circuits with All. I also switched your List for IEnumerable, just to save an unnecessary ToList call if you end up with some other kind of collection.

You should also check if you really need that DynamicInvoke. If not, you can further simplify to

public static Boolean IsValidEntity<T>(this T entity, IEnumerable<Predicate<T>> predicates)
{
    return predicates.All(p => p(entity));
}

Depending on your wider design, this might be enough. However, since you asked about extensibility, you can see that having to build predicates isn't the nicest business. For example, you had your 'less than 8' predicate. What if elsewhere in the code you wanted 'less than 7'? You'd have to repeat the (albeit very simple in this example) logic, just with a different number.

If you tried to refactor this to adhere to the Don't Repeat Yourself principle, you might then end up with something like a PredicateFactory class which exists purely to build common predicates based on parameters. But this isn't fantastic design either. It would likely end up as a monolith of public methods without much cohesion, and violate the open/closed and single responsibility principle.

A better option might be to create an interface like:

interface IEntityValidator<T>
{
    bool IsValid(T Entity);
}

Instead of predicates, you can now create and use classes which implement this interface. This gives better adherence to the design principles I mentioned before, and allows you take full advantage of polymorphism (for more complicated validation you might find that inheritance is useful, for example). At this point your original method would be:

public static Boolean IsValidEntity<T>(this T entity, IEnumerable<IEntityValidator<T>> validators)
{
    return validators.All(v => v.IsValid(entity));
}

To my mind, that line is simple and readable enough that it may no longer warrant its own method, especially its own extension method which will apply to every single type. Validation doesn't seem like something that would be done in too many places, so even if you didn't like that line, you might just move it to a private method somewhere. That's more a matter of taste, though.


Data marshaling wrapper for a TCP server

The wrapper seems pretty good to me.  The only change you might consider is that CreateWrapper really only needs to run once for each type; since these are structs it can return copies of the same empty object each time.  Something like this should work:

static class EmptyHolder<T> where T : struct
{
    public static T EmptyInstance;
    // assign EmptyInstance in static constructor
}

and then:

public static unsafe T CreateEmpty<T>() where T : struct
{
    return EmptyHolder<T>.EmptyInstance;
}

Of course there's a tradeoff of an uncollectable memory for each type you call this with.  And with anything performance-related, you'll need to measure to see if it delivers any benefit.  The original code should be pretty fast so maybe it's not significant.

There shouldn't be any danger in no matter how often you call stackalloc, by definition it's not possible for any two such calls to affect the same stack at the same time.  And there's no danger of any sort of recursion that would have more than 1 of these allocations on the same stack since the block is freed at the end of this function.


Not only is this difficult to read, it's also inefficient.

Cache your duplicate LINQ lookup to save time and make it more readable.

As for using the ternary operator, that's up to you, but I prefer to use a full if statement when the line gets too long.

Additionally swap out "" for String.Empty, it shows your intent better, and also makes it more strongly contrast against " "

var state =ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName));

if(state.Value != null &&
    state.Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage)))
{
    return string.Empty;
}
else
{
    return " ";
}

I'm assuming this next bit executes elsewhere, because the two return statements above would otherwise make this unreachable code.

Use var when the type is obvious from the right hand side of the assignment (although in this case it's a little debatable, I'd personally use var here because the variable name mimics the type).

You have a typo in your second comment.

//Looks in a dictionary for a key called parameterName
var modelState = ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value;
//If I could find it I look for any error associated to that and I return it as a single string
if(modelState.Value != null &&
    modelState.Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage)))
{
    return string.Empty;
}
    else
{
    return " ";
}

Finally, structure-wise I'd recommend converting the if-statement above into a separate method, since you call it in multiple places. This will leave a single point to modify during refactoring.

private string ConvertModelStateErrorsToString(ModelState modelState)
{
    if(modelState.Value != null &&
        modelState.Value.Errors.Any(x => !string.IsNullOrEmpty(x.ErrorMessage)))
    {
        return string.Empty;
    }
        else
    {
        return " ";
    }
}

Leaving your other code samples as:

var state =ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName));

return ConvertModelStateErrorsToString(state);

And the other sample:

//Looks in a dictionary for a key called parameterName
var modelState = ViewData.ModelState.FirstOrDefault(x => x.Key.Equals(parameterName)).Value;
//If I could find it I look for any error associated to that and I return it as a single string
return ConvertModelStateErrorsToString(modelState);


I'm assuming that names have been changed to protect the innocent, but just in case they've not been...

These are terrible names. All of them.

Function names should have verb-noun names and be PascalCased. So instead of CUSTOMFUNCTION should be GetCustomMatch (or something like that. I can't say because you've ommitted any actual names...)
Parameters should be camelCase and tell me what kind of data
should be passed in and NEVER should they be numbered the way
this is. So, maybe this instead (again, I have to guess because I
have no clue):

Function GetCustomMatch(LookupRange As Range, lastYearsSalesRange as Range, iJustDontKnowWhatThisIsRange as Range) As String

Don't use hungarian notation. Just... please don't. It should be
killed with fire and buried out back.

Other Stuff

Some of your "Values" are used in multiple places. Store them in a
constant and use that constant anywhere they show up. (Of course,
use meaningful names for them.)
I have a feeling that sTableMatchingFieldLookup and ...Result should be actual ranges instead of strings. String typing is bad. If you insist on keeping them as strings, store the values as constants.
You should be able to pick up some performance by setting Application.Calculation = xlCalculationManual. This Stack Overflow answer has a pretty good example of what you're trying to do.

Things you did right

You exit early if you've already found a match before performing the lookup rather than nesting if statements.


I think what i was missing was a "builder" class that could take care of the construction, and allow the interfaces to be returned.
Not all transport types needed to be "started", so i left that concern to the builder of the specific bus (i.e. MQTT transport would have different requirements to Kafka for instance).
Any "stopping" can be done on dispose - any one not wanting to receive messages before then can unsubscribe via the ISubscriber interface.
So we build the base MessageBusBuilderBase class:
public abstract class MessageBusBuilderBase
{
    private MessageBusDiagnostics messageBusDiagnostics;
    public bool IsDebugEnabled => messageBusDiagnostics != null;

    protected abstract Task<ITransport> NewTransportAsync(ILoggerFactory loggerFactory, Func<TransportMessage, Task> receiveMessage);

    public async Task<BuiltInterfaces> CreateAsync(IMessageSerializer[] serializers, ITypeIdentifier typeIdentifier, ILoggerFactory loggerFactory, bool isDebug = false)
    {
        var serializerRegistry = new SerializerRegistry(serializers);
        var receiver = new MessageDeserializer(serializerRegistry, typeIdentifier, loggerFactory.CreateLogger<MessageDeserializer>());
        var transport = await NewTransportAsync(loggerFactory, receiver.ReceiveMessageFromTransport);
        var publisher = new MessagePublisher(serializerRegistry, transport, typeIdentifier);
        var subscriber = new MessageSubscriber(transport);

        // chain up event handler functions
        receiver.OnMessageDecoded = subscriber.ReceiveMessageFromDeserializer;

        if (isDebug)
            this.messageBusDiagnostics = new MessageBusDiagnostics(transport, loggerFactory.CreateLogger<MessageBusDiagnostics>());

        return new BuiltInterfaces(publisher, subscriber);
    }
}

And the specific derived class for MqttMessageBusBuilder:
public class MqttMessageBusBuilder : MessageBusBuilderBase
{
    private readonly MqttSettings settings;
    public MqttMessageBusBuilder(MqttSettings settings)
    {
        this.settings = settings;
    }

    protected override async Task<ITransport> NewTransportAsync(ILoggerFactory loggerFactory, Func<TransportMessage, Task> receiveMessage)
    {
        var logger = loggerFactory.CreateLogger<MqttMessageBusBuilder>();
        logger.LogDebug($"{nameof(MqttMessageBusBuilder)} is creating a new {nameof(MqttConnection)} and will connect to {this.settings.Server}:{this.settings.Port}.");

        var connection = new MqttConnection(this.settings, receiveMessage, loggerFactory.CreateLogger<MqttConnection>());

        await connection.StartAsync();
        logger.LogDebug($"{nameof(MqttConnection)} has been started via {nameof(MqttConnection.StartAsync)}");

        return connection;
    }
}

With the above, we now have the interfaces chained correctly, and can register the instances with a inversion of control container clearly separating the concerns of publishing and subscribing:
var mqttBusBuilder = new MqttMessageBusBuilder(settings);
var serializers = new [] { MessagePackSerializer };
var idStrategy = new IdentifyUsingTransportHeaders();
mqttBusBuilder
    .Create(serializers, idStrategy, loggerFactory, var out publisher, var out subscriber);

container.RegisterSingleton(publisher);
container.RegisterSingleton(subscriber);

With regards to "stopping" the bus, I could create a BusManager class to manage a list of created busses and call StopAsync on call - alternatively will just perform this transparently by stopping in Dispose() and let that be a concern of the bus itself as i see other busses do not have Start or Stop functions so I shouldn't let that be the driver of my interface design.


Here are my thoughts:

Good use of arrow functions where appropriate. If you really wanted to, you could shorten some of those small functions- e.g.:

function ensureNumber(input) {
    if (Number.isInteger(input.value)) {
        return '';
    }
    return 'field must be number';
}

Could be shortened to a single line:

const ensureNumber = (input) => Number.isInteger(input.value)?'':'field must be number';

I also like the use of the spread operator when getting the errors back from the mapped validation for a field.
Depending on how the validationResult is used, a POJO could be used instead of a Map to utilize less memory, though that might not be a concern. A POJO doesn't have .forEach like Map would (though one could iterate over the keys of a POJO). Apparently when using an ES-2015 compliant engine, the key order is maintained.
Bearing in mind that it might not be preferable/possible to update the DOM, one could apply class names to the inputs/textareas/selects/etc. and then use Document.getElementsByClassName() instead of querySelectorAll() but that might only lead to a slight performance gain.


Fill an array of objects with some default object

I see a few ways this can be improved.

First, you are creating the template variable as a copy of the defaultObject, but then you are inserting defaultObject rather than template. I am going to assume this is a bug.

I would also say that there is not a big reason why you should have a defaultObject, then create and modify a copy to add. Just create objects on the fly.

Second, you are using a while loop, but constructing it like a for loop (loop variable, incremented every iteration). You actually don't even use the loop variable, so it can be removed completely. There is also a second potential bug where you are checking against arr.length + temp in your conditional, but arr.length increases every time you add an element to the array, so you are counting by 2's instead of by 1's.

Lastly, the name fillRemaining does not clearly describe what the function is supposed to do. Since it is padding onto the end of the array, perhaps padArrayWithDefault or something similar might be more descriptive.

Here's what I would suggest:

function padArrayWithDefault(arr, n) {
    while(arr.length < n) {
        arr.push({
            "id": new Date().getTime(),
            "name": ""
        });
    }
}


class Program

For clarity it would be nice if the main class and method would be declared public.
Also that name is not that good, you should find a better one.

//------------------Variables------------------------

If you need such comments, I'd argue that there is something wrong with your class layout.

double frameInterval = 1000/30;
Stopwatch msstopwatch = new Stopwatch();
Stopwatch tpsstopwatch = new Stopwatch();
int tpscount = 0;

Are these variables used outside of your main class? If no, than these should be private. Everything should be the least accessible as possible, for clarity and encapsulation reasons.

static void Main(string[] args)

Same here, for clarity it should be public.

void Server()

That's a bad name for a function, even the simple Run() would have been a better choice.

Thread.Sleep(1);

Thread.sleep is not trustworthy, neither might be StopWatch.

If you do not have any constraint on ho much time needs to be between requests, then do not time it at all, perform the requests as fast as possible and if you've done 30 in this second, wait as precisely as possible for the next second.

Is this accurate enough for a real-time server over the internet serving multiple clients?

Definition of a real time Wikipedia:

A key characteristic of an RTOS is the level of its consistency concerning the amount of time it takes to accept and complete an application's task; the variability is jitter.[1] A hard real-time operating system has less jitter than a soft real-time operating system. The chief design goal is not high throughput, but rather a guarantee of a soft or hard performance category. An RTOS that can usually or generally meet a deadline is a soft real-time OS, but if it can meet a deadline deterministically it is a hard real-time OS.[2]

So my first guess as answer to your question would be: no.
However, the more sane approach to that question should be: What are your specs and does this fall into your specs?


Counting ways to form an amount using coins

How about something like this:

(defn shift-vector
  "Shifts v one to the left, insert shift-val at the right"
  [v shift-val]
  (conj (subvec v 1) shift-val))

(defn update-in-all
  "Updates ks in m with f applied for each value at k."
  [m ks f]
  (reduce (fn [m' k] (update-in m' [k] f)) m ks))

(defn fast-iterative-coinstacks
  "Returns the number of ways to form a coin stack with a total
  value of n with coins"
  [n coins]
  (let [max-coin (reduce max coins)
        initial-stacks (into [1] (repeat max-coin 0))
        process-stacks (fn [stacks]
                         (-> stacks
                             (update-in-all coins (partial + (first stacks)))
                             (shift-vector 0)))]
    (-> (iterate process-stacks initial-stacks)
        (nth n)
        first)))

Some explanations:

update-in works both with vectors and maps, and can update nested values as well,
the threading macro -> makes the flow of your code easier to follow,
iterate is a really convenient function that given f and x returns a lazy sequence of x, (f x), (f (f x))...
you can do a lot of things with reduce!


Unit test for class converting between DTOs and entities

@BeforeEach
void init(){
    ModelMapper modelMapper = new ModelMapper();
    passwordEncoder = new BCryptPasswordEncoder();

You're using actual implementation classes from your unit test.  This has implications in that you're also effectively testing these classes, so you have potential side effects from changes when you upgrade the library, performance / dependency considerations.  That said, it may be acceptable if you consider these to be reliable library methods with low performance impact/dependencies (nobody mocks out String for example), however if not you might want to consider mocks. I would probably mock out at least the PasswordEncoder, as this would make it easier to control the result of the encoded password.

You're also setting up these dependencies before each test.  There doesn't seem to be any need to do this, the same ModelMapper and PasswordEncoder could be used for all of the tests, so I'd tend to put it in @BeforeAll, or even when initialising the fields.

@Test
void encodePassword_correctly(){

Your other tests have three parts to their names.  It looks like they are 'methodName_source_result'.  MethodName seems to be missing for this test name.  Where possible, consistency really does make it easier for other people to understand to expect.

//THEN
assertNotEquals(registerUserDto.getPassword(), user.getPassword());

You don't really need to assert that the encoded password doesn't match the original password, if you're going to test that it matches with the password encoder as well.  It just adds noise to the test.

assertTrue(passwordEncoder.matches(registerUserDto.getPassword(), user.getPassword()));

This is checking with your encoder that the returned password would match.  As I've said, this is testing more than just your code, however it might be acceptable to you.  I'd prefer a pair of tests that explicitly test this interaction something like this:

@Test
void convert_fromRegisterUserDto_toEncodedPassword() {
    //BEFORE
    when(passwordEncoder.encode(any(String.class)))
        .thenReturn("encodedPassword");

    //WHEN
    ConvertMapper.User user = converterRegisterUserDto.convert(registerUserDto);

    //THEN, assert encodedPassword is mapped into returned user.
    assertEquals("encodedPassword", user.getPassword());
}

@Test
void convert_delegatesPasswordEncoding_toPasswordEncoder() {
    //BEFORE
    registerUserDto.setPassword("unencodedPassword");

    //WHEN
    converterRegisterUserDto.convert(registerUserDto);

    //THEN, verify correct password was encoded
    verify(passwordEncoder).encode("unencodedPassword");
}

Which assumes a mock setup in the field/init:

privatePasswordEncoder passwordEncoder = mock(PasswordEncoder.class);

void init() {
    // default to returning emptyString
    when(passwordEncoder.encode(any(String.class))).thenReturn("")

This test seems a bit redundant:

  assertEquals(User.class, user.getClass());

Do you really care if it's an actual instance of User, rather than a derived type?

assertEquals(registerUserDto.getUsername(), user.getUsername());

assertEquals always seems counter intuitive to me (I want the expected to be on the right).  So I tend to use assertJ:

assertThat(user.getUsername()).isEqualTo(registerUserDto.getUsername());

However, it can also be more descriptive to use constants in your tests to be more expressive.  This allows you to see at a glance where the tested information is coming from:

@Test
void convert_fromRegisterUserDto_isMappingCorrectly() {
    //Before
    registerUserDto.setUsername("UserName");
    registerUserDto.setEmail("A@B.C");

    //WHEN
    ConvertMapper.User user = converterRegisterUserDto.convert(registerUserDto);

    //THEN
    assertEquals("UserName", user.getUsername());
    assertEquals("A@B.C", user.getEmail());
}


I don't know what you mean by "more easily", but here are some comments on the code:
No error handling
In many statements like i=int(input());list.append(alphabet1[i-1]) you use user input directly to index a list, without checking if it is in range, or even if it is a number.
One wrong keystroke from the user and the whole program crashes.
Mixed code
You mix main script code with function definitions, making it harder to follow your program flow by hand, thus making your program harder to understand.
You should have your main program code follow all the functions in one coherent block, and it is even better to wrap it in its own main function, then use a construct like this:
if __name__ == '__main__':
    main()

Repetitive code
In both listtranspose and chooselist you write the same line 5 times over, just because you used separate variables for 5 (almost) identical lists instead of a list of lists.
Naming
Do not use list as a variable name! It is a Python builtin for creating new lists, and while Python is nice enough to allow you to overwrite it, this can both break future code and make your code harder to understand by others.
There are seemingly random one letter variables in your code h, g, e, it is hard to understand what they do.
Please give them more meaningful names.
Function alphabetlist actually prints the lists, so it would be better to name it print_lists or similar.
Also, there is no reason to hardcode the lists you print, since they already exists as list type variables.


Headers and namespace

We're missing headers

#include <algorithm>
#include <climits>
#include <cmath>
#include <vector>

Also, it appears the code assumes using namespace std.  Bringing all names in from a namespace is problematic; namespace std particularly so. See Why is “using namespace std” considered bad practice?.

Code the solution, and adapt it to fit

The use of the Solution class appears to be an artefact of your test environment.  Since the function doesn't need any state, prefer to write it as you normally would:

// we'll change this signature later
static int minimum_range(const std::vector<int> &A,
                         const std::vector<int> &B,
                         const std::vector<int> &C);

And then provide Solution as a thin wrapper around it, like:

int Solution::solve(std::vector<int> &A, std::vector<int> &B, std::vector<int> &C) {
    return minimum_range(a, b, c);
}

We can then call minimum_range from our test program much more simply:

int main()
{
    return
        + (0 != minimum_range(std::vector{5}))
        // add more tests here
        + (1 != minimum_range(std::vector{1, 4, 5, 8, 10}, std::vector{6, 9, 15}, std::vector{2, 3, 6, 6}));
}

We might make an exception to this general advice in the case of competitive performance-oriented programming; but then code review goes out of the window entirely, as speed trumps style and maintainability there.

Algorithm

The method is basically sound; it scales well to large vectors, but doesn't scale well to many vectors (as you note in the description).

For general code, prefer to think in iterators rather than indexes.  The code will be equivalent, but usable with more types than just vectors and arrays.

If we keep a collection of iterators (one for each of the arrays), then at each step, we want to advance the one that points to the smallest element (added complication - we need to tie-break by choosing the one that advances the least).  We have finished when that one reaches the end of its array; that means we also need to remember the end iterator for each array.  That means we end up storing a range for each input vector.

template<typename Iter>
struct range
{
    Iter current;
    Iter const end;
};

template<typename T>
range<typename std::vector<T>::const_iterator> make_range(const std::vector<T> &v)
{
    return {v.begin(), v.end()};
}

Now we can transform the vectors into ranges:

static int minimum_range(const std::vector<int> &A,
                         const std::vector<int> &B,
                         const std::vector<int> &C)
{
    auto range = { make_range(A), make_range(B), make_range(C) };

    auto minmax_range = std::minmax_element(range.begin(), range.end());

For the std::minmax_element() call to work, we'll need a suitable < operator in our range.  Add this:

bool operator<(const range& other) const
{
    if (current == end) return false;
    if (other.current == other.end) return true;
    auto a = *current, b = *other.current;
    if (a != b) return a < b;

    // it's a draw - which one advances least?
    if (current+1 == end) return false;
    if (other.current+1 == other.end) return true;
    a = current[1], b = other.current[1];
    return a < b;
}

Now let's go back to the algorithm and make it iterate:

auto minmax_range = std::minmax_element(r.begin(), r.end());
auto& min_range = minmax_range.first;
auto& max_range = minmax_range.second;
int best = **max_range - **min_range;

while ((++*min_range).current != min_range->end) {
    minmax_range = std::minmax_element(r.begin(), r.end());
    best = std::min(best, **max_range - **min_range);
    if (best == 0) {
        break;   // we can't improve on zero
    }
}

There's some stuff to explain there.  We create aliases for the minmax_range, which is a pair of iterators to range objects.  We use the dereference operator, which needs defining in range to give the current first element of the range:

auto operator*() const { return *current; }

The loop control starts by incrementing the lowest range - that needs an implementation:

range& operator++() { ++current; return *this; }

If that produced a range that has reached the end, then we've considered all the possibilities.

Inside the loop, we find the new min and max (remember that min_range and max_range still alias the members of minmax_range), and update best if required.

Extension to many inputs

We can now use a std::initializer_list to supply an arbitrary number of collections of any kind of (comparable) element.  I'll use C++17 for this (so we can write an implicit constructor for range, using a deduction guide).

#include <algorithm>
#include <vector>

template<typename Iter>
struct range
{
    Iter current;
    Iter const end;

    template<typename T>
    range(const T& v)
        : current{v.begin()},
          end{v.end()}
    {
    }

    explicit operator bool() const { return current != end; }

    auto operator*() const { return *current; }

    range& operator++() { ++current; return *this; }

    bool operator<(const range& other) const
    {
        return *this && (!other || *current < *other.current);
    }
};

// deduction guide
template<typename Container>
range(Container c) -> range<typename Container::const_iterator>;

template<typename Iter>
static auto minimum_range(std::initializer_list<range<Iter>> containers)
{
    using std::begin;
    using std::end;

    // Copy initializer list to read/write container
    std::vector r(begin(containers), end(containers));

    auto minmax_range = std::minmax_element(begin(r), end(r));
    auto& min_range = minmax_range.first;
    auto& max_range = minmax_range.second;
    auto best = **max_range - **min_range;

    while (++*min_range) {
        minmax_range = std::minmax_element(begin(r), end(r));
        best = std::min(best, **max_range - **min_range);
    }

    return best;
}

// convert containers to ranges and forward
template<typename... Args>
static auto minimum_range(const Args&... args)
{
    return minimum_range({range(args)...});
}

#include <list>
int main()
{
    return
        + (0 != minimum_range(std::list{5}))
        + (0.5 != minimum_range(std::vector{0.0}, std::vector{0.0}, std::vector{0.5}))
        + (6 != minimum_range(std::vector{6,30}, std::vector{10,12}, std::vector{6,15,30}, std::vector{12}))
        + (1 != minimum_range(std::vector{0, 6, 10}, std::vector{5}, std::vector{5}))
        // add more tests here
        + (1 != minimum_range(std::list{1, 4, 5, 8, 10}, std::list{6, 9, 15}, std::list{2, 3, 6, 6}));
}

I was unable to construct a test that proves the need for the tie-break in operator<, so I removed that code.  I shouldn't have written it in the first place without a test to exercise it, of course...


Computing intersections of a Polyline and a line

In getIntersectLon, I didn't find the docstring very helpful. For y = m*x + b, I think of m as rise over run, but in (a[0] - b[0]) / (a[1] - b[1]) I think I'm seeing run over rise. Ok. So we're multiplying 1/m by some delta_latitude, then we subtract, which seems like it could be related to the docstring. Maybe the docstring should talk about how the line described by two points intersects a line of latitude. Given that (lat,lng) are spherical coordinates, the approximation seems to have accuracy that falls off with increasing distance. Maybe this function should be named getLongitudeAt, with 1st parameter being the line of latitude.

It's not obvious to me that a[1] - b[1] shall be non-zero.

The latitudes == 0 test is maybe more stringent than you would like. Consider using abs(latitudes) < epsilon.

If you're mostly interested in sign changes, you might want to define sgn() and then work with small signum values.

def sgn(n):
    return math.copysign(1, n)

The comments "THIS IS THE {|END OF} THE CORE ROUTINE" suggest that you may want to break out a helper routine.


I think this is an interesting idea, although I haven't personally used it when building REST APIs.

Here's some code which shows how it could be done.

I tested the following code to ensure that it works. To test it:

make a todo model with a :name column
add resources :todos to the routes
visit localhost:3000/todos

...

# app/controllers/todos_controller.rb
class TodosController < ApplicationController
  include GenericController
  RecordClass = Todo
  def record_params
    params.require(:todo).permit(:name)
  end
end

You can see that there are only two points of customization in each controller.
You'll have to specify the RecordClass and your secure parameters method.

The following "generic controller" was built using Rails' default scaffold controller.
You can customize it to follow your own default controller logic.

# app/controllers/generic_controller.rb
module GenericController

  before_action :set_instance, only: [:show, :edit, :update, :destroy]

  def index
    @records = RecordClass.all
  end

  def show
  end

  def new
    @record = RecordClass.new
  end

  def edit
  end

  def create
    @record = RecordClass.new(record_params)
    respond_to do |format|
      if @record.save
        format.html { redirect_to @record, notice: '#{RecordClass} was successfully created.' }
        format.json { render :show, status: :created, location: @record }
      else
        format.html { render :new }
        format.json { render json: @record.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @record.update(record_params)
        format.html { redirect_to @record, notice: '#{RecordC;ass} was successfully updated.' }
        format.json { render :show, status: :ok, location: @record }
      else
        format.html { render :edit }
        format.json { render json: @record.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @record.destroy
    respond_to do |format|
      format.html { redirect_to records_url, notice: #{'RecordClass} was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    def set_record
      @record = RecordClass.find(params[:id])
    end


I'm not a scala/fp expert but here is my 2 cents.

Your code reads very much like you have read the definition on wikipedia and translated it into scala. As the wikipedia definition is written as a human implemented algorithm you end up with a very procedural approach.

A few specific things:

tabulaRecta - this is constant, making it a var is a massive code smell
makeFullkey - you use zipWithIndex but don't use c, just use index
why can't tabulaRecta be a function?
why create a fullKey - can't you compute the key char as a function?


Static web server with a bit of error handling

My initial reaction to this code is that it would be clearer if you bring some functions outside main = do.

One of the great things about Haskell is it's explicit type system and safety; your code doesn't leverage this as there are no function type declarations.


First non-repeated character in a string in c

Alex, it looks quite efficient. There are some issues that I see:

gets should never be used. Use fgets (but note that you will have to strip the trailing \n)
define main at the end to avoid the need for a prototype for repeat_ch
declare repeat_ch as static
your limit does not work as i is not incremented.  But why not stop on
reading an empty string rather than limit the number of loops?
NULL is normally defined as (void *) 0 so comparing a char with NULL is
wrong.  The compiler will warn you of that.  Just use 0 or better '\0'

In repeat_ch

function name is inaccurate - function looks for a non-repeated char.
the two // comments are noisy (ie. don't tell reader anything)
array would be better sized 256
p should be const
for-loops would be better

for (const char *p=string; *p; ++p) {
    array[*p] += 1;
}
for (const char *p=string; *p; ++p) {
    if (array[*p] == 1) {
        return *p;
    }
}
return '\0';


Find number of inversions in a given array

Here are two things that can speed up your code:

Using custom scanner instead of java.util.Scanner. You can create it using BufferedReader and StringTokenizer. It speeds up input significantly.
Avoiding allocation of left and right arrays inside invCount functions. To do it, you can rewrite your merge and invCount function so that they always use your initial array and take lower and upper bound indices. Merging would require additional buffer anyway, but it can be allocated only once (before  any merge is executed). So there would be only two array allocations per test case. It would probably make you code slightly longer and less readable, but it should make it faster.


Yes, you can reduce your markup!  How small?  This small:

Jump Session Outdoor Editon

Party

London

How?  With pseudo elements.  http://codepen.io/cimmanon/pen/sIgju

.module-wrapper {
  width: 20%;
  margin: 40px auto;
  padding: 10px 0;
  color: white;
  text-align: center;
}
.module-wrapper:before, .module-wrapper:after {
  content: '';
  display: block;
  height: 10px;
}
.module-wrapper > :first-child, .module-wrapper > :last-child {
  position: relative;
}
.module-wrapper > :first-child:before, .module-wrapper > :last-child:after {
  content: '';
  display: block;
  background-color: inherit;
  height: 10px;
  position: absolute;
  left: 10px;
  right: 10px;
}
.module-wrapper > :first-child:before {
  top: -10px;
}
.module-wrapper > :last-child:after {
  bottom: -10px;
}
.module-wrapper div {
  padding: 15px;
}
.module-wrapper .title {
  background: green;
}
.module-wrapper .type {
  background-color: red;
}
.module-wrapper .locale {
  background: black;
}

Now I know you're convinced that you don't need a CSS Preprocessor because you're certain that vanilla CSS is more readable.  But what if you wanted to change the size of your corner cut-outs?  How do you know which value you need to change?  Here's the Sass I used to generate the above CSS:

$corner-width: 10px;
$corner-height: 10px;

.module-wrapper {
  width: 20%;
  margin: 40px auto;
  padding: 10px 0;
  color: white;
  text-align: center;

  // the pseudo elements here prevent us from having
  // to do the math on the parent element's margin
  // to ensure there's no overlap from preceding/
  // following elements
  &:before, &:after {
    content: '';
    display: block;
    height: $corner-height;
  }

  > :first-child, > :last-child {
    position: relative;
  }

  // this is where the illusion of the "corner"
  // happens
  > :first-child:before, > :last-child:after {
    content: '';
    display: block;
    background-color: inherit;
    height: $corner-height;
    position: absolute;
    left: $corner-width;
    right: $corner-width;
  }

  > :first-child:before {
    top: -$corner-height;
  }

  > :last-child:after {
    bottom: -$corner-height;
  }

  // pretty up our child elements
  div {
    padding: 15px;
  }

  .title {
    background: green;
  }

  .type {
    background-color: red;
  }

  .locale {
    background: black;
  }
}

With the use of variables, I only need to make 2 adjustments and everything is recalculated for me.  Since the padding on the child elements and the margin on the parent element is not using the variables, I know that I am free to change them without it affecting the corners.

I am almost certain you mean "locale" for your class name, not "local".

If your CSS goes away, does your content still make sense?  If not, then you may need something more to give it some context.  A table may be appropriate here.

If you ever have a class called "title", that's almost a sure sign that you should be using an h1-h6 element instead.


Trimming whitespace from the beginning and ending of a file

A couple lines that bother me:

strncpy(str_buffer, tmp_strstrlen(tmp_str));

First, bear in mind that strncpy does not place a \0 terminator at the end of the string if the buffer size limit is reached (but it does in every other case!).  Thus, you have to be extremely careful when using strncpy.

Second, you're copying a large (256-byte) buffer into a smaller (100-byte) buffer, and you're (presumably) passing the length of the larger buffer to strncpy.  If tmp_str holds a string that's too long, you'll get a buffer overflow.

str_buffer[strlen(str_buffer) - 1] = '\0';

When the string has length zero (e.g. the file is empty or did not have a trailing newline), the array access will be out of range.  Otherwise, it will blindly delete the last character, even if it wasn't whitespace.

The lines that I highlighted will work... if you make a couple assumptions:

Every line of input has < 100 characters
The "whitespace characters" we want to delete always exist.

However, it looks like you're deleting the trailing newline returned by fgets.  I'm not even sure your code works.

If I were you, the first step I'd take is to come up with a concise specification of what you're trying to do.  Correct me if I'm wrong, but it sounds like you want to do this:

first line: s/[\t ]$//
last line:  s/[\t ]$//
Lines are terminated by '\n', except the last line might not have a terminator.

The s/[\t ]$// syntax is borrowed from sed, and means: if there's a '\t' or ' ' character at the end of the string, remove it (i.e. replace it with an empty string).

Then, observe that this operation can be done with a trivial amount of buffering.  When a newline is detected, hang on to the last character in the line, and only emit it when you're not on the first line and you know that more lines follow.  Thus, you don't need an intermediate file.

I recommend implementing a helper function with this signature:

int remove_trailing_spaces(FILE *in, FILE *out);

You should only need to fread and fwrite in large chunks.  The int lets you return an error code if one of these functions fails.


Portably get one character from standard input using standard library only

Your strcmp can be replaced with:

if (*prompt) {

Your last loop has issues. You effectively have both a precondition (feof) and a postcondition (next). You can replace the lot with:

while (!feof(stdin))
    if (getchar() == '\n')
        break;


Better way to calculate double-scattering diffraction using cartesian product of arrays?

You can replace:
d12 = np.array([a+b for a, b in list(itertools.product(p1.T, p2.T))])

with something like:
p1 = p1.T
p2 = p2.T
p3 = p3.T
d12 = p1[:,np.newaxis,:] + p2[np.newaxis,:,:]
d12 = my_d12.reshape((len(p1)*len(p2),2))

I find it most of the times easier to use the first index of an array for point_index and the second index for the dimensions, hence the .T's
With the use of the magic index np.newaxis at the right places you can create numpy array's of shape (M,N) with normal operators acting on arrays of shape (M) and (N).
With the reshape method d12 changed again to the shape in your original solution.


Deep copy linked list with a random pointer

public class Node {
 public int val;
 public Node next;

 public Node random;

 public Node(int val) {
  this.val = val;
  next = null;
  random = null;
 }
}

I understand that this was for a demo rather than production code, but it's really neither idiomatic C# nor good OO. I would have preferred

To use properties rather than fields;
To make the setters private, and move the clone method into Node;
Since the specification doesn't say anything about the contents, to parameterise as Node<T> rather than forcing the contents to be int (although maybe you clarified this with the interviewer and forgot to include it in the question).

I'm also not keen on exposing the Node class directly, although I'm not sure what API the enclosing LinkedList class would have with respect to the random links.

class CopyUtil {

 Node deepCopy(Node head) {

Node is public: why is CopyUtil internal and deepCopy private?

Why is neither the class nor the method static?

  if (head == null) return head;
  Dictionary < Node, Node > nodePool = new Dictionary < Node, Node > ();
  Node current = head;
  Node newHead = new Node(head.val);

  nodePool.Add(current, newHead);

Stylistically, I think there's far too much whitespace in Dictionary<Node, Node>. I suspect that you're applying C++ style guides designed to avoid parsing ambiguity with >> vs > >.

Why not Node newHead = getNode(nodePool, head)?

There is plenty of room for debate around when to use var, but I think few people nowadays would favour writing out an explicit type twice when calling a constructor.

  newHead.random = getNode(nodePool, head.random);

I think that with a bit of thought you could remove the special case head == null and this line and treat them as part of the general case in the loop.

  Node returnHead = newHead;

This is the first warning sign that newHead is a bad name. It's the head when first assigned, but later on it's really newCurrent.

 Node getNode(Dictionary < Node, Node > nodePool, Node current) {

I could have mentioned this above when the dictionary was created, but this is a better place: code to the interface, not the implementation. nodePool should be an IDictionary<Node, Node>.

Why current? That makes sense in deepCopy, but here a better name would be oldNode.

  Node ret = null;
  if (current==null) return ret;

I don't understand the point of ret given that you're not following the single exit principle.

  if (nodePool.ContainsKey(current))
   ret = nodePool[current];

This searches through the dictionary's data structures twice. The .Net API has a nicer way of doing it:

Node newNode;
if (nodePool.TryGetValue(current, out newNode)) return newNode;


Efficiently performing multiple nested grouping and mapping in Javascript

I don't see what lodash has to offer here.  With modern JavaScript it can be written quite tersely thus:
const events = data.reduce((events, { log_type, date }) => {
  const event = (events[log_type] || (events[log_type] = []));
  const match = event.find(({ x }) => x == date);
  match ? match.y++ : event.push({ x: date, y: 1 });
  return events;
}, { });

The first line inside the .reduce method creates the event array if it doesn't exist.
The second line finds the element with a matching date.
The third line, if a matching date was found, increments its y property.  Else, it adds a new element with the date.
For example:

const data = [
  {
    log_type: 'eventOne',
    date: '2020-08-27T20:00:00+00:00'
  },
  {
    log_type: 'eventOne',
    date: '2020-08-27T20:00:00+00:00'
  },
  {
    log_type: 'eventTwo',
    date: '2020-08-27T00:00:00+00:00'
  },
  {
    log_type: 'eventTwo',
    date: '2020-08-27T00:00:00+00:00'
  },
  {
    log_type: 'eventTwo',
    date: '2020-08-27T40:00:00+00:00'
  },
  {
    log_type: 'eventOne',
    date: '2020-08-27T00:00:00+00:00'
  },
];

const events = data.reduce((events, { log_type, date }) => {
  const event = (events[log_type] || (events[log_type] = []));
  const match = event.find(({ x }) => x == date);
  match ? match.y++ : event.push({ x: date, y: 1 });
  return events;
}, { });

console.log(events);


Add headers to colums and rows in Python - 2D array (list of lists)

Maybe this can help (if you don't want to use numpy):
headers = ['foo', 'bar', 'baz', 'other']
l = len(headers)

arr = [["xxx" for i in range(l)] for j in range(l)]

# adding top row
arr = [headers] + arr

# adding first column
headers_mod = ['Title'] + headers
new_arr = [[headers_mod[i]]+arr[i] for i in range(l+1)]

for i in new_arr:
  print(*i)

gives you the output as:
Title foo bar baz other
foo xxx xxx xxx xxx
bar xxx xxx xxx xxx
baz xxx xxx xxx xxx
other xxx xxx xxx xxx

Otherwise, when dealing with array manipulations in python try going with numpy, pandas, as they provide better operations like by giving option for axis, transpose, etc.


Map-reduce implementation for splitting strings

What about the following code. I've improved it by not using regular expressions (except one call of String.split, perhaps you already improved this by your own function split).

private final static char EXPR_VAR = '$';
private final static char EXPR_START = '{';
private final static char EXPR_END = '}';
private final static char EXPR_SPLIT = ',';

public static String replaceVariables(final String expression, final Map<String, String> vars) {
    if (expression == null) {
        throw new IllegalArgumentException("The expression may not be null!");
    }

    if (vars == null) {
        throw new IllegalArgumentException("The vars map may not be null!");
    }

    int firstIndex = expression.indexOf(EXPR_VAR);

    if (firstIndex == -1) {
        // nothing to replace, just return the expression
        return expression;
    }

    final StringBuffer sb = new StringBuffer();
    String tmpExp = expression;
    int lastIndex;
    String group;
    String parts[];

    while (firstIndex != -1) {
        // check if char after '$' is '{'
        if (tmpExp.charAt(firstIndex + 1) != EXPR_START) {
            continue;
        }

        // find ending sign '}'
        lastIndex = tmpExp.indexOf(EXPR_END, firstIndex);

        if (lastIndex > -1) {
            // complete pattern "${...}" found, append previous chars
            sb.append(tmpExp.substring(0, firstIndex));

            // get value inside pattern
            group = tmpExp.substring(firstIndex + 2, lastIndex);

            if (group.indexOf(EXPR_SPLIT) > -1) {
                // we have a pattern like "${xxxxx,xxxxxx}"
                parts = split(group, EXPR_SPLIT);

                if (vars.containsKey(parts[0])) {
                    sb.append(vars.get(parts[0]).substring(0, Integer.valueOf(parts[1])));
                } else {
                    throw new IllegalArgumentException("Key [" + parts[0] + "] not found in variable map!");
                }
            } else {
                // we have a pattern like "${xxxxx}"
                if (vars.containsKey(group)) {
                    sb.append(vars.get(group));
                } else {
                    throw new IllegalArgumentException("Key [" + group + "] not found in variable map!");
                }
            }

            // cut off previous chars from expression
            tmpExp = tmpExp.substring(lastIndex + 1);
        } else {
            // assuming, that if no right parenthesis is found, there is nothing
            // more to replace in this expression. So just get out of here!
            return sb.append(tmpExp).toString();
        }

        // find next pattern
        firstIndex = tmpExp.indexOf(EXPR_VAR);
    }

    // append rest of expression and return it as String
    return sb.append(tmpExp).toString();
}

With the following example values:

final String expression = "Hello! This is a ${1} ${0,2} of foo bla.";
final Map<String, String> vars = new HashMap<>();
vars.put("0", "Foo");
vars.put("1", "funny");

I have a benchmark of (1 million replaces):

// Original (yours):  1872 ms
// Improved (mine):    500 ms

So it's a bit more than three times faster than your implementation.
And the more values like {1,3} are in the input expression, the faster it is in relation:

Input:

final String expression = "${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ";

Benchmark:

// Original:   17455 ms
// Improved:    2855 ms

So, here it is more than six times faster!

Probably, it can be much more improved. But I just wanted to show you a possible direction so far!


No, there is nothing you're doing in that code that would result in memory leaks.

I found an article written by Jack Slocum (creator of the ExtJS framework) that details some basic steps to follow to avoid memory leaks. The original article is a bit dated and browsers have gotten a lot better at cleaning up memory, so I don't know how much of it still applies to the latest browsers (it certainly applies to older versions of IE and Firefox).

Here is the article: http://maxthonuser.blogspot.com/2008/02/easy-steps-to-avoid-javascript-memory.html

Relevant text (in case the link ever dies):

  It's as simple as these 3 steps:

  Never put anything in a DOM expando or property other than a primitive value unless you plan on cleaning it up.
  This is the most important rule of all. It may seem convenient to put your JS object in a DOM expando, so you can $() and get it, but don't do it. Sure, I know what you are thinking, I am being a little paranoid. There are lots of instances where putting a JS Object in a DOM expando won't cause a leak. That's true, but there are also many that will... some which are not so easy to detect (i.e. closures). So to avoid the possibility all together, I follow this simple rule.
  Clean up all your DOM event handlers on unload if there's a chance they could reference a DOM object.
  There's no reason to manually do this when there are libraries that do it automatically. I use YAHOO.util.Event for all my event handlers, it handles this for me automagically. Other libraries (prototype, dojo, etc) have some sort of mechanism to do the same thing, although I'm not sure how effective they are. If you look at the leak images above once again, you will notice almost all of them are in event related code of those libraries.
  Set your XMLHttpRequest onreadystatechange handlers to null when you are done with them.
  I use YAHOO.util.Connect for all my XHR connections and it uses a polling mechanism instead of readstate, so I don't need to do this anymore. If you can switch to YAHOO.util.Connect (or YAHOO.ext.UpdateManager built on top of it), I'd recommend it.


What you are already doing is a nice way of defining both the text for the button and the action for it at the same time.

As you're able to use Java 8, I would really recommend that you start using Java 8.

You might actually even want to consider migrating to JavaFX (that would probably require even more work though, but it could be a nice user interface upgrade).

One option, when using Java 8, is to do this:

JButton button = new JButton("A button");
button.addActionListener(this::doStuff);

private void doStuff(ActionEvent event) {
    ...
}

Or:

JButton button = new JButton("A button");
button.addActionListener(e -> this.doStuff());

private void doStuff() {
    ...
}

A different approach would be to do this:

JButton createButton(String text, Runnable action) {
    return new JButton(new AbstractAction(text) {
        @Override
        public void actionPerformed(ActionEvent ae) {
             action.run();
        }
    });
}

And then:

JButton button = createButton("A button", this::doStuff);
JButton button = createButton("Another button", () -> this.doStuff());


If you are using jQuery than why use vanilla JS DOM manipulation such as document.getElementById and others, why not use jQuery DOM manipulation like jQuery("#term")?


You can reduce the code duplication by moving the logic of comparing two values of which at least one is null to a separate method and call this method like this:

if (requestId1 != null && requestId2 != null) {
    fullCompare = requestId1.compareTo(requestId2);
} else {
    fullCompare = compareWithNull(requestId1, requestId2);
}

//...

if (security1 != null && security2 != null) {
    fullCompare = security1.compareTo(security2);
} else {
    fullCompare = compareWithNull(security1, security2);
}

//...

This reduces the code duplication, but you still have duplicate code, namely the procedure of checking whether both values are non-null and proceeding accordingly. So you could also move this logic into a separate method, for instance, into the compare(T, T) method of a separate comparator:

public int compare(T a, T b) {
    if (a == null) {
        return (b == null) ? 0 : -1;
    } else if (b == null) {
        return 1;
    } else {
        return a.compare(b);
    }
}

The good news is that you don't actually have to do this yourself, because since Java 8, there's a method Comparator.nullsFirst(Comparator) that does exactly that: It returns a comparator that considers null less than non-null (and equal to null), and if both objects are non-null, compares them using the provided comparator. The code sample above is in fact a slightly modified copy from the source of Comparator.nullsFirst(Comparator). Since you order non-null elements according to their natural ordering, you would just need to call Comparator.nullsFirst(Comparator.naturalOrder()).

So the first three comparison stages can be reduced to the functionality of these four comparators:

Comparator<String> nullsFirstStringComparator = Comparator.nullsFirst(Comparator.naturalOrder());

Comparator<HTMLLogLine> requestIdComparator = Comparator.comparing(HTMLLogLine::getRequestId, nullsFirstStringComparator);
Comparator<HTMLLogLine> securityComparator = Comparator.comparing(HTMLLogLine::getSecurity, nullsFirstStringComparator);
Comparator<HTMLLogLine> scenarioComparator = Comparator.comparing(HTMLLogLine::getScenario, nullsFirstStringComparator);

Judging by your comment, you already seem to be aware of the method Comparator.thenComparing(Comparator), so there's no need to explain how to chain those comparators using this method.

Unfortunately, the forth comparison stage does not fit into this pattern. Of course, you could ditch the nulls-first comparator and write your own generalized version of it which, instead of comparing the two values with null, checks a given Predicate against the values:

class CustomComparator<T> implements Comparator<T> {
    Predicate<? super T> predicate;
    Comparator<? super T> otherComparator;

    @Override
    public int compare(T o1, T o2) {
        if (predicate.test(o1)) {
            return (predicate.test(o2)) ? 0 : -1;
        } else if (predicate.test(o2)) {
            return 1;
        } else {
            return otherComparator.compare(o1, o2);
        }
    }
}

But I think there would only be a point in doing that if you need it more than once, because otherwise, it would not really be a remedy for code duplication, but just unnecessary code (since you don't really need it for the first three cases due to the pre-existing method Comparator.nullsFirst(Comparator)).


has_cycle in directed and undirected graphs

Comments regarding graphs:

The typical way to describe a graph G is G = {V, E} where V is the set of vertices and E is a bag of edges. The number of vertices is denoted n. The number of edges e [1]. Convention is to re-label the vertices by number either from 1 to n or from 0 to n-1 for the sake of programming conventions.

E is a bag because redundant edges matter in several important graph algorithms (e.g. minimum cut). If u and v are vertices then a non-directed edge is annotated u--v and a directed edge from u to v as u-->v.

For sparse graphs, the bag of edges is typically represented as a sequence [e.g. array or list] of tuples (u,v). For dense graphs an adjacency matrix of n rows and n columns is more typical ("sparse" and "dense" are terms of art, profiling to determine the data structure is appropriate).

Using mathematical language for variables and constants will make for more readable code, as will following conventions for vertex labeling and the data structures for edges.

[1] Art of Computer Programming: Volume 4A, Knuth.


getting inferences working with typescript pubsubber

I have a few pointers regarding your snippet.
Return type
Let's start with pubSubber function return type. It's very nice that typescript infers types, but it also a good way to make a mistake. The bad thing about it is that you can accidentally change the return type without knowing it. If you use this function somewhere in the app there is a chance that typescript will notify you about the change. But if you are creating a library and don't have tests, you will change the return type without any error.
Personally, I like the rule to always specify return type (unless using inline arrow functions). I even use the lint rule to enforce this.
Don't use any
Change any to unknown. In this case, maybe it doesn't matter at least at the moment, but in the future, you may change this code. With any you can do anything and typescript won't say anything. With unknown you can't do anything, unless you cast it or use type Type Guard
const subscribers = new Map<keyof T, Set<Subscriber<any>>>()

Don't use cast if possible
Let's look into this line.
const current = (subscribers.get(topic) || new Set()) as Set<
  Subscriber<T[R]>
>;

current real type is Set<Subscriber<any>>, but you cast it to Subscriber<T[R]>. But in this example, there is no point having cast at all, because even without it the code is correctly typed. This function implementation works with any type, so you can leave it as it is. As for the outer interface, it can be more strict.
const current = subscribers.get(topic) || new Set()
current.add(subscriber);
subscribers.set(topic, current);
return () => current.delete(subscriber);

Second example is a bit better:
const toCall = Array.from((subscribers.get(topic) || [])) as Subscriber<T[R]>[];
toCall.map((f) => f(data))

You already had one mistake because of this cast. Also, I don't see any reason to convert Set to the list. You can just loop the Set. And if you combine it with optional chaining, it will look like:
subscribers.get(topic)?.forEach(f => f(data));

Better typing
In the previous section, I mentioned casts. But removing casts in theory you lose some typings (adding also lose some typings, dilemma...). Let's try to have full correct typings without any cast. So to start with we need to change Map to Object. Map types do not allow relations between key and value (e. g.: a key must-have number value`).
Example of relation-based subscribers list:
const subscribers: {
  [P in keyof T]?: Set<Subscriber<T[P]>>
} = {}

Final solution
So the final solution can looks like:
type Subscriber<R> = (data: R) => void;
type BaseTopics = Record<string, unknown>

interface PubSubber<T extends BaseTopics> {
  subscribe: <R extends keyof T>(topic: R, subscriber: Subscriber<T[R]>) => () => void
  publish: <R extends keyof T>(topic: R, data: T[R]) => void
}

function pubSubber<T extends BaseTopics>(): PubSubber<T> {
  const subscribers: {
    [P in keyof T]?: Set<Subscriber<T[P]>>
  } = {}
  return {
    subscribe(topic, subscriber) {
      const current = subscribers[topic] || new Set();
      current.add(subscriber);
      subscribers[topic] = current;
      return () => current.delete(subscriber);
    },
    publish(topic, data) {
      subscribers[topic]?.forEach(f => f(data));
    },
  };
};


Simple javascript code to create an image caption

Not a comment on functionality, but here:

const wideImg = document.querySelector('.full-width-image-atf img'),
      captionText = wideImg.getAttribute('alt'),
      captionInnerHTML = '' + captionText + '',
      caption = document.createElement('div');

I don't think chaining declarations using , like you are is a good idea for a couple reasons:

It isn't immediately clear that all the variables involved are being declared as const. Yes, you can tell if you check the indentation, or notice the commas at the end, but it isn't as clear as explicit consts all the way down.
It makes refactoring more of a pain. Say in the future you want to break that up and maybe stick a log call in there or some other non-declaration. Now you need to manually replace the commas with semi-colons, and remember to add const to all the now separate declarations.

I'd suggest just writing it out fully from the start, and maybe space out the last one since it has a separate purpose:

const wideImg = document.querySelector('.full-width-image-atf img');
const captionText = wideImg.getAttribute('alt');
const captionInnerHTML = '' + captionText + '';

const caption = document.createElement('div');


Your basic hierarchy seems fairly solid.  There is just one thing - HTTP_ACCEPT_LANGUAGE is not so simple.  I wrote an answer on it here.  What follows is the relevant code from that:

// Parse the Accept-Language according to:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
preg_match_all(
   '/([a-z]{1,8})' .       // M1 - First part of language e.g en
   '(-[a-z]{1,8})*\s*' .   // M2 -other parts of language e.g -us
   // Optional quality factor M3 ;q=, M4 - Quality Factor
   '(;\s*q\s*=\s*((1(\.0{0,3}))|(0(\.[0-9]{0,3}))))?/i',
   $_SERVER['HTTP_ACCEPT_LANGUAGE'],
   $langParse);

$langs = $langParse[1]; // M1 - First part of language
$quals = $langParse[4]; // M4 - Quality Factor

$numLanguages = count($langs);
$langArr = array();

for ($num = 0; $num < $numLanguages; $num++)
{
   $newLang = strtoupper($langs[$num]);
   $newQual = isset($quals[$num]) ?
      (empty($quals[$num]) ? 1.0 : floatval($quals[$num])) : 0.0;

   // Choose whether to upgrade or set the quality factor for the
   // primary language.
   $langArr[$newLang] = (isset($langArr[$newLang])) ?
      max($langArr[$newLang], $newQual) : $newQual;
}

// sort list based on value
// langArr will now be an array like: array('EN' => 1, 'ES' => 0.5)
arsort($langArr, SORT_NUMERIC);

// The languages the client accepts in order of preference.
$acceptedLanguages = array_keys($langArr);

// Set the most preferred language that we have a translation for.
foreach ($acceptedLanguages as $preferredLanguage)
{
    if (in_array($preferredLanguage, $websiteLanguages))
    {
       $_SESSION['lang'] = $preferredLanguage;
       return $preferredLanguage;
    }
}

You would need to define website languages or just set the most preferred language.

Also as a very minor point I would change:

$lang = xxx;
return $lang;

To:

return xxx;


Thanks for sharing your code,

instead of using size, you should implement __len__, this way you can use len(my_stack).

def __len__(self):
    return len(self.item)

I think a method that prints an element from a collection is a bit unusual. What I would expect is a method called peek that returns the top element but doesn't remove it. By just printing it you're limiting its use to console only applications, and the only way to retrieve the element is to remove it!

You should consider adding an error message to go with your IndexError, and maybe reconsider the exception type, an IndexError sounds like you're accessing an index, but you're not maybe a custom StackEmpty exception would be more suitable.

I think self.item should be self.items (plural) as it will be representing zero or more items.

Bonus Stuff

you could implement the __iter__ method. This would allow the caller to do something like

for element in my_stack:
    do_stuff()

You code is also missing docstrings, you could optionally add those to document your code.

You could implement the __str__ method to provide a nice string representation so you can simply say

print my_stack

Hopefully you found this helpful, keep it up!


Recursive LinkedList. Which implementation is better and why?

Both of these implementations are bad.

The first is probably worse.

every node in the linked list, from self.head to the last node's head.next is unconditionally written to, which makes every cache-line/cache-page/virtual-memory-page the linked list touches "dirty" and need to be flushed/written.
self.head is passed to insertHelper(), which recursively calls itself N times, eventually (assuming N > 1) returning the value that it was given self.head, to be stored back into the self.head member.  This is a LONG critical section.  If any threading support was added, locks would need to be held way longer than necessary.

Recursion

Both use recursion, and Python does not do tail-call-optimization.  This means that if your linked-list is very long, you will get a stack overflow.  There are manual ways to make your function behave in a tail-call-optimized fashion, even if Python won't do it for you, but they are complex and it is by far simpler to just use a loop.

PEP-8

Both insertHelper and insertRHelper are helper functions, which should not be exposed a public methods.  They should begin with a leading underscore to indicate they are not part of the public interface.
The members next, head, and probably data should also not be public, so should be named with a leading underscore.
Classes are named using BumpyWords; functions, members and variables should all be snake_case.  These means insertHelper should be named _insert_helper, and so on.
if(...): is not Pythonic.  The parenthesis are unnecessary.

Tail

The best solution would be to maintain a ._tail member in the LinkedList:

class LinkedList:
    """Description of class here"""

    def __init__(self):
        self._head = None
        self._tail = None

    def insert(self, data: Node) -> None:
        """Description of the insert function here"""

        if self._tail:
            self._tail._next = Node(data)
            self._tail = self._tail._next
        else:
            self._head = self._tail = Node(data)

Now, insertions at the tail of the LinkedList are \$O(1)\$.

Naming

As mentioned by Matthieu M. in the comments:

  I would also consider renaming here: insert should be append, to make it clear where the insert occurs, and offer a path to proposing different insertions such as prepend, or insert with an index.