Plots of prior and posterior distributions for a model

There was a couple of errors in the code as originally posted. The code was OK as far as base R goes.

First thing I did was run styler and then lintr on your code; these two things help clean up the coding style in your scripts.

That does things like this:

colors = c("red","blue","green","orange","purple")

# changed to (spaces / idiomatic assignment):
colors <- c("red", "blue", "green", "orange", "purple")

Then I changed your 1:length(alphas) to seq_along(alphas). The latter is a bit safer since the former can fail with empty input.

Then I replaced your 5-separate prior/posterior plots with a single plot that contains 5 panels. This makes it easier to compare the appropriateness of the different priors. To do this, I removed your dev.new()s, added a call to par(mfrow = c(number_of_rows, number_of_columns)) and obviously, tidied this up afterwards (returning to a 1x1 grid)

par(mfrow = c(2, ceiling(length(alpha) / 2)))

for (i in seq_along(alpha)) {
    # removed dev.new()
   ... plotting code ...
   )
 }

par(mfrow = c(1, 1))

Then I cleaned up your experimental data and your prior-parameters / plotting parameters; they were all winding around each other. I also renamed your alpha / beta vectors - in R, these correspond to the shape and rate parameters that are passed into dgamma:

# ---- experimental data

num_observations <- 10

lambda <- .2

x <- rpois(num_observations, lambda)

# ---- prior parameters

# assumed 'beta' was a rate parameter
# - this, since there was confusion in the parameterisation of dgamma():
#   - early section used rate = 1 / beta[i];
#   - later section used rate = beta[i]; and
#   - definition of beta_star = beta[i] + n; implied beta was definitely a rate

shape <- c(.5, 5, 1, 2, 2)
rate <- c(.5, 1, 3, 2, 5)

# ---- plotting parameters

colors <- c("red", "blue", "green", "orange", "purple")

# ---- search parameters

grid <- seq(0, 2, .01)

Then I made a function to do your prior-comparison stuff (the first set of plots). Any parameters that were to be passed through to plot were passed in using the ... argument.

# ---- comparison of the prior distributions

plot_priors <- function(grid, shapes, rates, colors,
                        legend_text, lwd = 2, ...) {
  plot(grid, grid, type = "n", ...)

  for (i in seq_along(shape)) {
    prior <- dgamma(grid, shape = shape[i], rate = rate[i])
    lines(grid, prior, col = colors[i], lwd = lwd)
  }

  legend(
    "topleft",
    legend = legend_text, lwd = lwd, col = colors, bty = "n", ncol = 2
  )
}

This can be called like:

plot_priors(
  grid, shape, rate, colors,
  legend_text = paste0("Gamma(", c("0.5,0.5", "5,1", "1,3", "2,2", "2,5"), ")"),
  xlim = c(0, 1), ylim = c(0, 4), xlab = "", ylab = "Prior Density",
  main = "Prior Distributions", las = 1
)

It's useful to split your computations away from your plotting code - so I extracted the code you used to compute the posterior params:

compute_posterior_parameters <- function(observations,
                                         prior_shape,
                                         prior_rate) {
  list(
    shape = prior_shape + sum(observations),
    rate = prior_rate + length(observations)
  )
}

Then I pulled the plotting code for your prior/posterior comparisons into a function (similarly to the above)

plot_prior_post_comparison <- function(
                                       observations,
                                       grid, shapes, rates, colors,
                                       lwd = 2,
                                       ...) {
  # make a grid for plotting
  par(mfrow = c(2, ceiling(length(shapes) / 2)))

  for (i in seq_along(shapes)) {
    # details of the prior and post distributions
    posterior_params <- compute_posterior_parameters(
      observations,
      prior_shape = shapes[i], prior_rate = rates[i]
    )
    prior <- dgamma(
      grid,
      shape = shapes[i],
      rate = rates[i]
    )
    post <- dgamma(
      grid,
      shape = posterior_params$shape,
      rate = posterior_params$rate
    )

    # plotting code
    plot(grid, grid, type = "n", ...)
    lines(grid, post, lwd = lwd)
    lines(grid, prior, col = colors[i], lwd = lwd)
    legend("topright",
      c("Prior", "Posterior"),
      col = c(colors[i], "black"), lwd = lwd
    )
  }

  # revert the plotting grid back to 1x1
  par(mfrow = c(1, 1))
}

note that the par calls, which change the plotting grid are all nested inside the function, so any subsequent plots should be unaffected.

Then I called that function:

# ---- prior/posterior comparison

plot_prior_post_comparison(
  observations = x,
  grid = grid, shapes = shape, rates = rate, colors = colors,
  xlim = c(0, 1), ylim = c(0, 10), xlab = "", ylab = "Density",
  xaxs = "i", yaxs = "i",
  main = "Prior and Posterior Distribution"
)

Then I put all the functions at the start and all the calls at the end of a script:

The full code:

# ---- comparison of the prior distributions

plot_priors <- function(grid, shapes, rates, colors,
                        legend_text, lwd = 2, ...) {
  plot(grid, grid, type = "n", ...)

  for (i in seq_along(shape)) {
    prior <- dgamma(grid, shape = shape[i], rate = rate[i])
    lines(grid, prior, col = colors[i], lwd = lwd)
  }

  legend(
    "topleft",
    legend = legend_text, lwd = lwd, col = colors, bty = "n", ncol = 2
  )
}

# ---- prior:posterior analysis

compute_posterior_parameters <- function(observations,
                                         prior_shape,
                                         prior_rate) {
  list(
    shape = prior_shape + sum(observations),
    rate = prior_rate + length(observations)
  )
}

plot_prior_post_comparison <- function(
                                       observations,
                                       grid, shapes, rates, colors,
                                       lwd = 2,
                                       ...) {
  # make a grid for plotting
  par(mfrow = c(2, ceiling(length(shapes) / 2)))

  for (i in seq_along(shapes)) {
    # details of the prior and post distributions
    posterior_params <- compute_posterior_parameters(
      observations,
      prior_shape = shapes[i], prior_rate = rates[i]
    )
    prior <- dgamma(
      grid,
      shape = shapes[i],
      rate = rates[i]
    )
    post <- dgamma(
      grid,
      shape = posterior_params$shape,
      rate = posterior_params$rate
    )

    # plotting code
    plot(grid, grid, type = "n", ...)
    lines(grid, post, lwd = lwd)
    lines(grid, prior, col = colors[i], lwd = lwd)
    legend("topright",
      c("Prior", "Posterior"),
      col = c(colors[i], "black"), lwd = lwd
    )
  }

  # revert the plotting grid back to 1x1
  par(mfrow = c(1, 1))
}

# ----

# ---- experimental data

num_observations <- 10

lambda <- .2

x <- rpois(num_observations, lambda)

# ---- prior parameters

# assumed 'beta' was a rate parameter
# - this, since there was confusion in the parameterisation of dgamma():
#   - early section used rate = 1 / beta[i];
#   - later section used rate = beta[i]; and
#   - definition of beta_star = beta[i] + n; implied beta was definitely a rate

shape <- c(.5, 5, 1, 2, 2)
rate <- c(.5, 1, 3, 2, 5)

# ---- plotting parameters

colors <- c("red", "blue", "green", "orange", "purple")

# ---- search parameters

grid <- seq(0, 2, .01)

# ---- comparison of priors

plot_priors(
  grid, shape, rate, colors,
  legend_text = paste0("Gamma(", c("0.5,0.5", "5,1", "1,3", "2,2", "2,5"), ")"),
  xlim = c(0, 1), ylim = c(0, 4), xlab = "", ylab = "Prior Density",
  main = "Prior Distributions", las = 1
)

# ---- prior/posterior comparison

plot_prior_post_comparison(
  observations = x,
  grid = grid, shapes = shape, rates = rate, colors = colors,
  xlim = c(0, 1), ylim = c(0, 10), xlab = "", ylab = "Density",
  xaxs = "i", yaxs = "i",
  main = "Prior and Posterior Distribution"
)

I don't thnk its perfect - the plotting and calculation steps are still pretty tied together - but it should be more easy to add extra pairs of rate/shape values into your prior distributions, for example.

One place the code coould be further improved is by passing in a data.frame where each row contains the shape/rate/colour values and any annotations for a given prior. The functions contain too many arguments at the moment, and this would fix that (and guarantee that there is a shape for each rate).


Checking if a column belongs to a provided list

Can you see a better solution?

Yes use braces {} also for single line statements of an if condition.

Using .Any() instead of checking .Length > 0 is faster but only for an IEnumerable

I also would enclose reader["IDAgentClient"] == DBNull.Value in () as it is more readable or even better you can introduce a boolean isDbNullValue

DataRow[] drsIDAgentClient = reader.GetSchemaTable().Select("ColumnName = 'IDAgentClient'");
if (drsIDAgentClient.Length > 0)
{
    Boolean isDbNullValue = (reader["IDAgentClient"] == DBNull.Value);
    coupon.IdAgentClient = isDbNullValue  ? null : (int?)reader["IDAgentClient"];
}

After rereading your question it seems that you want to know if a column with a specific name exists in the SchemaTable.

So you can use instead of the code above simply this

String columnName = "IDAgentClient";
if (reader.GetSchemaTable().Columns.Contains(columnName))
{
    Boolean isDbNullValue = (reader[columnName] == DBNull.Value);
    coupon.IdAgentClient = isDbNullValue  ? null : (int?)reader[columnName];
}

I would like to expand @Malachi's answer with not using a tenary

Malachi's check

bool IsColumnEmpty(string columnName)
{
    return reader.GetSchemaTable().Columns.Contains(columnName))
        ? Reader[columnName] == DBNull.Value
        : true;
}

can be rewritten like

bool ColumnHasValue(string columnName)
{
    return reader.GetSchemaTable().Columns.Contains(columnName) &&
           Reader[columnName] != DBNull.Value;
}

and if you really need to use an extension method you can do this like

public static class HelperExtension
{
    public static bool ColumnHasValue(this IDataReader reader, string columnName)
    {
        return reader.GetSchemaTable().Columns.Contains(columnName) &&
               Reader[columnName] != DBNull.Value;
    }
}

and call it

coupon.IdAgentClient = reader.ColumnHasValue(columnName) ? (int?)reader[columnName] : null;


This:

//set the object information
$user_id         =get_current_user_id();
$title           =$this->input->post('ui_title_input');
$content_url     =$this->input->post('ui_url_input');
$content         =$this->input->post('ui_textarea');
$right           =RIGHT_NOTE_PUBLIC;
$status          =STATUS_NOTE_ACTIVE;

$aNewUserNote->set_user_id($user_id);
$aNewUserNote->set_title($title);
$aNewUserNote->set_content_url($content_url);
$aNewUserNote->set_content($content);
$aNewUserNote->set_right($right);
$aNewUserNote->set_status($status);

Should be rewritten as this

// create and populate note object
$note = new obj_note();
$note->set_user_id(get_current_user_id());
$note->set_title($this->input->post('ui_title_input'));
$note->set_content_url($this->input->post('ui_url_input'));
$note->set_content($this->input->post('ui_textarea'));
$note->set_right(RIGHT_NOTE_PUBLIC);
$note->set_status(STATUS_NOTE_ACTIVE);

Other than that, my comment on your question will explain the rest.


else:
    cnt[points.index(p[0])] = segments_num

Looking up the index of every point here is slow. A quick fix would be to store counts in a dict and traverse it in the correct order afterwards; see how that performs.

cnt = {}
segments_num = 0

else:
    cnt[p[0]] = segments_num

return [cnt[x] for x in points]

It also looks like your solution isn’t quite correct, since the sort could put lefts, rights, and points at the same location in different orders. Since the correct order of left, point, right also happens to be in alphabetical order, you can do another minimal fix and replace this:

listpoints.sort(key=lambda x: x[0], reverse=False)

with this:

listpoints.sort()

That’s a bit of a hack, but for this sort of task, it seems standard to keep the code short (fast to write in a competition?) rather than particularly expressive.


Indeed, addition is faster than modulo.  This implementation runs about 33% faster than the original when counting up to 100.  However, I expect that it wouldn't scale as well to larger limits due to its O(n) memory usage.

def fizz_bang(limit=100):
    limit += 1
    strings = [''] * limit

    fbb = ((3, 'Fizz'), (7, 'Bang'), (11, 'Buzz'))
    for stride, noise in fbb:
        for n in range(0, limit, stride):
            strings[n] += noise
    for n in range(1, limit):
        print strings[n] or n

Also, according to PEP 8 conventions, FizzBang should be named fizz_bang instead.


Less CSS Mixin for positioning with options for corresponding top, left, right, bottom values

Is this a useful Mixin? Depends on if you need it a lot.

Or is it a bad practice to create Mixins like this? Nothing is bad practice if it helps you float your boat.

Is it too complicated or too hard to understand? Not really, but seems like you'll often have to lookup the generated CSS to fix positioning problems. F.e. I'm not a big fan of 10px, null, null, 10%, I know it's NESW, but still... Wouldn't it be better to have .position(fixed, top 10px, left 10%) if that is possible?

Can this be optimized or shortened? Probably yes, but why do premature optimization if the use-case is unknown?


Why not use a map of types (CImpl concrete instances) that are instantiated upon Factory initialization? The values of the map would be instances of BImpl, DImpl, etc, and the respective keys would be the types. The function getBuilderFor() would just do a map lookup and on the value returned from the map, call BuilderImpl() and return the result.

This approach would allow to avoid the if/else block. Additionally, it would make it easier and more elegant to add more types in the future.


Recommendations

The less tasks that a subroutine performs the easier it is debug and modify.  If I were to put this code into production (distribute it for general use) I would extract these functions from the main code:

ApplicationState(PauseEvents): - handles the application state
getWorksheetNames()  - returns Arquivo().  This will allow you to tests whether the worksheets exists in the main workbook and whether the files exists without having to run the main code.  This alone will reduce your main code from 49 lines to 31.  I personally like to keep my subroutines no bigger than 25 - 30 lines whenever possible.
getXMLWorkBook(FilePath) As Workbook - use Len(Dir(FilePath)) > 0 to test if the file exists, if so, open and return the workbook.

Next I would add error handlers to test if the workbook exists or if there are any missing worksheets.

Excel Do's and Don't

There are very few times where you'll need to Select or Activate an Object.

Watch: Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)

There is no reason to use Application.DisplayAlerts = False in this code.  Workbook.Close SaveChanges:=False does not display any alerts.

Range references should be fully qualified.  If you are working with multiple workbooks, you should also qualify the worksheets to their parent workbook.  It might take a little getting used to but fully qualifying your references will save you a ton of headaches.  What usually happens is that you get the code working great and but later when you come back and to modify it you get unexpected results.  This can be especially tough to resolve in a large project.

Refactored Code

Here is how I would refactor the code for in-house use.

Sub AtualizarRelatorioGeral()
    Const BasePath As String = "C:\macrosm\prerelatoriolucimara\FileName.xls"
    Dim wsName As Variant, wbName As String
    ApplicationState True

    For Each wsName In Array("zpp03ontem", "vl10a", "mb51consumomensal", "mb51repassegerado", "mb52peixerev", "mb52peixepro", "mb52exp", "mb52repassesaldo", "zsd17", "zsd25fat", "zsd25dev", "mc.9estoquecd", "mc.9consumo", "mc.9centro", "mc.9cdhipet", "mc.9valor", "zpp25", "mc.9produto")
        wbName = Replace(BasePath, "FileName", wsName)
        With Workbooks.OpenXML(wbName)
            ThisWorkbook.Worksheets(wsName).Cells.Clear
            .Worksheets(wsName).Cells.Copy ThisWorkbook.Worksheets(wsName).Range("A1")
            .Close SaveChanges:=False
        Next
    Next

    ThisWorkbook.Worksheets("Sheet1").Cells(4, 16).Value = Date

    ApplicationState False
End Sub

Sub ApplicationState(PauseEvents As Boolean)
    With Application
        .Calculation = IIf(PauseEvents, xlCalculationManual, xlCalculationAutomatic)
        .ScreenUpdating = Not PauseEvents
        .EnableEvents = Not PauseEvents
    End With
End Sub


This is pretty good. Minor points:

You can return just root in createList:

ListElement * createList(int size) {
    ListElement *root;
    ListElement *current;
    root = malloc(sizeof(ListElement));

    if (root != NULL) {
        root->value = 0;
        current = root;
        int i;

        for (i = 1; i < size; i++) {
            current->next = malloc(sizeof(ListElement));

            if (current->next != NULL) {
                current->next->value = i;
                current = current->next;
            } else {
                freeList(root);
                return NULL;
            }
        }
    }

    return root;
}

And your freeList is O(n^2) complex, because you are removing from the end. Removing from the beginning would make it O(n).


A partially overlapping sequence of jQuery animations

@Paritosh has suggested some code to change what you have done, but doesn't explain it at all.

The suggestion is that you use a loop

(function loop() {
    $('.elements').each(function() {
        var $self = $(this);
        $self.parent().queue(function (n) {
        $self.fadeIn(2000).delay(200).fadeOut(2000, n);
        });
    }).parent().promise().done(loop);
}());

This is the code taken from Paritosh's JSFiddle

All that is being done here is that you are sending a node as a parameter to the function and then it is going through each child node of that node, fading it in and then fading it out.

This is much more efficient and can be used on any node, in other words you can reuse this code whereas the original code couldn't be reused unless you changed all the ID's.


Merge duplicated cells in bulk per each column VBA

'Declare All Variables:

Dim myCell As Range
Dim myRow As Integer
Dim myRange As Range
Dim myCol As Integer
Dim i As Integer
Dim k As Integer

Dim myFirstRow As Long
Dim myFirstColumn As Long

Dim rngCopy As Range, rngPaste As Range

Don't do this. This procedure is somewhere between 2 and 3 screens high on my laptop: when I'm at the bottom of the procedure, I don't know what I'm looking at, so I scroll back up to this wall of declarations, parse the chunk of code, locate the variable I'm looking for, then scroll back down to where I was, ...and that gets very annoying, very fast.

People defending this "declare everything at the top of the procedure" habit usually defend it pretty hard, and they're wrong. "I can see everything that's used in the procedure at once" sounds great on paper. Truth is, it only makes you scroll back and forth all the time for no reason, and makes it much harder than it should be, to know whether or not a variable is used, let alone where it's used.

If you declare variables where you first assign them, as you need to introduce them, then you simply can't miss the fact that myCell, myRange, rngPaste are never assigned or referenced anywhere... and that iRow and n aren't declared at all. This is extremely bug-prone, you don't want to allow VBA code to run with undeclared variables. Fortunately you can completely prevent this, by simply specifying Option Explicit at the very top of every module you ever write any VBA code in.

Proper indentation also helps, massively. It started well:

For i = 1 To myRow

    If iRow <> n Then

...and then suddenly went way out there:

                Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3)).HorizontalAlignment = xlCenter

...to seemingly random:

            Else
            n = Cells(myFirstRow + i + 1, myFirstColumn)

                For k = 1 To myCol - 3 'need to merge data per column but don't need to merge data in the last 3 columns

Use an indenter if you're unsure how to keep indentation consistent.

Row numbers should always be As Long. An Integer is a 16-bit signed integer type, so its maximum possible value is 32,767. This means as soon as your data involves row 32,768 and beyond, your code breaks with an "Overflow" run-time error. In fact, there's little to no reason at all to ever declare anything As Integer in 2019: processors are optimized to deal with 32-bit integer types, and that's a Long in VBA.

I like this:

With ActiveSheet

I makes ActiveSheet references explicit, and that's very good.

However you're implicitly referring to whatever the ActiveSheet is everywhere else outside this With block.

myRow = Range(Cells(3, 1), Cells(3, 1).End(xlDown)).Count + 2 'first two rows are headers
myCol = Range(Cells(2, 1), Cells(2, 1).End(xlToRight)).Count

Unqualified like this, Range and Cells are implicitly referring to the ActiveSheet: the With ActiveSheet block is therefore redundant, and makes accesses to that active sheet inconsistent: some are explicit, some are implicit - and that's very bug-prone.

A note about this:

myRow = Range(Cells(3, 1), Cells(3, 1).End(xlDown)).Count + 2 'first two rows are headers

Looks like you're trying to get the last used row; this is not a reliable way to do it. Consider flipping the logic around and going up from the last row on the sheet to get the .Row of that specific cell, rather than the Count of cells in a range:

myRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

Note how the fist two rows being headers, doesn't matter any more.

I'd strongly advise against using my as a prefix for anything, regardless of how often you see it in documentation. Same goes for rng and o and whatever other prefixing scheme you might read anywhere. Use meaningful names instead. "myRow" doesn't say what's important about it: it's the last row with data. lastRow would already be a much better name for it.

rngCopy is assigned, its borders are formatted, ...but it's not being copied anywhere. The name strongly suggests it's a source, especially since it's declared right next to the unused rngPaste, which strongly suggests that would be a destination for an operation involving the clipboard. Pretty misleading, since none of that is happening anywhere in the procedure.

I already mentioned n isn't declared. Its usage is a problem.

Set n = Cells(myFirstRow + 1, myFirstColumn)

It's Set-assigned to a Range. Thus, its runtime type at that point is Variant/Range.

If iRow <> n Then

Now it's being compared to iRow, which is another undeclared Variant/Range variable, and the two objects are only comparable through implicit let-coercion involving hidden default member calls - making it all explicit would look like this:

If iRow.Value <> n.Value Then

And while that's now explicit, it's wrong. It's wrong, because they shouldn't be Range objects. They shouldn't be Range objects, because they're later being Let-assigned to plain values:

        iRow = Cells(myFirstRow + i, myFirstColumn)
        n = Cells(myFirstRow + i + 1, myFirstColumn)

Beyond that point, the data type of iRow and n is up in the air. If you're lucky, you're looking at two Variant/Double values. Otherwise, you're looking at one or more Variant/Error values (that would be the case if the worksheet contains error values), and everything blows up with a type mismatch error.

Not declaring variables is one thing, reusing variables is another, but reusing undeclared variables and assigning them a new runtime type, makes everything very hard to follow. Declare them with an explicit data type, and let them be values, instead of objects that behave like values thanks to implicit hidden code.

As for performance, the reason it's slow is because it's doing the single slowest thing any code can do: interact with worksheet cells directly, in a loop.

You can't help it, interacting with worksheet cells is precisely what this macro needs to do. All you can do is tell Excel to stop trying to keep up as you modify the worksheet.

Every time a cell is modified, Excel evaluates whether a recalc is needed, and will perform it if it has to. Switch calculation to manual before you start manipulating the worksheet, and toggle it back to automatic when you're done: Excel will only recalculate once. That's Application.Calculation (set to xlCalculationManual, then back to xlCalculationAutomatic when you're ready).

Every time a cell is modified, Excel fires worksheet events (e.g. Worksheet.Change), and if there's a handler procedure for that event, then that code will run before the next instruction does. Turn off application events before you start manipulating the worksheet, and toggle it back on when you're done: no worksheet events will be fired; that's Application.EnableEvents (set to False, then back to True when you're ready).

Every time a cell is modified, Excel tries to repaint itself. While that's normally pretty fast, when you're modifying cells in a loop you don't want Excel to even try to keep up - you want to make your changes, and have Excel repaint itself when you're done. Do that by toggling Application.ScreenUpdating (set to False, then back to True when you're ready).

Whenever you toggle this global Application state, make sure you handle runtime errors, and have your error-handling subroutine ensure that the global state gets properly reset whether the procedure succeeds or fails, whatever the reason for failing might be.


Go API server - request handlers becoming excessively long

Some random notes:

Your use of notFoundHandler().ServeHTTP(w, r) is weird. Why do you have a function returning this if it doesn't take any params? You'd probably be better off just having a function writeNotFound(w, r). This mirrors the approach of net.http, which already provides functions like this.
From a RESTful approach, you shouldn't be returning the StatusCode in the JSON. That should be the HTTP status code.
This is minor, but what is an Enrol? Enrollment?
if r.Method != http.MethodGet, you should be returning a 405 Method Not Allowed instead of a 404 Not Found
If json.Marshal fails, you should return a 500 Internal Server Error instead of an unauthorized
Be careful with variables shadowing a package (store *store.Store). That can have unexpected consequences. Ideally you package name and struct should form a complete thought like http.Server (instead of server.Server). Unfortunately, in some scenarios this is difficult.
Your store functions don't follow Go conventions. If you are returning (X, error) then you should only check err != nil. Either err != nil (and you ignore the first thing) or err = nil and the first thing is valid. Don't do assessments == nil || err != nil. This should just be err != nil. You may need to change how the store functions behave to conform to this pattern.

The overarching point

Repetitive error handling is an unfortunate consequence of some of the design decisions of Go (namely, a lack of parametric polymorphism). In this case however, even if you had generics (to pull out the repetitive error handling logic), you'd still need some way to bubble the return up to the http.HandlerFunc. And that would require something like:

if !tryQuery(func() (User, error) { return store.GetUserByEmail(email) }) {
    return
}

Where tryQuery returns false if store.GetUserByEmail(email) returned an error. This is certainly shorter, but it's dubious that this is an improvement. You also couldn't write such a tryQuery currently in go because the first return type User would need to be generic. Sure, you could cast through interface{}, but that's a world of ugliness that you don't want to deal with. It would require you to do lots of casts, which incur a runtime cost and are (programmer) error prone.

So what to do? Well, any refactoring you embark on will be a tradeoff. The go ethos often prefers more verbose, repetitive code because it's easier to follow. But this comes at a cost. Eventually code becomes hard to reason about and harder to test because units have many responsibilities.

That said, I think there are some patterns you could use that would really help clear this code up. In the end, the code should be easier to read and easier to test.

First, checks like "is the user authorized" is often better suited for middleware. This pattern will allow you write the authorization check once and then wrap every handler in this middleware that needs it:

func needsAuthorization(handler http.HandlerFunc) http.HandlerFunc {
    return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
        if !request.IsAuthorized(r) {
            log.Println("Unauthorized")
            writeUnauthorized(w, r)
        } else {
            handler(w, r)
        }
    })
}

Then you can use it like so:

func stateHandler(store *store.Store) http.HandlerFunc {
    return needsAuthorization(func(w http.ResponseWriter, r *http.Request) {
        // This is only called if user is authorized
        // Check email, get assessments, etc.
    })
}

This is appropriate for checks like authorization (and maybe checking the request method), but shouldn't be used for everything.

Another option here (although sometimes frowned upon by the purists) is to use an existing HTTP framework that handles routing (including method) and maybe already has utilities for injecting middleware. This is somewhat in conflict with Go's obvious philosophy as there is some magic introduced. As with refactoring , there are tradeoffs here. Frameworks abstract away some common patterns to enable more succinct business logic. For example, with a buffalo router you can do:

a.GET("/state", stateHandler(store))

The meat of your problem still exists. All of the interaction with your models and constructing the response still is a lot of repetitive error handling. The ideal approach here would be an Applicative pattern which is capable of constructing data up until the point of an error. In Haskell, this would look something like:

user <- getUserByEmail =<< getParam "email"
return $ StateResponse <$> user <*> getEnrollments user <*> getAssessments user
                       <*> getSubmissions user

The beauty here is that all of these steps (user, getEnrollments user, etc.) can fail. And when they do, the error is returned instead. But until one occurs, we just continue to construct the data. Note that this looks almost like how you build the StateResponse struct in Go, except it also does error handling.

In Go, you'd have to duplicate some (trivial) code to achieve something like this. And I'm not sure it would be worth it. You'd end up with something like:

state := StateResponseBuilder{}

state.SetEmail(func() (string, bool) { return  r.Url.Query()["email"] })
state.SetUser(func() (store.User, error) { return store.GetUserByEmail(state.Email) })
state.SetEnrollments(func() ([]store.Enrollment, error) { return store.GetEnrollmentsByUser(state.User.UID) })
state.SetAssessments(func() ([]store.Assessment, error) { return store.GetAssessmentForUser(state.User.UID) })
state.SetSubmissions(func() ([]store.Submission, error) { return store.GetSubmissionsForUser(state.User.UID) })

respBytes, err := state.Build()
if err != nil {
    // return error
} else {
    w.Write(respBytes)
}

The idea here is that StateResponseBuilder somewhat follows the Pike technique. Each SetX looks like this:

type StateResponseBuilder struct {
    Err error
    X X
}

func (s *StateResponseBuilder) SetX(f func() (X, error)) {
    if s.Err != nil {
        return
    }

    if x, err := f(); err != nil {
        self.Err = err
    } else {
        self.X = x
    }
}

Your error short circuiting is handled by checking if s.Err != nil before running f(). s.Err is the first error we encountered or nil if everything so far as succeeded.

You'll note this requires a lot of code repetition in the SetX methods. Furthermore, the resulting code is probably less obvious even though it lacks all the error checking.

That said, such a pattern can be useful in certain contexts.

A better approach

A more suitable pattern, in my opinion, would be to separate concerns and use some indirection to make errors responsible for reporting themselves (instead of making your handler responsible for knowing how to report them). The big idea here is that currently your handler has many jobs. This is what is making it slightly unwieldy. You can separate its main jobs into two categories:

HTTP related (specifically, translating errors/data to the appropriate constructs in HTTP)
Interacting with store

If you separated these two, you could de-duplicate some of your repetitive HTTP error handling code. Further, this would abstract your controller logic away from HTTP so if you wanted to provide another kind of API (maybe some sort of custom protocol over TCP), you could do this fairly easily. Doing something like this would make your handler look like:

func stateHandler(store *store.Store) http.HandlerFunc {
    return needsAuthorization(onlyGet((http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        var email string

        emails := r.URL.Query()["email"]
        if len(emails) == 1 {
            email = emails[0]
        }

        response, err := buildStateResponse(store, email)
        if err != nil {
            err.WriteHTTP(w)
        } else {
            w.Write(response)
        }
    })))
}

We've done several things here. First, all the HTTP error handling has been reduced to one location. This should make logging much easier. All HTTP-related things are located just in the handler. Note that we did push some of this into the errors themselves. This kind of indirection allows us to not have to handle every case in the HTTP handler. The advantage here is if another error condition arises when you're working on store, you don't have to go through all of your HTTP handlers and handle outputting the error each place a store function is used. Doing this would require you to create a custom error interface that has WriteHTTP, but you could just as easily make this a function that takes an error as its first parameter. The simplicity of the pure controller logic speaks for itself:

// You may want to return the `StateResponse` here and handle serialization in the HTTP handler
func buildStateRespones(store *store.Store, email string) ([]byte, error) {
    user, err := store.GetUserByEmail(email)
    if err != nil {
        return nil, err
    }

    enrolled, err := store.GetUserEnrollments(user.UID)
    if err != nil {
        return nil, err
    }

    assessments, err := store.GetUserAssessments(user.UID)
    if err != nil {
        return nil, err
    }

    submissions, err := store.GetUserSubmissions(user.UID)
    if err != nil {
        return nil, err
    }

    return json.Marshal(StateResponse{
        User: *user,
        Enrolled: enrollments,
        Assessment: assessments,
        Submissions: submissions,
    })
}

You still need the error checks, but now you aren't trying to do so much inside them. This code should be much easier to follow. What's more, if the new error check proposal lands, this code will immediately be convertible to this much more readable form:

func buildStateRespones(store *store.Store, email string) (*StateResponse, error) {
    user := check store.GetUserByEmail(email)
    enrolled := check store.GetUserEnrollments(user.UID)
    assessments := check store.GetUserAssessments(user.UID)
    submissions := check store.GetUserSubmissions(user.UID)

    return &StateResponse{
        User: *user,
        Enrolled: enrollments,
        Assessment: assessments,
        Submissions: submissions,
    }, nil
}

Here we've separated business logic from protocol specific "presentation" logic. The result is that each separated part is now easier to reason about (and easier to unit test!).


Is this a good way to store error messages to display back to the user?

I would recommend you use a factory instead.

cosmo.error = function(id) {
    ...
};

then just use cosmo.error("ssn-empty")

Having your logic in a factory rather then an object gives you more control and makes your code significantly more DRY.

Implementation of error:

var error = (function() {
    var base = {
        empty: "Please enter ",
        numeric: "Please enter a valid number for ",
        date: "Please enter a valid date for ",
        ssn: "SSN",
        lastName: "Last Name",
        dob: "Date of Birth",
        studentId: "Student ID"
    };

    var methods = {
        "ssn": function(id) {
            if (id === "invalid") {
                return base.numeric + base.ssn;
            }
        },
        "dob": function(id) {
            if (id === "invalid") {
                return base.date + base.dob;
            }
        },
        "studentId": function(id) {
            if (id === "invalid") {
                return base.numeric + base.studentId;
            }
        },
    };

    return function(id) {
        var parts = id.split("-");
        if (parts[1] === "empty") {
            return base.empty + base[parts[0]];
        } else {
            return methods[parts[0]](parts[1]);
        }
    }
}());

console.log(error("ssn-invalid"));

live example


You want to test for element.startswith('LOCATION: ').  You are doing 'LOCATION' in element, which is not only slower since it has to check at every position of every element, it might also lead to false matches.

Also, element and data are poor names.  I suggest header and headers, respectively.

My suggestion:

LOC = 'LOCATION: '
xmllinks = [header[len(LOC):] for header in headers if header.startswith(LOC)]
if xmllinks:
    xmllink = xmllinks[0]


Retrieving current time and computing a hash value

Just a couple of points which are more from a stylistic point-of-view rather than strict language requirements or algorithmic correctness:

Classes should be named upper-case: Car, House, TwoTimesPlusOne, Addition
Interfaces should also be named upper-case: InfixOperator
Variable names should use camel-case: leafIndex, unsignedValue
i, j and k are used as iterator variables (the more you reference a variable, the shorter it should be named)
Prefer lists over arrays and make use of the enhanced for loop

for(InfixOperator i : operators) {
    //...
}

Adhering to common language standards will make your code more easily understandable for other programmers.


Haskell basic typeclass primer (quadratic equations)

It's hard to tell if the compiler would be able to eliminate duplicate calls to delta. It may do that, by inlining the x1 and x2 functions and then eliminating common subexpressions. Personally though, I prefer to do this myself. The following modification is guaranteed to call delta only once:
solve (Quadratic a b c) = solutions
    where
        both = [x1, x2]
        one = [x1]
        zero = []
        solutions = if _delta < 0 then zero else if _delta == 0 then one else both
        _delta = (delta a b c)
        x1 = ( - b - sqrt _delta) / ( 4 * a * c )
        x2 = ( - b + sqrt _delta) / ( 4 * a * c )


I'm sorry to hear you got rejected - that's never any fun. I'll go through line by line, with some general comments at the end.

Some of my notes are labeled as style suggestions; these usually mean generally accepted Java principles (naming conventions, etc.), so I'll try to point out where I'm trying to argue for a given style I personally recommend instead of giving a general rule.

import java.util.Scanner;

public class CreateAccount {

Style: classes should usually be nouns - e.g. Account or maybe AccountCreator, because you use them as Objects - so it makes more sense to have "an Account" than "a CreateAccount"

    int accountid;
    String accountantname;
    String IFSCcode;

Style: Java almost always uses Camel Case naming, so accountid should be accountID and accountantname accountantName, etc.

   public CreateAccount(int accountid,String accountantname,String IFSCcode){

Style: method names should start with a lower case letter EDIT: this is a constructor (my bad) and is therefore correctly named. Non-constructor methods should start with a lowercase letter.

    this.accountid = accountid;
    this.accountantname = accountantname;
    this.IFSCcode = IFSCcode;
   }

    /*//adding deposit money with the balance

What is this comment supposed to tell me? The function is called depositMoney, so I expect that it will deposit money - you don't need to tell me that. Instead, it might be helpful to explain that the deposit amount comes from the user's input, or what the return value means

    public double despositMoney() throws MiniumAmountDeposit{

        double Currentbalance = 0.00;
        Scanner scn = new Scanner(System.in);
        System.out.println("please enter the deposit amount");
        double Depositamount = scn.nextDouble();
        Currentbalance += Depositamount ;
        System.out.println("your currentbalance="+Currentbalance);

        return Currentbalance;
    }*/

This method is a little busy - it would be nice if the functionality to get input from the user was somewhere else (in a separate function), especially because you need to use it for multiple commands.

Also, it really seems like Currentbalance (currentBalance, if we use Camel Case ;p) should be an object variable.

  In the question paper they clearly mentioned that no data persistence is required.

BUT, I think what they meant is, no data persistence is necessary between program executions (you don't need to save account data to a file when the program shuts off, and read it back in when it starts up again). It would make a lot more sense to keep track of a user's balance while the program is running, and check, for example, that the user doesn't withdraw more money than they have in their account.

    //withdrawl money  and set daily withdrawl limit
    public void WithdrawMoney() throws InsufficientBalException, MiniumAmountDeposit{

        double Currentbalance = 0.00;
        Scanner deposit = new Scanner(System.in);
        System.out.println("please enter the deposit amount");
        double Depositamount = deposit.nextDouble();
        Currentbalance += Depositamount ;
        System.out.println("your currentbalance="+Currentbalance);

        /*double Currentbalanace = despositMoney();*/

See the above note - we probably don't want to force the user to deposit money before every withdrawal.

        //setDaily Withdrawl limit
           final double setDailyLimit = 2500.00;

This is a configuration constant - it should go at the top of the class, before methods. If all users should have the same withdrawal limit, it should be declared static, too.

            Scanner withDraw = new Scanner(System.in);
            System.out.println("please enter the withdraw amount");
            double WithdrawMoney =withDraw.nextDouble();

        if(Currentbalance < WithdrawMoney)
            System.out.println("you have less amount : your current balance is="+Currentbalance);

        else if (WithdrawMoney > setDailyLimit)
            System.out.println("you have entered amount exceed than daily limit : your dailyLimit="+setDailyLimit);

        else
            Currentbalance -= WithdrawMoney;
            System.out.println("your current balance is="+Currentbalance);

    }

These checks are good, nice job.

    /*public void setWithdrawlLimit()throws exceedLimit{
        Scanner scn = new Scanner(System.in);
        System.out.println("please enter the withdraw amount");
           double  enterAmount = scn.nextDouble();
        double DailysetLimit = 2500;

        if(enterAmount>DailysetLimit)
            System.out.println("you have exceed daily limit : your dailyLimit"+DailysetLimit);

    }*/

I don't understand what this function is for.

    public String toString(){

        return "accountid="+this.accountid + "accountantname="+this.accountantname + "IFSCcode="+this.IFSCcode;
    }

    public static void main(String[] args){
        CreateAccount account = new CreateAccount(1234455533,"samy","ICIC09");
        System.out.println("you have created account : " +account);
    /*
        try {
            account.despositMoney();
        } catch (MiniumAmountDeposit e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/

        try {
            account.WithdrawMoney();
        } catch (InsufficientBalException | MiniumAmountDeposit e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        /*try {
            account.setWithdrawlLimit();
        } catch (exceedLimit e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

In general, you shouldn't leave auto-generated TODOs in submitted code. For an interview, I would be fine with leaving TODOs explaining functionality I wish I could implement but didn't have time for.

*/
    }
}

And that's the end, so, overall: It looks like you have a solid start on the problem. The biggest issues I see (in order of importance (my opinion) for code turned in as part of an application):

The code looks a little rushed. Just like in a face-to-face interview, appearances matter for code that will be read and reviewed. Big chunks of commented code with no explanation, as well as misspelling / inconsistent naming schemes, won't make a good impression.
It seems like you're a little unsure of the problem specification. It can help a lot to think carefully about the input / output to each function, and what data will need to be stored in object variables, as you're writing your code - these things can change as you go along and understand the problem more. It's very helpful to document (write in comments!) the assumptions you're making about how the program should run.
There are some spots where you deviate a lot from established Java rules. No company has the exact same code style (here are Google's for Java), but there are some things (camel case, for example) that are very central to a given language. Not using camel case correctly when writing Java is a signal that you don't know Java very well - depending on the position you're applying for, this may or may not be a problem.

My biggest suggestions for improvement are: always submit the cleanest code possible, try to follow broad, important, rules for how the language should look, so it looks clean to the reviewer, and work on writing short, helpful comments around tricky or interesting spots in the code.


Count words in a list of titles, with some cleanup

Very good first post! There are a few small things to call out. First, refrain from using pandas and numpy unless it's absolutely necessary. Both are fantastic tools which excel in certain areas, but generally speaking many stock Python scripts can be just as performant, much more portable, and a lot more clear on their own. For example, stock Python is fantastically suited for counting the frequency of hashable items (in fact, you used it with Counter). But if I wanted to do QR decomposition, I would absolutely reach for numpy as it already has an implementation of this and that implementation will likely be much faster than anything I can write. Always be sure to use the right tool for the job. Generally speaking, the more dependencies a piece of code has, the harder it is to compose with other things (harder could be quantifying programmer effort here--as in, the effort to install dependencies/debug version issues/etc.). So for this reason, I'm going to remove numpy and pandas from my answer.

#imports Counter, as we will need it later:
from collections import Counter

This is a useless comment. Of course that's what the following line does. And of course you're importing something because you need it. Don't just comment for the sake of commenting. Comment to explain the "why" not the "what."

You can do your csv reading with stock python. You should be using with contexts here to handle properly closing files (especially if exceptions are raised). csv.DictReader will be useful here as it is an iterator that yields dicts for each row. This allows us to use a generator comprehension to build the list of titles. If you are unfamiliar with generators, you should [read up on them}(https://stackoverflow.com/q/1756096/568785). The benefit they give you is that they don't build up a big list in memory. They only produce values upon request. In your code you have a lot of list and string manipulation (see the list comprehension of resultwords, the join/split dance of total_words_string and querywords--which is unnecessary--,and huge_title_list). All of these points can be bottlenecks, because they require building up in memory the entire state to that point. Instead, using a generator allows you to lazily defer the work until you need it (in this case, when you use Counter).

A good analogy for this is an assembly line. Imagine you had a factory building computers with 3 stops on the assembly line (we'll call them A, B, and C). At each stop, a worker adds one component to the computer (let's say motherboard, CPU, RAM). If we were to write this out using lists it would look like this:

computers_after_A = [add_motherboard(computer) for computer in bare_computers]
computers_after_B = [add_CPU(computer) for computer in computer_after_A]
computers_after_C = [add_RAM(computer) for computer in computer_after_B]

This looks innocent enough, but if you were to run your factory like this you'd have some real problems. Let's say the factory processes 1000 computers per day. The above code would be equivalent to the following:

The worker at A adds motherboards to each incoming computer and then adds the finished computers to a big stack.
Once worker A is done with all 1000 computers, the stack is pushed to worker B who takes one from each stack, adds the CPU and then makes a new stack of finished computers.
Once worker B is done with all 1000 computers, the stack of 1000 computers is pushed to worker C, who adds the RAM and then adds the computers to the finally done stack.

The problem with the above is that it is inefficient (worker B has no work until worker A completes all 1000 computers and worker C has no work until both workers A and B finish all 1000 computers) and requires you to have the room to store all 1000 computers at each location A, B, and C.

A much better approach is how factories really work. A constantly moving conveyor belt which moves the computers through one by one. At each location, the worker adds their respective component and then send each computer along individually to the next station. This would be equivalent to the following:

computers_after_A = (add_motherboard(computer) for computer in bare_computers)
computers_after_B = (add_CPU(computer) for computer in computer_after_A)
computers_after_C = (add_RAM(computer) for computer in computer_after_B)

With this approach we've replaced lists with generators. Now, computers are immediately available (instead of only available after everything finishes) and we don't need the space to build up 3 piles of 1000 computers.

Hopefully, this motivates why we should use generators. I'll be using them below.

There's no reason to use pandas to sort the counts from Counter. Counter has a most_common() method that will do this for you.

You had the right idea with using translate to replace unwanted characters. But you don't need to build the dictionary every time. Instead using string.maketrans and saving this "translation dictionary" will avoid doing lots of extra work.

remove_words_list should probably be called stop_list as this is the common parlance for words you want to exclude. Also, you should make this a frozenset so that word in stop_list is O(1) instead of an O(n) scan (what you currently do, which is really inefficient).

Typically, we include code that we want to run in a main() function and run it only if __name__ == '__main__'. This allows other code to include this file (and potentially use an utility functions it defines) without having the main() run.

With all that in mind, I'd refactor your code to something like this:

import csv
import string

STOP_WORDS = frozenset(('at', 'of', 'a', 'and', 'in')) # ...
EXCLUDE_CHARS = string.maketrans('', '', '.:,-%()[]?\'')

def main():
    with open('Article_titles.csv') as f: # consider accepting the filename as an argument (sys.argv)
        titles = (row['title'] for row in csv.DictReader(f, delimter='|'))
        words = (word.lower().translate(EXCLDUE_CHARS)
                 for title in titles for word in title.split())
        interesting_words = (word for word in words if word not in STOP_WORDS)
        frequencies = Counter(interesting_words)

        print(frequencies.most_common())

if __name__ == '__main__':
    main()

Now remember how I mentioned above choosing the right tool for the job? It turns out that what you're trying to do (word extraction) is pretty tricky. Natural language has all sorts of irregularities, odd formatting, and inconsistencies. Luckily, there's a fantastic Python library which has a fairly good (complicated) implementation for handling all this for you: nltk. This is a very appropriate use of a library, because this task is hard and nltk has put lots of work into building a robust implementation. The home page has an example of what you need:

>>> from nltk import word_tokenize
>>> word_tokenize('When this thing hits 88 miles per hour')
['When', 'this', 'thing', 'hits', '88', 'miles', 'per', 'hour']

I'll leave integrating nltk as an exercise for you, but it should only involve changing one line in my above code.


Search utility that searches through source code files

The POSIX grep command accepts the keyword as the first parameter, then the paths to search as subsequent parameters.  That has the advantage of letting the user specify any number of paths to search.

You misspelled "argumetns".  Also, I recommend writing "#{File::basename($0)}" rather than hardcoding "finder" as the program name.

It is customary to put all of the class / method definitions first, then all of the "main" code at the end.  You've put the argument-handling code at the top, and the file_finder(expand_path(path), keyword) call at the bottom.  Curiously, you test ARGV.length in three places — is it really that important?

file_finder

Avoid using Dir#chdir, as changing the current directory alters the global state of the process.  One consequence of Dir#chdir is that you need to use absolute paths.  For portability, use File::join(path, item) instead of path + "/" + item.

For efficiency, IGNORED_DIRS should be a Set.

def file_finder(path, keyword)
  Dir.foreach(path) do |item|
    next if IGNORED_DIRS.include?(item)

    item_path = File::join(path, item)
    if File.file?(item_path)
      search_in_file(item_path, keyword)
    else
      file_finder(item_path, keyword)
    end
  end
end

expand_path

Your expand_path incorrectly treats an absolute path as a relative path.

When expanding a path starting with ~, I don't see any reason to provide __FILE__ as the second argument to File.expand_path.

In case of an error, you should raise an exception instead of printing a message here.  However, I don't see any reason why there should be an error in the first place.

If you avoid changing directories altogether, then you wouldn't need to generate absolute paths at all.  Then you could just eliminate this function and call File::expand_path instead.

search_in_file

Opening a file without closing it causes a file descriptor leak.

flag is a poor variable name.

I'm not a fan of augmenting the String class, especially for code that is, strictly speaking, related more to terminal control than strings.

def search_in_file(path_to_file, keyword)
  seen = false
  File::open(path_to_file) do |f|
    f.each_with_index do |line, i|
      if line.include?(keyword)
        if not seen
          puts path_to_file.bold.blue
          seen = true
        end
        puts "#{i+1}:".bold.gray + " #{line}".sub(keyword, keyword.bg_red)
      end
    end
  end
  puts "" if seen
end


Custom exception for each invalid input value

With regard to if you need multiple exceptions or not:
I'd argue not in this particular situation, multiple exceptions are great for if you want to do different logic to handle them(so you plan to catch PasswordFormatException because that needs to be handled differently to your other validation errors).

To solve this you can add multiple constants on the same class if you want to return the code for what's invalid at the point you throw it:

class CaliException extends \Exception {
    const INVALID_USERNAME = "DM:USERCA:0001";
    const INVALID_PASSWORD = "DM:USERCA:0002";
    const INVALID_LAST_ACTIVITY_TIME = "DM:USERCA:0003";
    const INVALID_CREATION_TIME = "DM:USERCA:0004";

    private $caliCode;

    // Note that caliCode is now required, forcing you to pass in a constant
    // to say what the error is
    public function __construct(string $caliCode, string $message = "",
                                int $code = 0, Throwable $previous = null) {
        parent::__construct($message, $code, $previous);

        $this->caliCode = $caliCode;
    }

    function getCaliCode(): string {
        return $this->caliCode;
    }
}

// ....
// And then when you use it you now say it's a username or password field that failed validation

throw new CaliException(CaliException::INVALID_USERNAME, 'Username must not contain special characters');

As for if this should extend InvalidArgumentException:
I'd argue not, this feels more like you should have a class for UserInputValidationError or similar and extend this for your purpose. Failing validation of user input is not a fundamental problem with the program which InvalidArgumentException would imply but instead a natural consequence of having to handle user inputs.


Not repeating what 1201ProgramAlarm reported.

std::mutex    m_lock;   // reader writer lock, multiple getters are allowed

I see a regular exclusive lock, not a reader/writer lock.
std::lock_guard<std::mutex> gaurd(m_lock);

Not taking advantage of class template argument deduction?  This is a case where I really want it.  (If not, use an alias for the lock type so it can be easily changed.)
std::lock_guard guard(m_lock);

    m_lruList{},
    m_lruMap{},
    m_lock{}

Just adds noise — is that a thing someone actually recommends?  I would say don’t list all the things that are taken care of on their own.
   for (const auto &node : m_lruList)
        std::cout << node._key << std::endl;

The style in C++ is to put the * or & with the type, not the identifier.  This is called out specifically near the beginning of Stroustrup’s first book, and is an intentional difference from C style.
Some people criticize the leading underscore of identifiers as a style.  I point out that it is easy to clash with compiler-supplied identifiers and you must remember to never use a capital letter after the score, so it is a hazard.

Update
#ifndef LRUCache_h__

Any name containing a double underscore is reserved for use by the implementation.

/***
 * Method:        objcache::LRUCache::LRUCache
 * Access:        public
 * Description: This creates a cache of given size.
 */

Banner comments like this just get in the way of reading the code.  Repeating the function name in a comment just before its definition does what exactly?  (Oh, and a point of nomenclature:  C++ does not have “methods”.)  Nobody comments each function as being public or private.  For the description, don’t prefix it with “Description:”; just describe it.
Since I can see name of the argument is size and see how it’s used on the on the following line
LRUCache(size_t size) :
    m_cacheSize{ size },

a comment saying
// This creates a cache of given size

is useless.  It only repeats what is in the signature:  A constructor creates an instance of this class, and this one takes a size.
See (⧺P.1).  You might also find this useful (Comments starts on page 17; material originally published in 1992).


Getting keyboard input for real-time console application

You could join the two loops. I think this way your intent will be clearer, and it's not like a few extra comparisons are going to cost you anything.

//return "IEnumerable<T>" if all you need to do is iterate over elements
public static IEnumerable<ConsoleKeyInfo> GetInput()
{
    //use "var" if return type is obvious from context
    //use "HashSet<T>" if you need a collection of unique items
    var input = new HashSet<ConsoleKeyInfo>();
    var keyCount = 0;
    while (Console.KeyAvailable)
    {
        var key = Console.ReadKey(true);
        //use constants instead of magic numbers
        if (++keyCount > MaxInputLength) continue;
        //no need to call "Contains", non-unique items will be dropped automatically
        input.Add(key);
    }
    //no need to convert anything
    return input;
}

But I have to question your design. Why do I have to input (and memorize?) a 10-key sequence where every key means something and the order is important? Sounds like a really poor user experience. I feel like it is not the way to go in modern applications, iddqd or not.

Edit: I forgot, that HashSet does not preserve insertion order. So if order is important, you should stick to List (your original approach).


Combinatorics challenge solved it Python

Style
We all have our own 'what is the best' style. However even if you do something that others don't agree with, if you're consistent about it then that's all that matters.

From here you have some inconsistencies in your code.

Indent style. You don't have a fixed style, and you've mixed two styles together to make something I think both sides can agree is not right.

With opening delimiter:

return [lst + [x] for x in·
        range(lst[-1]+1, length)]

Hanging indent:

result = [
    ''.join(symbols[s] for s in el)
    for el in result
]

Both:

result = [ item for sublist in result
    for item in sublist
]

You're not consistent in your newlines in comprehensions.

Item and for _ in on first line:

return [lst + [x] for x in·
        range(lst[-1]+1, length)]

Item and entire for _ in ... on first line:

result = [ item for sublist in result
    for item in sublist
]

Item on first line:

result = [
    ''.join(symbols[s] for s in el)
    for el in result
]

We can fix these by just having a consistent style.
return [
    lst + [x]
    for x in range(lst[-1]+1, length)
]

result = [
    item
    for sublist in result
    for item in sublist
]

result = [
    ''.join(symbols[s] for s in el)
    for el in result
]

Improvements

Your last two comprehensions that build two lists are wasteful when you can just merge the comprehensions together. This will also improve readability.
return [
    ''.join(symbols[s] for s in item)
    for sublist in result
    for item in sublist
]

Your code is not very readable. I can't tell that you're effectively calling itertools.combinations len(symbols) times.
Whilst combinatorics are not very pleasant to read, your code doesn't show the most basic part clearly.
def solution(symbols):
    for i in range(1, 1 + len(symbols)):
        yield from itertools.combinations(symbols, i)

Overall
You should get a consistent style and your code has some improvements to be made.
However your code is pretty good on the combinations front.
The range aspect is smart, maybe too smart, but if you used a docstring to explain the input and output then the implementation details can be guessed at fairly easily from your code.


At the end of the code, it looks like merge() is called by nesting the array in a list and the result is the 0th element of the returned list.  This is an unusual calling convention, is different than the way the built in sorted() is called, and it is not documented, which would likely lead to many errors.  If this interface is needed for the algorithm to work, it would be better if merge() handled these details an then called another function.  For example:

def merge(array):
    return _merge([array], True)

def _merge(array, True):
    ... same as your original code ...

The boolean argument split appears to control whether merge() splits the array into two smaller parts or merges two smaller parts together.  This complicates the logic and makes it more difficult to follow.  It would be better two have two separate functions.

It is also appears that the code takes parts of a recursive implementation and parts from an iterative implementation.  For example, merge is called recursively to split the array into smaller arrays, but for i in range(0, len(array), 2): loops over a list of subarrays and merges them in pairs.

The essence of merge sort is: if the array isn't sorted, split it into two parts, sort both parts separately, and then merge the two parts together.  Here is a recursive implementation:

def merge_sort(array):
    if is_not_sorted(array):
        # split array in two
        middle = len(array) // 2
        left_half = array[:middle]
        right_half = array[middle:]

        # sort each part
        left_half = merge_sort(left_half)
        right_half = merge_sort(right_half)

        array = merge_halves(left_half, right_half)
        return array

    else:
        # array is already sorted
        return array

Usually, if is_not_sorted(): is implemented as if len(array) > 1: (if there is more than one item in the array, it is presumed to be unsorted).  But some implementations (like Python's builtin sorted or list.sort) check small lists to see if they are already sorted.  Also, the two halves are usually sorted using a recursive call to merge_sort(), but some implementations may use a different sorting algorithm if the array is small.

merge_halves() is then basically the same as the while pointer_a < len(array[i])... loop in your code (with a few simplifications):

def merge_halves(left, right):
    merged_array = []
    pointer_a = 0
    pointer_b = 0
    while pointer_a < len(left) and pointer_b < len(right):
        if left[pointer_a] <= right[pointer_b]:
            merged_array.append(left[pointer_a])
            pointer_a += 1

        elif right[pointer_b] < left[pointer_a]:
            merged_array.append(right[pointer_b])
            pointer_b += 1

    #At the end of one subarray, extend temp by the other subarray
    if pointer_a < len(left):
        merged_array.extend(left[pointer_a:])

    elif pointer_b < len(right):
        merged_array.extend(right[pointer_b:])

    return merged_array

An iterative version might look something like this (code on the fly, so may have errors):

def merge(array):
    # make all the sub arrays 1 item long.  A more intelligent version might
    # split it into runs that are already sorted
    array = [[item] for item in array]

    while len(array) > 1:
        temp = []

        for i in range(0, len(array), 2):
            #Pointers are used to check each element of the two mergin arrays
            pointer_a = 0
            pointer_b = 0

            #Loop to merge the array
            while pointer_a < len(array[i]) and pointer_b < len(array[i+1]):
                if array[i][pointer_a] <= array[i + 1][pointer_b]:
                    temp.append(array[i][pointer_a])
                    pointer_a += 1

                else:
                    temp.append(array[i + 1][pointer_b])
                    pointer_b += 1

            if pointer_a < len(array[i]):
                temp.extend(array[i][x])

            elif pointer_b < len(array[i + 1]):
                temp.extend(array[i + 1][x])

        #there were an odd number of sub_arrays, just copy over the last one
        if len(sub_arrays) % 2:
            temp.append(sub_arrays[-1])

        array = temp

    return array[0]


Using a dictionary template for consistent response structure from an API

There is no need to use deepcopy here. Just have a function that returns a new object when you need it. And while you're at it, just make the message and the result parameters of that function. Or even all of them:

def json_response(message, result, status="ok", code=0, error=False):
    return {
        "status" : status,
        "code" : code,
        "error" : error,
        "message" : message,
        "result" : result
    }

@route('/example')
def example():
    result = {
        "title" : "Test Title",
        "body" : "
Lorem ipsum dolor sit amet...
"
    }
    return json_response("Success", result)

Having all as parameters, but with default values, allows you to do this in the future:

json_response("Failure", None, status="fail", code=404, error=True)

In the end it depends on how often you need to use this template whether or not this is better than just directly returning the dictionary explicitly:

@route('/example')
def example():
    return {
        "status" : "ok",
        "code" : 0,
        "error" : False,
        "message" : "Success",
        "result" : {
            "title" : "Test Title",
            "body" : "
Lorem ipsum dolor sit amet...
"
        }
    }


A method to insert a database entry for a newly registered account

Organization, while not exactly code related, is still very important. Especially when it comes to OOP and especially when you're just getting started. If your code is organized correctly, there is no need for namespaces such as ".class". I spent a solid week perusing different frameworks before finally deciding on one I liked. Then I spent another month fine tuning and tweaking it. Originally, my organizational scheme came from the Zend framework.

application
    configs
    controllers
    models
    views
data
    logs
    cache
public
    images
    css
    js

There's a bit more to it, but I got the most important bits. This scheme specifically caters to an MVC framework, so it may not apply to your situation. You don't have to use this scheme, you don't even have to use a popular one. Hell, you can create your own to fit your own needs, and sometimes that is required. However, a good organizational scheme is hard to find and the popular ones are usually popular for a reason. And one thing a good organizational scheme should do is allow you to avoid namespacing your files. In my scheme my class files would go in one of two folders. The "controllers" or the "models". Knowing these were the only locations for class files means I don't have to namespace them.

Sorry for the mini-rant, let's move along now. I don't really see anything wrong with the OOP, but then again, there's not really much going on here. I do have a few suggestions that might help though.

First, your class is incomplete. You have three class properties and have not declared them. You should always declare your properties, otherwise you risk allowing public access to private properties, such as the password property.

class accountactions() {
    private
        $username,
        $password,
        $emal
    ;

You should avoid internal comments as they just add clutter to your code. If your code is self-documenting then most comments become unnecessary anyways. Everything else can be relegated to doccomments. So, for instance: "Hash password" is pretty obvious from the context and is unnecessary.

Its a minor violation, but still, there is a violation of the "Don't Repeat Yourself" (DRY) Principle here. As the name implies, your code should not repeat itself. You use the same function on each of your method's parameters in order to sanitize them. The easiest way to do this would be to change the way the method accepts its parameters so that you instead accepted an array. Then you could loop or walk over the array to sanitize its contents. For instance:

public function register( Array $credentials ) {
    array_walk( $credentials, 'mysql_real_escape_string' );

    $this->username = $credentials[ 'username' ];
    //etc...

However, there is a problem with this. For one, these parameters should not be sanitized. Validated: yes; Sanitized: no. You validate for registry; You sanitize for login. If you sanitize them now then you could be changing what that user provided without informing them, which could cause all kinds of confusion. The better thing to do here would be to verify that it has no illegal characters and have the user change it if necessary. Once you validate it, it has essentially been sanitized and you can use it like normal.

Another thing you might consider is using custom sanitizing/validating filters. mysql_real_escape_string() was a very nifty tool when you had nothing better to use, but now there are options such as filter_input() and filter_var(). The former should only be used when accessing raw user input from a form directly, the latter when accepting unknown variables. In this instance, even though you will probably get these values from a form, you will use the latter because your method only sees it as a variable and doesn't know for sure where it comes from.

if( filter_var( $username, FILTER_SANITIZE_STRING ) === $username ) {
    $this->username = $username;
}
if( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
    $this->email = $email;
}

You might want to consider adding whitespace for legibility on lines that are too long. The rule of thumb here is 80 characters, including indentation. Both PHP and SQL are very lax when it comes to whitespace, so don't be afraid to use it.

$db->simplequery( "
    INSERT INTO radio_users(
        id,
        username,
        password,
        email
    ) VALUES (
        '',
        '$this->username',
        '$this->password',
        '$this->email'
    )
" );

Now, as to how you can incorporate your $db class into your accountactions class. The easiest, and best, way is to inject it. This can either be done during construction, or via some sort of setter. I'm going to assume that your database model is still MySQL because I can't find anything to contradict it, so I'll use that to type hint it. By the way, you should really upgrade your MySQL to MySQLi or PDO and take advantage of their prepared statements if you haven't already done so.

public function __construct( MySQL $db ) {
    $this->db = $db;
}

/** or as a setter */
public function setDb( MySQL $db ) {
    $this->db = $db;
}

Hope this helps!


Since you're loading all comments for all issues, I think

await client.Comment.GetAllForRepository(owner, name)

is what you're looking for. Otherwise, if you do need to use GetAllForIssue, try using Task.WhenAll to run comments retrieval in parallel:

public static async Task<IReadOnlyList<IssueWithComments>> GetAllForRepositoryWithComments(IIssuesClient client, string owner, string name)
{
    var issues = await client.GetAllForRepository(owner, name);

    return await Task.WhenAll(issues.Select(async i => IssueWithComments.FromIssue(i, await client.Comment.GetAllForIssue(owner, name, i.Number)));
}


Connection request to LinkedIn profiles on search page

It doesn't sound like a great idea to run something infinitely.
Especially, doing $("a:contains('Next >')")[0].click() periodically is flawed, because when there is no more Next links, the dom query will return empty result, the [0] index of which is undefined, and the .click() will throw a TypeError.

I suggest to make it possible to stop the periodic calls, especially the second one. See this related answer for a technique that you can use.

In this code, the parameters index and a of the anonymous function are never used:

$("a:contains('Connect')").each(function (index, a) {
    $(this).trigger('click');
});

You could omit them, using simply function () { in the function declaration.

Instead of using anonymous functions in the setInterval calls,
I suggest to use named functions, something like this:

var clickConnect = function() { ... };

var clickNext = function() { ... };

window.setInterval(clickConnect, 1000);
window.setInterval(clickNext, 5000);

When written this way, the window.setInterval calls are easier to read,
When using anonymous functions,
it can be hard to search for the delay parameter,
as you have to scan the code to see where the function ends and the delay parameter begins.


It's an unusual approach, it's very cryptic and as a result will be a bad maintenance of the code in the future, if in the future you wanna add some custom validators, style or add some dependent validators or other things will became a chimera this component, definetly will kill productivity on quick prototyping. If you wanna handle a big bulks of forms, i suggest you to look at using a dynamic form.


The major problem I can see is this piece of code :

            try {
                if (num1.getText().length() == 0 || num2.getText().length() == 0) {
                    throw new Exception();
                }
            }
            catch (Exception ex){
                JOptionPane.showMessageDialog(null, "Field missing", "Warning", JOptionPane.WARNING_MESSAGE);
            }

If you throw inside a try-catch, you will not exit the function. Since your condition is num1.getText().length() == 0 when you try to do Double.parseDouble(num1.getTest() well your string is empty so this throw an exception.

You should not use throw and catch to manage an error, not in this way. You should first remove the try-catch and work with a simple if :

if (num1.getText().isEmpty() || num2.getText().isEmpty()) {
    JOptionPane.showMessageDialog(null, "Field missing", "Warning", JOptionPane.WARNING_MESSAGE);
    throw new Exception();
}

I would not suggested that since now you add a complexity to your code.

The method now need to declare throws Exception (which is not possible for actionPerformed()), now the caller need to manage this possible outcome.
Exception would be too generic.
I guess that this case would happen a lot,so throwing an Exception could become heavy for the program.

The real solution is to only return from the method. You've already warned the user that he need to do something (you could be more clear) and you don't want to execute the rest of method.

There is some general notion that are lacking in your code, but I won't cover it all, since I mention it in others answer :

There is naming convetions in Java, b_add does not follow it, it should be bAdd (but it could simply be add)
You should not extend JFrame, but rather just have a private JFrame, you're not adding any functionnality to JFrame you're only using it. (Composition over inheritance) answer that cover a bit that part


Formatting

I really like my SQL queries to be formatted a certain way. For example, if I'm retrieving multiple columns I typically do something like

SELECT
    col1
    ,col2
    ,col3
    ,col4
FROM mytable

I thought it was super ugly at first, but having each on its own line is nice for readability (I don't like having them on the same line as the SELECT either, same reason). Putting the comma at the front of the line seems kinda weird, but I do like that I don't have to try and remember to add commas at the EOL if I grab more columns, which is an error I used to run into all of the time.

I like to format my JOINs a certain way as well, for example

SELECT *
FROM Table1 AS Alias1
     JOIN Table2 AS Alias2
         ON Alias1.Column1 = Alias2.Column3

I find that this makes it much easier to visually separate each table, or CTE, or sub-query, that is being joined. I also find that it makes the conditions by which they're joined much easier to distinguish as well.

Lastly, I find that when combining multiple conditions it is a lot nicer to have the boolean logic (AND/OR) to be at the beginning of the line; then I just look at a single column to see how that row is combined with everything else.

SELECT * FROM myTable
WHERE (COND1
       AND COND2
       AND COND3)
      OR COND4;

Use constants

Right now you have a bunch of magic numbers all over the place, e.g.

Posts.Score > 0
Users.Reputation < 4000
Posts.PostTypeId IN (1, 3) AND
PostHistoryTypeId IN (14, 15)

I personally really like to have constants for values where it makes sense. In this case, I'd probably rewrite those lines to look like this

DECLARE @MinPostScore int = 0
DECLARE @MaxReputation int = 4000
DECLARE @PostTypes TABLE (Value int)
INSERT INTO @PostTypes VALUES (1)
INSERT INTO @PostTypes VALUES (3)
DECLARE @PostHistoryTypes TABLE (Value int)
INSERT INTO @PostHistoryTypes VALUES (14)
INSERT INTO @PostHistoryTypes VALUES (15)

...

Posts.Score > @MinPostScore
Users.Reputation < @MaxReputation
Posts.PostTypeId IN (SELECT Value FROM @PostTypes) AND
PostHistoryTypeId IN (SELECT Value FROM @PostHistoryTypes)

You may also find it helpful to declare values used repeatedly (i.e. '[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]') as variables and insert/concat as needed.

Comments per clause in WHERE

A number of these clauses don't make a lot of sense to a lay reader (mostly because I don't know much about SEDE) - variables instead of magic numbers would help, but maybe a comment describing the query (or replacing it with a function, if performance/SEDE allows it) would help.

Character classes

According to msdn you can use character ranges with LIKE. This would make the last few lines look like this:

Posts.Title LIKE '[a-z]%' OR
Posts.Title LIKE '%[A-Za-z]([A-Za-z]%' OR
Posts.Title LIKE '%[A-Za-z])[A-Za-z]%' OR
Posts.Title LIKE '%[A-Za-z],[A-Za-z]%' OR
Posts.Title LIKE '% i[ '']%'

You can then simplify this even more, like so

Posts.Title LIKE '[a-z]%' OR
Posts.Title LIKE '%[A-Za-z][(),][A-Za-z]%' OR
Posts.Title LIKE '% i[ '']%'

Unfortunately the columns you're comparing use case-sensitive collation (played around using this to figure that out) so you can't just leave out one version. SEDE is run on T-SQL, so it won't support the iLIKE operator either.

Short circuiting

Unfortunately, short circuiting isn't guaranteed in T SQL, so we can't guarantee any optimizations here, however if you carefully examine your conditions you might find ways where you can take advantage of short-circuiting if it were to occur. For example, you might choose to place the "most likely" case first, or use De Morgan's Laws to switch up the order such that each case is mutually exclusive. YMMV.


PHP function to convert a Portuguese word from plural to singular

Let me start by saying, that I have respect for Mike Brant, and have been enjoying his posts for quite a while now.  However, I disagree with some of his review.

$regex_config can not store the the replacement values as associative keys unless the regex patterns that use the same replacement value are merged.  This is not explained in the ... (yatta-yatta).  The key clash would be on el.
Simply throwing 1 at the end of preg_replace() is NOT going to provide the desired output.  Declaring a replacement limit on the call will only limit the replacements PER array element. The damage is evident in this output: meses => mês = mê
Most trivially, array_values() doesn't need to be called because preg_replace() is "key ignorant" regarding the array inputs.

For this process to maintain accuracy, there needs to be a return as soon as a replacement occurs on the input string.  To avoid calling multiple replacements, iterate the array of pattern-replacement pairs.
You can avoid using capture groups and shorten your replacement strings in a couple places by implementing the \K metacharacter (restart fullstring match).  This way you don't need to use $1 or rewrite a literals from the pattern into the replacement.
If you need to add case-sensitivity to your replacement process, you can check the last character of the incoming string.  If it is uppercase, assume the whole string is in CAPS and call mb_strtoupper().
I don't have a sample string to test against ~[áó].*eis$~iu, but I wonder if this is accurate/correct and my Portuguese is not too sharp.
After my implementation of \K you can see that two pairs of patterns are making the same replacement.  If you don't expect to be making lots of future adjustments to this set of regex patterns, you could combine the patterns with a pipe.  Here's what I mean: '~(?:[áó].*eis|[eé]is)$~iu' => 'el', and '~(?:[rzs]\Kes|s)$~iu' => ''
I am using the regex patterns as the keys because they will all logically be unique.  the same cannot be said about the replacement values (not without merging anyhow).

Code: (Demo)

function is_allcaps($string)
{
    $last_letter = mb_substr($string, -1, 1, 'UTF-8');
    return $last_letter === mb_strtoupper($last_letter, 'UTF-8');
    // otherwise use cytpe_upper() and setlocale()
}

function plural_to_singular($string)
{
    // quick return of "untouchables"
    if(preg_match('~^(?:[oó]culos|parab[eé]ns|f[eé]rias)$~iu', $string))
    {
        return $string;
    }

    $regex_map = [
        '~[õã]es$~iu' => 'ão',
        '~(?:[áó].*e|[eé])is$~iu' => 'el',
        '~[^eé]\Kis$~iu' => 'l',
        '~ns$~iu' => 'm',
        '~eses$~iu' => 'ês',
        '~(?:[rzs]\Ke)?s$~iu' => ''
    ];

    foreach ($regex_map as $pattern => $replacement)
    {
        $singular = preg_replace($pattern, $replacement, $string, 1, $count);
        if ($count)
        {
            return is_allcaps($string) ? mb_strtoupper($singular) : $singular;

        }
    }
    return $string;
}

$words = array(
    'óculos' => 'óculos',
    'papéis' => 'papel',
    'anéis' => 'anel',
    'PASTEIS' => 'PASTEL',
    'CAMIÕES' => 'CAMIÃO',
    'rodas' => 'roda',
    'cães' => 'cão',
    'meses' => 'mês',
    'vezes' => 'vez',
    'luzes' => 'luz',
    'cristais' => 'cristal',
    'canções' => 'canção',
    'nuvens' => 'nuvem',
    'alemães' => 'alemão'
);

foreach($words as $plural => $singular)
{
    echo "$plural => $singular = " , plural_to_singular($plural) , "\n";
}


Better way to use a Condition (CancellationToken)

EDIT

I think this is what you are looking for, it will only check once inside the using block, if you want to dispose the form if that first Queue.TryTake(out TextureData, 300)) is false then add to the else of that statement.

if you really want to test it at the last second you could do it like this

 SharpDX.Windows.RenderLoop.Run(form, () =>
    {
        if (Queue.TryTake(out TextureData, 300))
        {
            Stoptimer = new Stopwatch();
            Stoptimer.Start();

            device.BeginScene();
            sprite.Begin(SpriteFlags.None);
            try
            {
                using (var surface = texture.GetSurfaceLevel(0))
                {
                    if (!CTS.IsCancellationRequested)
                    {
                        Surface.FromFileInMemory(surface, TextureData, SharpDX.Direct3D9.Filter.None, 0);
                    }
                    Else
                    {

                        // I imagine if you close the form that you want this stuff to
                        //happen as well
                        sprite.End();
                        device.EndScene();
                        device.Present();
                        Stoptimer.Stop();
                        Console.WriteLine(Stoptimer.ElapsedTicks);
                        form.Dispose();
                    }
                }
                sprite.Draw(texture, new ColorBGRA(0xffffffff));
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Rendering: Texture");
            }

            sprite.End();
            device.EndScene();
            device.Present();
            Stoptimer.Stop();
            Console.WriteLine(Stoptimer.ElapsedTicks);
        }
        //Optional for Disposing of the form if Queue.TryTake(out TextureData, 300))
        // is false
        Else
        {
            form.Dispose();
        }
    });


Calculating (\$a^2\$ + \$b(2c-d)^2)/(3e)\$ in assembly

Some registers have a basic purpose and they supposed to be used for those but it's not that you can't use cx for storing arithmetic operation result. There are few things you could improve in your code
Comment
I would really recommend you to start putting comments. Assembly is not a difficult language but it's very context specific. Each similar looking assembly line might be doing different thing depending on the context and comments are important, even in such small application codebase as this one. Do not try to write what the instruction does in english like
add ax,cx ;adds content of cx to ax

but rather explain the meaning.
add ax,cx ;after that ax  = a^2 + b(2*c - d)^2

Assembly
As I wrote above there's nothing wrong in your usage of assembly (unless you use some register that can't be used - like segment ones), but there are few things you could optimize.
mov ax,0

could be written as xor ax,ax and saved few bytes (only if you want to). And you don't have to zero ax & cx as you don't use it before you assign any value to it.
This is a strange construct too:
mov dx,ax
push dx
mov dx,0

You are moving the result from calculation to dx to push in to the stack and then clearing the register. Why not just
push ax

Instructions at the end also looks like they are doing too much of moving around so this could be simplified as:
mov ax,e
mov bx,3
mul bx
mov bx,ax
pop ax
div bx

You are writing that you want to use registers more so those push/pop could also be removed. Also res is unsued in the code - remove it.
Final program (probably - could be even more improved)
.model small
.stack 100h
.data
a dw 4
b dw 15
c dw 86
d dw 155
e dw 8
.code
_start:
  mov ax,@data
  mov ds,ax

  xor dx,dx
  mov ax,c
  shl ax,1  ; ax = 2*c

  mov bx,d
  sub ax,bx ; ax = 2*c - d
  mul ax    ; ax = (2*c - d)^2
  mul b     ; ax = b*(2*c - d)^2
  mov cx,ax

  xor dx,dx
  mov ax,e
  mov bx,3
  mul bx    ; ax = 3*e
  mov bx,ax

  mov ax,a
  mul ax    ; ax = a^2
  add ax,cx ; cx = a^2 + b*(2*c - d)^2

  div bx    ; ax = (a^2 + b*(2*c - d)^2)/3e

  mov ax,4c00h
  int 21h
end _start


Synchronizing two SQL Server database tables with the most recent changes to both tables

How often would you be writing to the master? And what purpose is Master serving in your setup?

Merge or peer-to-peer replication is one solution to keep both databases in sync but keep in mind they can be time consuming to troubleshoot and adds another extra thing in the mix to worry about.

Typically this would be done by updating records based on ID and last_updated key on tables. Merge statements can be a cause for race conditions where multiple users try and run the merge at the same time. Doing these operations with individual statements may keep you more clarity on the different operations that are happening on the db and keep things simple.

Delete: I would do this first by marking the records as 'soft-delete' (can be bit value) on master. Then running a sql server job on a schedule to remove all the records from tables which are marked for deletion.

Insert: Pull new records down from master based on the primary key value being higher than what's in the client.

Update: Based on the last_update field. This will solve the issue of updating tables on the remote server as well.


I have a few suggestions:

In your constructor, you are passing in string by copy when it is completely unnecessary to do so. You should pass these in by const reference:

bankAcc(const string &fn, const string &ln) { /*...*/ }

Also, this constructor should check whether or not fn or ln are clean inputs (i.e. they're valid first and last names). You can do this like so:

bankAcc(const string &fn, const string &ln)
{
    if (fn == "" || ln == "")
        throw std::invalid_argument("Can't have empty names");
    firstName = fn;
    lastName = ln;
}

Speaking of firstName and lastName, I don't see a use for them here at all as they're only used in the constructor and nowhere else. Is there a need for them?

You should also practice the Principle of Sole Responsibility here. In other words, each class should have only one single responsibility to take care of. Your class is called bankAcc yet it really seems more like a BankAccountLoginValidator class to me. Your class isn't doing anything that a bank account should be doing (no balance, no withdrawal/deposit schemes etc). Moreover, you should generally separate I/O operations from the validation code in this class. Have the caller of the class objects perform the I/O and then have them use your class to validate their input. Your class should not be responsible for I/O.

Finally, your use of two vectors to store the user-name and password is inefficient since you end up spending O(n) time searching for the right username in the usernames vector. Instead, look at using a hashtable to store this information instead. A hash-table in C++11 is called std::unordered_map. Then, your lookup operation can be done in O(1) amortized time. With this map, your correct_login() function becomes unnecessary.

Here's your code refactored a bit:

class bankAcc
{
public:
    bankAcc() = default;
    bankAcc(const string &fn, const string &ln)
    {
        if (fn == "" || ln == "")
            throw std::invalid_argument("Error! Can't have empty names");
        firstName = fn;
        lastName = ln;
    }
    bool createUser(const string &user_name, const string &pass_word)
    {
        if (user_name == "" || pass_word == "")
            return false;
        /* Maybe add more validation code here */
        // ....

        uname_to_pass.insert(user_name, pass_word);
    }
    bool login(const string & user_name, const string &pass) const
    {
        return uname_to_pass[user_name] == pass;
    }

private:
    static unordered_map<string, string> uname_to_pass;
    string firstName, lastName;
    string username, password;
};


Finding a path from one wikipedia page to another using semantic similarity of links (Spacy)

First a few observations, then we'll try to improve things.

"Frog" in the first list comprehension should be closest_match (which is initialized to 'frog').
The two list comprehensions are identical, which suggests the code could be rearranged to eliminate the redundancy.
In the while loop, item.similarity() already returns a float, so the float() call is redundant. Also, it seems fishy that the test involves whatever happend to be the last item in link_list_1 or linked_list.
Avoid hard coding "magic numbers" like 1.0, 0.0, and 20 in the code. Use a defined constants with meaningful names to make the code clearer. For example, while item.similarity(nlp(word_2))) != PERFECT_MATCH.
I suspect calling nlp() is computationally expensive, but the code calls nlp(word_2) repeatedly.
word is a poor variable name, particularly when the page titles or links often have multiple words.
If a DisambiguationError is raised, the error is ignored. But, closest_match isn't changed, so the error will repeat the next time through the loop...until the loop count limit is reached.

Now let's try to improve the code.
It looks like the basic idea behind your code is to try to get from one Wikipedia page to a target page by following links. The strategy for picking which link to follow is to pick the one with text that is most similar to the target page name.  There doesn't appear to be any kind of breadth first search or back tracking or anything.
You got the code to grab the links on a page. Right now, the code runs nlp() on each link and check if it is similar to the target before checking if it's already been visited.
raw_links = wikipedia.page(current_page, auto_suggest=False).links
new_links = (link for link in raw_links if link not in path)

According to the spacy documentation it is more efficient to use nlp.pipe(), to process a sequence of texts. nlp.pipe() is a generator that yields a spacy.Doc for each text in the input.
next_pages = nlp.pipe(new_links)

But we want the page with the highest similarity to the target page. The Python builtin max() should work with an approriate key function:
target_page = nlp(target)  # this is done once outside the loop

next_page = max(nlp.pipe(new_links), key=target_page.similarity)

Of course, package it all up in a function:
def find_path(start, target, limit=20):
    start = start.lower()
    target = target.lower()

    try:
        target_page = nlp(target)

        current = start
        path = [start]

        for _ in range(limit):
            raw_links = wikipedia.page(current, auto_suggest=False).links
            new_links = (link.lower() for link in raw_links if link not in path)
            best_page = max(nlp.pipe(new_links), key=target_page.similarity)

            current = best_page.text
            path.append(current)

            if current == target:
                return path

    except wikipedia.exceptions.DisambiguationError as e:
        print(e)

    return []

START = "frog"
TARGET = "crystal"

print(find_path(START, TARGET))

Note: I don't have spacy so I couldn't test this code. It may have some bugs, but based on the docs, I think it should point you in the right direction.