Cause of your performance issue

As this is homework, I don't want to give away the whole solution but I'll tell you where the problem is and if you need more help, just comment and I'll see what I can do.

You can have up to \$10^4\$ test cases and the number of rows can go up to \$10^8\$. You're better off assuming your examiner will actually use such a test case. More than likely they will.

Looking at your code you have two for-loops.

This one:

  for (unsigned long long int i = 0; i < stPrimerov; i++)

and this one:

  for (unsigned long long int l = 0; l< temp; l++)

where temp is \$\max_{\forall i}(row_i)\$. So the worst case is when: temp = 10E8, and then the inner loop is executed stPrimerov=10E4 times, resulting in \$10^{12}\$ iterations through the inner loop. Now that's a lot.

Instead of this for (unsigned long long int l = 0; l< temp; l++) you must realize that there are only 4 interesting points that you need to look at, and those are l=array[x]. So by looking at the values in the array and how they differ, you will be able to determine how many lines are necessary without checking each row. So if you can replace the inner for loop with some smart checking, you can reduce from \$10^{12}\$ to \$10^{4}\$ loop iterations which should make even the hardest test cases run in under half a second. :)

Try to think of it for yourself for a while and come back later if you're still stuck and look at the hints below.

Hint #2

   Let's consider an easier problem. Let the input be the same, but all
 columns are either 0 or k high. Like this:

     3
     0 3 3 0
     0 4 0 4
     9 0 9 9

 Result :

     3  (3*1)
     8  (4*2)
     18 (9*2)

 Now this is easy, just count the number of streaks of non zero
 columns. There is one streak that is two wide in the first case.
 There are two streaks that are one column wide in the second set. And
 there are two streaks in the last case, one that is one column wide and
 one that is two columns wide. Then multiply the number of streaks by
 the height of the columns.

Hint #3

   Given four columns of (possibly) unique heights, the rows can be split
 into at most 4 sections where each column in the section is either
 zero or equally tall as the other columns. With these two hints you
 should be able to figure out how to calculate the answer without
 checking every row in the inner loop.


Calculate CPU% by process from /proc/stat and /proc//stat

You have code outside of functions or an if __name__ == "__main__" guard (which isn't ideal in itself), both above and below the various function definitions, which makes the code relatively difficult to follow. I would structure the script as follows:

import os
import subprocess
import sys
import time

def proct(pid):
    ...

def cput():
    ...

def main(pid):
    ...

def parse_args():
    ...
    return pid

if __name__ == "__main__":
    main(parse_args())

Now if you want to import this functionality elsewhere, it's easy. Also, note that I have made the imports alphabetical, per the style guide.

I would factor out any temporary variables, e.g.

proctotal = int(utime) + int(stime)
return(float(proctotal))

can be written:

return float(int(utime) + int(stime))

Try not to do the same thing twice, e.g.

proctimes = pidfile.readline()
utime = proctimes.split(' ')[13]
stime = proctimes.split(' ')[14]

could be rewritten

proctimes = pidfile.readline().split(' ')
utime = proctime[13] # you could also call int here
stime = proctime[14]

which only calls str.split once.

Consider adding docstrings to your functions, rather than the inline comments (some of which are redundant - utime = proctimes.split(' ')[13] does not need the explanation # get utime from /proc/<pid>/stat, 14 item, which just adds an extra line to read). Better function names would also help with clarity - e.g. cpu_total rather than cput.

The main part of cput:

cputimes = procfile.readline()
cputotal = 0
for i in cputimes.split(' ')[2:]:
    i = int(i)
    cputotal = (cputotal + i)
return(float(cputotal))

can be rewritten in a functional style:

return sum(map(float, procfile.readline().split(' ')[2:]))

or using a generator expression:

return sum(float(s) for s in procfile.readline().split(' ')[2:])


If some of your init values (prefix, filePath, fileName) are empty, you should fail on init, not once you try to log something. Returning errors as soon as possible is a good practice and makes debugging much easier.
setPrefix should be called setCustomLogger or something, or better, since it's a one-line function, just inline it.
You're calling setPrefix twice on init. createLogFile shouldn't call it.
Don't join paths using string concatenation. Use filepath.Join instead.
You should check that createLogFile succeeds on init, and fail fast otherwise.
InitLogger should simply be called Init, PrintLog should be Print, FatalLog should be Fatal: you're going to call them with logger.[…] from outside your package.
godoc comments should start with the name of the function they document: PrintLog prints a log message on the console, as well as in the log file… or something.
Why are you calling createLogFile many times? Just call it on init, save the file somewhere and use it each time. I think this also allows you to get rid of all these weird variables and replace them with only what you need (an open file).
Hoooo I understand why, it's because it needs to be reinitialized to os.Stderr. Damn, that's complex. Why not simply have two loggers (once initialized to os.Stderr and the other to your file, and simply call the corresponding function on each when your custom logger is called?
You're never closing your file. There is no way you can do that from your logging package (unless you open/close it every time you write a log line, but this is terribly inefficient), so maybe your Init function should take a os.File argument instead of a file path + file name. This way, the main function of your program (which will initialize the logger) can close it once the program is over. Of course, you should also close it when Fatal is called

In short: your Print method should be two lines long, your Fatal method should be three lines long, you shouldn't have more than 2 global variables, and all errors should be caught on Init.


Work command handler for an economy system

Why loop?

for x in posts.find({"guildid":f"{ctx.guild.id}","id":f"{ctx.author.id}"},{ "_id": 0,"job":1,"level":1}):
  level = int(x["level"])

You're looping over the result of posts.find to... convert an element to an integer and then throw it away? Are you sure that this is what you want to be doing?

If you care about level, your current code is overwriting it on every iteration, so you'll only get the last one.

Don't repeat yourself

for job_name, level_min, income in (
   ('Garbage Collector',  0,  50),
   (          'Cleaner',  7,  70),
   (       'Car Washer', 16, 105),
   (             'Maid', 27, 145),
   (     'Receptionist', 36, 185)
):
    if selection.lower() == job_name.lower() and level >= level_min:
        data = {
           "id": f"{ctx.author.id}",
           "guildid": f"{ctx.guild.id}"
        }
        set_stuff = {
          "$set": {
              "job": job_name,
              "income": income
          }
        }
        posts.update_one(data, set_stuff)
        break
else:
    return await ctx.send(f"You are currently {level}, please go to school using ?learn")

If you want to get fancier, you can use a case-insensitive dictionary, but for this, that isn't strictly needed.


There are a bunch of small improvements you can make.

Since you aren't using name or setName, you can remove them and their useState call (consider a linter to warn on unused variables).

You have <form onSubmit={search}>, but the search function does filter(event.target.value.toLowerCase()). Forms don't have .values, so this will throw an error when the button is pressed. Also, the search function could be confused with the Search component - the difference is only in capitalization, which isn't enough. The button doesn't do anything otherwise, because searching occurs when the input's change event fires.  You might consider removing the button completely - this way you can remove the search function and just call filter:

<form>
    <input onChange={event => filter(event.target.value)} />
</form>

In your code, eveywhere you return JSX at the bottom of a function, there's no trailing ; after the final ). This can result in bugs if you ever decided to put the fragment into a variable instead of returning immediately, due to automatic semicolon insertion. Since you're using semicolons everywhere else, consider using them everywhere they're appropriate as well. (again, linting will help with this)

Similarly to the search vs Search above, you also have a persons array and a Persons component. Maybe call the component PersonsList instead, since it creates a
.

Rather than using forEach and conditionally pushing to an array outside, it may be a better idea to construct the array directly by filtering for elements which match, then .mapping to the individual
s. Higher-order functions are great:

const PersonsList = ({ persons }) => (

        {(
            persons
                .filter(person => person.show)
                .map(person =>
{person.name} -- his/her telephone number: {person.phone}
)
        )}

);

In addPerson, if you want to check whether any items in an array match a condition, rather than setting a flag outside and conditionally reassigning it while iterating over an array, it's more appropriate to use Array.prototype.some:

const alreadyExists = persons.some(person => person.name === name);

If you were to use your original code, at least use strict equality with === instead of loose equality ==.

Also in addPerson, using window.alert is almost never a good choice. It's user-unfriendly, since it completely blocks them from using the rest of the page. It also prevents any other Javascript from executing until the alert is dismissed, which would be a problem if there were anything on the page other than this phone number component. Inform the user of the problem some other way. A very simple tweak would be to add errorMessage to the form's state:

if (!alreadyExists)
    setPersons(persons.concat({ name, phone, show: true }));
else
    setNewFormInfo({ name, phone, errorMessage: `${name} is already added to the list!` });

and add to the form's JSX:

{(errorMessage &&
{errorMessage}
)}

In the filter function, there's no need to check if the input is empty - if it is, everything will be rendered anyway. Feel free to remove that part and make the code simpler.

Also in filter, since you're creating a filtered array by iterating over each element of persons and pushing an element to filtered, using .map would be more appropriate than forEach / if / push:

function filter(nameToFilter) {
    const nameToFilterLower = nameToFilter.toLowerCase();
    setPersons(persons.map(person =>
        ({
            ...person,
            show: person.name.toLowerCase().includes(nameToFilterLower),
        })
    ));
}

If you run the development version, you'll see the warning:

  Warning: Each child in a list should have a unique "key" prop.

Without such a prop, each element will have to be re-created each time. See here for an in-depth explanation. Since you're only adding items to the list, easiest fix would be to add
 {
    return (

Search

            <form>
                <input onChange={event => filter(event.target.value)} />
            </form>

    );
};

const PersonsList = ({ persons }) => (

        {(
            persons
                .filter(person => person.show)
                .map(({ name, phone }) =>
{name} -- his/her telephone number: {phone}
)
        )}

);

const App = () => {
    const [persons, setPersons] = useState([
        { name: 'Arto Hellas', phone: '040-123456', show: true },
        { name: 'Ada Lovelace', phone: '39-44-5323523', show: true },
        { name: 'Dan Abramov', phone: '12-43-234345', show: true },
        { name: 'Mary Poppendieck', phone: '39-23-6423122', show: true }
    ]);

    const [{ name, phone, errorMessage = '' }, setNewFormInfo] = useState({ name: '', phone: '' });
    function addPerson(event) {
        event.preventDefault();

        const alreadyExists = persons.some(person => person.name === name);
        if (!alreadyExists)
            setPersons(persons.concat({ name, phone, show: true }));
        else
            setNewFormInfo({ name, phone, errorMessage: `${name} is already added to the list!` });
    }

    function filter(nameToFilter) {
        const nameToFilterLower = nameToFilter.toLowerCase();
        setPersons(persons.map(person =>
            ({
                ...person,
                show: person.name.toLowerCase().includes(nameToFilterLower),
            })
        ));
    }

    return (

            <Search filter={filter} />

Phonebook

            <form onSubmit={addPerson}>

                    name: <input onChange={event => setNewFormInfo({ name: event.target.value, phone })} />

                    number: <input onChange={event => setNewFormInfo({ name, phone: event.target.value })} />

                    <button type="submit">add</button>

                {(errorMessage &&
{errorMessage}
)}
            </form>

Persons

            <PersonsList persons={persons} />

    );
};
ReactDOM.render(<App />, document.getElementById("root"))
.error {
  color: red;
}

  Can I make persons a class?

You can, but React highly recommends using hooks (and stateless functional components) when possible. They're easier to make sense of too, IMO.

  in larger applications, each person would have methods and more variables

If you want to encapsulate common functionality for Persons, you can easily do so by putting it into its own file and defining those functions you need inside that file (or by importing them), eg:

// example helper function
const transformName = name => name.toUpperCase();
export const PersonsList = ({persons}) =>
  // ...

{transformName(name)} -- his/her telephone number: {phone}

  // ...

There are a few rare cases for which classes must still be used, but none of those circumstances are relevant here.


Generally, you should do what you can not to throw an exception - it is slow and it looks bad.

In this case, you should go with:

        if (fstIndex<fst.length){
            fstIndexValue = fst[fstIndex];
        } else {
            System.arraycopy(snd, sndIndex, result, fstIndex + sndIndex, snd.length - sndIndex);
            break;
        }

Exceptions, as the name implies, suggest an exceptional condition in which the application is. In your case, it's just the algorithm's termination point - a point which you want to reach. It's not exceptional, it's desired.

Also, I don't think there ever is a good excuse to explicitly catch a java.lang.ArrayIndexOutOfBoundsException - if your code is throwing it, then you're doing something else wrong (namely, missing appropriate checks).


Find top two clothing sizes in the array

You didn't specify if you were allowed to use ecmascript-6 features or not but presumably you were, since you used let and arrow functions. As an interviewer, I would note that you used those features, yet you iterated over the array using a regular for loop instead of using for...of. That isn't necessarily a bad thing since it demonstrates that you know how to increment a counter in a standard loop and then use that for indexing into the array, but you don't have to if you use a for...of loop.

The technique for sorting the array is good, though because Array.prototype.sort() "sorts the elements of an array in place and returns the array"1 there isn't really a need to store the value in newArr because resultArr is sorted.

let newArr = resultArr.sort((a,b)=>{
    return a[0]-b[0];
});

You could have just returned the first two elements of resultArr.

Also, const could have been used for any variable that is never re-assigned - including arrays that merely have elements pushed into them - to avoid accidental re-assignment.

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


Getting integer values and one CSS class name

First off, the question. Because some functionality is missing, I can't test my proposed solution. Try to ask self contained questions.

A possible alternative approach is to analyze the 4 integer and keep track.

function keepTrack(info, integer, cssClass){
  info[integer] = info[integer] || [];
  info[integer].push(cssClass);
}

info = {};
keepTrack(info, element1, 'element1-css');
keepTrack(info, element2, 'element2-css');
keepTrack(info, element3, 'element3-css');
keepTrack(info, element4, 'element4-css');

This way you have a list of items for each, you can just check how many css items there are per length and call the correct function with spread syntax.

for(integer in info){
  //You could use a switch here
  if(info[integer].length == 4)
    fourEqualElementsCss(...info[integer]);
  else if(info[integer].length == 3)
    threeEqualElementsCss(...info[integer]);
  else if(info[integer].length == 2)
    twoEqualElementsCss(...info[integer]);
}


Its a good start.
But function pointers are not the only type callable objects. Functors were a big part of C++03 and with C++11 lambdas are even more important.

Rather than using:

T(*func)(Ts...)

Which handles function pointers. You can generalize this with std::function<>.

std::function<T(Ts...)>

Which generalizes the callable construct.


Iterator producing unique random numbers in a specified range

Looks pretty reasonable. Just a few minor issues:

    public NonRepeatingRandom(int max) {

That's fine for general-purpose use, but you should consider adding a constructor which takes (int, Random) for testing purposes.

    @Override
    public boolean hasNext() {
        return ( unused.size() > 0 );
    }

I generally recommend favouring isEmpty() over size() == 0. For many collections isEmpty() just calls size(), but for some it is much more efficient, so it's a good habit to always use isEmpty().

        int idx = random.nextInt(size);
        int result = unused.get(idx);
        unused.remove(idx);

This is the biggest problem, although for your typical use case it might be relatively minor because it doesn't sound like this iterator is going to be a bottleneck.

Removing a random element from a list takes \$O(n)\$ time. But since you don't care about the order of the elements in the list, you could copy the last element to position idx and then delete the last element in \$O(1)\$ time.


Manipulate urls with regular expressions instead of the slip approach

You seek to:

validate the url as coming from your site domain, then
replace the 3rd and 4th directories/topics with a single/new directory/topic.

This is a simple matter of preserving the substrings that you want to keep as "capture groups" and writing the new replace substring between the two capture groups.

In my demo, the new topic will be FOO.  I'm using negated character classes to match the directory names -- this is relatively "loose" validation.  If you require a tighter validation rule, see the 2nd snippet.  Click on Run code snippet below to see the resultant output.

const regex = /^((?:https?:\/\/)(?:w{3}\.)?my-site\.com\/(?:[^/]+\/){2})[^/]+\/[^/]+(\/[^/]+)$/;
      url = 'http://www.my-site.com/topic1/Topic2/topic3/topic4/слизень',
      replacement = '$1FOO$2';

document.write(url.replace(regex, replacement));

To tighten the validation beyond non-slashes as directory substrings AND extend the characters classes to include multibyte letters, you will need to manually expand the character classes to include the letters that you expect to qualify.  Please have a read of Regular expression with the cyrillic alphabet.

const regex = /^((?:https?:\/\/)(?:w{3}\.)?my-site\.com\/(?:[À-žа-яa-z\d-]+\/){2})[À-žа-яa-z\d-]+\/[À-žа-яa-z\d-]+(\/[À-žа-яa-z\d-]+)$/i;
      url = 'http://www.my-site.com/Schnecke/to-pic2/topic3/naaktslak/слизень',
      replacement = '$1FOO$2';

document.write(url.replace(regex, replacement));


Here's one approach:

SHAPE_RENDERER = {}

def renders(shape):
    def inner(function):
        SHAPE_RENDERER[shape] = function
        return function
    return inner

@renders(Circle)
def draw_circle(circle, view):
    ...

@renders(Triangle)
def draw_triangle(triangle, view):
    ....

def render_shape(shape, view):
    SHAPE_RENDERER[shape.__class__](shape, view)


Removal of jQuery from script to auto-apply coupons from a link

As it stands, in most ways the code is now much better than the original. Your senior dev is absolutely correct in wanting to use CSS for the modal size. Despite this, there are a few suggestions I would make.

Instead of using window.onload use window.addEventListener("load", function(){});. If window.onload is used, then the function activating the modal could be overwritten by accident in the future.

There is no point in including Method in closeMethod. I'm sure that Method was added when the dev realized that just naming the function close hid the window.close function. closeModal would be a more descriptive name that also avoids this problem.

Is there any reason that both load and DOMContentLoaded events are listened for? These events should fire incredibly close to each other, and the code can likely be combined into a single initialization method to reduce complexity.

The ID of the popup-wrapper is overdefined. More than one method has it hardcoded in. If it were to be changed, it would be fairly easy to forget to change one or more occurrences. To fix this, it might be best to wrap everything in an immediately invoked function expression (IIFE) and pass the ID in. Using an IIFE also makes it possible to trivially avoid any troubles with global scope.

Instead of appending to className, use the classList API as this also makes removing the modal-overlay_visible class trivial. It also might make it possible to remove the modal-overlay_hidden class.

The DOMready function is exposed to the global scope. This isn't a huge issue on small pages, but should still be avoided to increase maintainability.

Lastly, consistency is a good thing. A style guide can make it easier to read code by ensuring everyone sticks to using double quotes (or single quotes) and uses the same CSS class patterns (I expected js-modal-close to be modal-overlay_close)

I could provide several different ways of writing this module. Which way is best heavily depends on your situation and is a judgement I can't make.


Long arithmetic addition implemented in functional style

Input validation

The function will happily return non-sense result when an argument contains not only digits.
Unless you are absolutely certain that this function is used in a safe context,
it would be good to validate the inputs.

Going even further,
I would create a validate function that returns a number or else throws an exception, and call it after splitting:

  lnum.split('').map(validate).reverse(),
  rnum.split('').map(validate).reverse()

This way the summing step will not need anymore the Number conversions,
 a bit simpler:

  var sum = (left || 0) + (right || 0) + rem;

Cleverness

I find this clever, but hacky:

rem: ~~(sum/ 10)

I suggest to just spell out the intention nicely:

rem: sum > 9 ? 1 : 0

On the other hand, instead of this:

if (rem !== 0) {

Since the value of rem is guaranteed to be either 0 or 1,
I think it's totally fine to be lazy and rely on the truthiness:

if (rem) {


Are these good examples of functions that do one thing only or am I getting a little carried away?

I think you have definitely taken it in the right direction. Excellent work!

I don't see any compelling reason to break AssembleDailySheetName() down any further.

My only complaint is that I don't really like the separation of adding and naming the sheets. I see both steps as being part of creating a sheet. I think it would be nice to set the name of the sheet immediately after adding it (in the same function). That will likely eliminate some code as well. I suspect Sheets.Add may return the new sheet. If that's the case, there would be no need to look up the sheet by index to name it.


If the first argument to your script contains a space, then you get an error message:

$ ./cr32076.sh "my repository"
./cr32076.sh: line 6: [: my: binary operator expected

To avoid this, put quotes around the variable $1, like this:

if [ -k "$1" ]; then

The man page for [ says:

-k file       True if file exists and its sticky bit is set.

is this really what you mean? It seems more likely that you want the -z option:

-z string     True if the length of string is zero.

You remember the current directory in a variable:

currPath=$(pwd)

and then later change to it:

cd $currPath

but this will go wrong if the current directory has a space in its name:

$ pwd
/Users/gdr/some directory
$ currPath=$(pwd)
$ cd $currPath
bash: cd: /Users/gdr/some: No such file or directory

To avoid this, put quotes around the variable, like this:

cd "$currPath"

If you want to change directory temporarily and change back again, then instead of writing

currPath=$(pwd)   # remember old directory
cd "$SVN_PATH"    # change to new directory
# do some stuff
cd "$currPath"    # go back to old directory

you can use a subshell:

(
    cd "$SVN_PATH"    # change to new directory
    # do some stuff
) # old directory is automatically restored when subshell exits

But in this script, there's no need to change directory back again, because after you go back all you do is echo "Done! ..." and it doesn't matter what directory you do that in.
In fact, there's no need to change directory at all, because instead of

SVN_PATH="/var/lib/svn"
currPath=$(pwd)

cd "$SVN_PATH"
svnadmin create "$1"
chown -R www-data:www-data "$1"
cd "$currPath"

you could write

SVN_PATH="/var/lib/svn/$1"
svnadmin create "$SVN_PATH"
chown -R www-data:www-data "$SVN_PATH"


No, this code isn't reusable.

Currently, you cannot "execute queries" but execute SELECT queries with exactly one or two parameters. What if you need to add a third id? Or a fourth? Or have a query with no parameters?

The easiest way to solve your problem is to just pass your $values array to execute:

public function execute_query( $query, $statement_id, $values )
{
    $statement = $this->database_connection->prepare( $query );
    $statement->execute($values);
    return $statement;
}

But this still doesn't make very much sense. Your function returns a PDO statement, which still has to be processed, so you didn't really gain anything by introducing this method (well, you save one line for every query you write).

You should either get rid of it and use PDO directly (or some alternative such as an ORM), or you should handle all PDO related code inside of this method (make sure that the method actually improves on using just PDO though).

Misc

It is pretty much never a good idea to change the behavior of a function based on some control string (like your db1/db2), as it is difficult to use, it must be properly documented, it can easily lead to bugs, etc. In your case, you could simply get rid of the parameter and ask for the size of $values.
$statement_id is poorly named.
You use the same db1/db2 string for two very different things (one for different database credentials, one for the number of ids. This is very confusing.


Cleaning up a class that contains the object it represents

Yes, your board.board has a code smell, but it is hard to say what to do without knowing Game.

Actually Board#board is an array. I would recommend to add methods to Board that allow you to use the instance of Board instead of Board#board.

Example: To get a row of yor board you can use:

class Board
  ...
  def [](row) #Access to one row
    @board[row]
  end
  def each_row #loop on all rows...
    @board.each{|row| yield row }
  end

end

class Game
  ...
  def is_over?
    @board.each_row{|row|
     row.each{|field| } ##your check
    }
    ...
  end
end


Let's clarify the logic.  The code simplification will follow.  The rules are:

"th" years are those ending in 4, 5, 6, 7, 8, 9, or 0.  Additionally, the 11th, 12th, and 13th centuries are exceptions also ending in "th".
Years ending in 1 are "st" years.
Years ending in 2 are "nd" years.
Years ending in 3 are "rd" years.

Now just translate the above into code:

def which_century(string)
  century  = (string.to_f / 100).ceil
  year     = century % 10
  nth_year = (11..13).include?(century) || !(1..3).include?(year)
  return "#{century}th century" if nth_year
  return "#{century}st century" if year == 1
  return "#{century}nd century" if year == 2
  return "#{century}rd century" if year == 3
end


Show a search input bar depending on which path the user currently is viewing

You could use PHPs in_array() function to test the current route against your required routes:

@php ( $searchRoutes = ['foo', 'bar'] )
@if( in_array(request()->route()->getName(), $searchRoutes))
   @include('partials._search')
@endif

You could define the allowed routes array in your controller and pass this into the blade template.


reinterpret_cast vs bit shifts for extracting 32-bit integers from bytes, with either endianness

You are correct to be concerned about the first method. It generates UB if buf[offset] doesn't happen to be at the right alignment boundary for a 32-bit value.

The second method is the way to go, even if you don't care about portability (but as a bonus, it's portable, except for the use of int32_t).

As mentioned by @AJNeufeld you need to fix up your out-of-bound checks. Once that's done, you could simplify the function quite a bit by using std::swap(). For example:

if (bswap) {
    swap(buf[offset    ], buf[offset + 3]);
    swap(buf[offset + 1], buf[offset + 2]);
}
return (buf[offset + 3] << 24) | (buf[offset + 2] << 16) |
    (buf[offset + 1] << 8) | buf[offset];

That's even pretty easy to generalize to any size with a couple of loops (that will almost certainly be unrolled).

EDIT: As @hoffmale notes in the comments, the return line is still possibly UB. The reason it technical.

auto b = int8_t{};
auto r = b << 8;

The above code is legal because in every arithmetic operation, signed chars and shorts are always promoted to int. So b is promoted to int, which must be at least 16 bits, and the shift is cool, and r is int.

The problems arise when you shift by more than 8 bits. The types will always be promoted to int, but int is only guaranteed to be 16 bits. That means if you did:

auto r = b << 16; // or 24

now you have a problem.

To solve it, you need to make sure the value being shifted is at least 32 bits before the shift:

auto r = uint_fast32_t{b} << 16; // or 24

This works portably.

So you'd need to add this cast before each shift in the return line.

But a better way to handle this - one that scales - is to use a loop:

auto ret = int32_t{};
for (auto i = 0; i < 4; ++i)
{
    ret << 8;
    ret |= buf[offset + (3 - i)];
}

or even:

auto ret = int32_t{};
for (auto i = 0; i < 4; ++i)
{
    ret << 8;
    if (bswap)
        ret |= buf[offset + i];
    else
        ret |= buf[offset + (3 - i)];
}

and now you don't have to worry about promotions. Any decent optimizing compiler will hoist the invariant conditional and offset out of the loop and unroll the loop (and eliminate the unnecessary shift). And you can even template the loop on the size and reuse it.

Shifting and OR-ing is the only portable way to get the little-endian data in buf into an integer for all machines.

@juhist describes another option: using memcpy(). That's not a portable solution for a number of technical reasons. First, you'll get different behaviour depending on the endianness of the machine. More technically, the machine may not always store integers the way you expect, and I'm not referring to endianness by that. You're dealing with signed values, but the type of signedness of the data may not be the same as the machine (for example, the data may be twos-complement, the machine may be signed magnitude). There may be padding bits and other weirdness going on that ends up meaning that a 32 bit value of 0xFFFFFFFF may not necessarily be represented in memory as 4 bytes of 0xFF. Or if your input data is "0x00 0x00 0x00 0xA0" which if memcpy()ed on a little endian machine will give you 0xA0000000 (that's its value, not its memory representation), which you assume is −2147483648... but that's assuming bit 31 is the sign bit, which is not necessarily true. Could be bit 0, for example, meaning this value is actually 1342177280. (Granted, if your data has a sign bit, you really need to handle it specifically in any case. That is, you'd need to calculate the high byte as something like buf[offset + 3] & 0x7Fu, and multiply the result by −1 if buf[offset + 3] & 0x80u... or you could dump the whole thing into an unsigned value, and then deal with the sign bit. But the point about the sign bit not being where you expect it still stands: 0x01 0x00 0x00 0x00, if memcpy()ed on a little-endian machine, could produce −2147483648 rather than 1... or anything else really.)

If performance really matters - and, I'll be blunt, if you're using this part of a serialization routine, it almost certainly doesn't; whatever time you spend decoding integers is going to be dwarfed by the I/O - you could write system-specific code. For example, if your system is little-endian, and you know the representation is the same as what's in the buffer, you could just memcpy(). If it's big-endian, maybe memcpy() and a swap intrinsic, or a loop that's basically reverse memcpy() (create the integer, then copy the bytes in reverse order). If it's other-endian or non-twos-complement or has some other quirck... well, you'd know how to deal with that in that case.

The bottom line is that shifting and OR-ing is the only portable solution (and you'd need to handle the sign bit properly). If you don't care about portability and you want speed, well, then the "right" answer depends entirely on 1) the data representation, and 2) your machine.


You shouldn't try to think of all the bad things that could be in the query, you'll never think of them all.

As it stands, your replacement is useless (as some of your commentors have noted). You can have any text you want inside of the string, its characters which might cause the string to be escaped which are a problem.

mysql_real_escape_string does everything you need. You don't need to implement your own function. Better yet use prepared statements.


Functions

Right now, write_html manages both parsing and writing to a file. Separate this function into two functions, perhaps parse_data and write_data.

String Formatting

This

s = "
" + line + "
"
e.write("" + sequence_1 + '	' + '\n')

can be written like this

s = f"
{line}>
"
e.write(f"{sequence_1}	\n")

The f"" allows you to directly implement variables into your strings.

Simplification

This

elif line.startswith('# Gaps:'):
    line = line.split()
    gaps = line[2]

can be written like this

elif line.startswith('# Gaps:'):
    gaps = line.split()[2]

The same with these two:

if line.startswith('# 1:'):
    sequence_1 = line.split()[2]
elif line.startswith('# 2:'):
    sequence_2 = line.split()[2]

Variable Assignments

This

sequence_1 = ''
sequence_2 = ''
identity = ''
similarity = ''
gaps = ''
html_string = ''

can be written like this

sequence_1, sequence_2, identity, gaps, similarity, html_string = '', '', '', '', '', ''

Type Hints

You can use type hints to make it clear what is being accepted as parameters, and what is being returned by the function.

From this

def write_html(result):

to this

def write_html(result: str) -> None:

Docstrings

You should include a docstring at the beginning of every function, method, class, and module you write. This will allow documentation to identify what these are supposed to do.

def write_html(result: str) -> None:
    """
    (Description about this method here)
    """
    ... code here ...


Including IO in a benchmark is no good. I tried some different benchmarks on quick-bench and the results were different: the versions with Expensive Functions (log, exp, etc) were much slower. Looking at the assembly, there was no "cheating" such as vectorizing the benchmark loop with the plain division - on the other hand, maybe that wouldn't be cheating, but a realistic representation of how it may work out in real situations. So you could even say that the division is likely to be better than this result shows in many (but not all) situations.
Such results do depend on the specific micro-architecture though. As a specific example, divss on Intel Haswell and before had less than half the throughput than on Intel Broadwell and later. log and exp can be implemented without division, so the relative cost will be different on different processors. That may also explain part of the differences we observed, but that does not take away that benchmarks should not include significant sources of overhead that aren't the subject of the benchmark.
On your architecture (and many others) there is a special hardware-accelerated approximate reciprocal. Indeed on some architectures, division is not a primitive at all and can only be implemented in terms of such an approximate reciprocal (that's tricky). For x86, you can write this, for a quite accurate but not perfect reciprocal:
float reciprocal(float y)
{
    float r = _mm_cvtss_f32(_mm_rcp_ss(_mm_set_ss(y)));
    r = r * (2 - r * y);
    return r;
}

The Newton-Raphson step is optional if you can accept a reduced precision, with a relative error of up to \$1.5 \cdot 2^{-12}\$.
Note than all the benchmarks that I linked before are for throughput, if you're in a situation where latency is important, an approximate reciprocal followed by a Newton-Raphson step is not actually good. Pentium4 may have been an exception to that, since it had a much slower division, but Pentium4 is not very relevant today.


Separating paging, sorting and filtering

For my money it would only be worthwhile having separate classes for Sorting/Filtering/Pagination if they were generic and able to work on multiple entity types. Even then they'd more likely be helper classes than a part of the top-level application interface.

If the current requirement of your application is purely to do what GetVehicleMakesWithPaginationAsync does then the proposed split into 3 classes doesn't strike me as justified. I'm more concerned about the nature/names of the parameters being passed.

Why not make "sort" a boolean flag called "sortDescending"? And I'd rename search to namePrefix or something that makes it clearer.

Lastly - is the AsQueryable() really needed?


I'm not 100% sure this works in Ruby, but can you use constants with string interpolation? This string is repeated a lot. I doubt it will ever change, but if it does, it would be nice to only have to change it once.

"#{'  ' * indent_level}data[pointer]"

Could be #{'  ' * indent_level}#{DATA}.


Delete node from singly linked list with tail pointer in C

You have not specified the behavior of your list, which makes it hard for us to reason about it, and makes it hard for you to reason about it. Because this is a module about a data structure, it's a good fit for Design-by-Contract, which I recommend you read about.

Fundamentally, in DbC, each method or function has a precondition which must be met just prior to executing the code, a postcondition which must be met after executing the code, and an invariant which must be true at the start and the end of execution, as well as being true when other public methods or functions are called from within the code.

Consider your lrsll_delete(list, data) operation: the precondition is that a node with key data may or may not be present in the list. The postcondition is that the first such node will be removed from the list. (It's not clear whether you want to handle multiple nodes with the same key: do you?)

You don't specify an invariant, but I'd suggest the invariant might be that list->head points to the first node in the list, or is NULL for an empty list, while list->tail points to the last node in the list, or is NULL for an empty list, and each node's ->next field points to the next node in the list, or is NULL when the node is at the end of the list.

You should consider documenting these three conditions. The invariant is always true - you can document it once at the top of the module. You might even document it in code, in a private helper function you can call for debugging purposes: _check_invariant(list).

The pre- and post-conditions will vary from function to function. I suggest documenting them in a block comment.

With that out of the way, let's consider your code:

lrsll_node *lrsll_delete(lrsll_list **list, char *data) {

Right off the bat, I want to ask why you're passing a lrsll_list** pointer? The "double pointer" in question is the lrsll_node**, not _list. Since the _list structure is encapsulating the head and tail pointers, and is not a node itself, I'll recommend that you just use a single level of pointer for this.

I'd also suggest that you typedef the key type. Make it a lrsll_key_t or something, not a char *.

    lrsll_node **node = &(*list)->head;

This can be just &list->head, if you use only one level of pointer to the list structure.

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

This is you searching for a matching key in the list. I'll bet you have this same code in other places, like a "find" and maybe an "insert" (if keys are required to be unique). You should consider either defining a macro or a private (internal) function to do this for you.

    if (*node == NULL)
        return NULL;

Not found so return null. This is legit. Moving on:

    lrsll_node *deleted = *node;

Save a pointer to the deleted node. Okay.

    *node = deleted->next;

Update the pointer to that node. Note: It's important to note that there are two possible structures being pointed to by node. In the first case, node is initialized to point to list->head, so node might be pointing into a struct lrsll_list. After the first node, you update with node = &(*node)->next which will be a pointer to a struct lrsll_node. So the node double-pointer points into two possible kinds of struct. That's awkward.

    //is there a way to get rid of this conditional check
    //using pointers in a more intelligent manner?
    if (deleted == (*list)->tail) {
        (*list)->tail = NULL;
    }

To answer your question, there's no good way that I know of - nor even a bad way - to get an update to the list->tail pointer without either destroying it and rebuilding it (by using the tail as your temporary, and then scanning-to-end once you're done), or comparing it and updating it if needed.

Suppose you use tail as some kind of previous node pointer? Well, that's the situation you are determined to avoid with the whole "Linus' double pointer" scenario. So I'll assume you don't want to do that.

Then how can you safely update the tail pointer? Well, consider this:

head -> node1 -> null
tail ---^

In the case where the list contains only one element, what happens if you delete it?

node -> &head -> node1

First, node points to &head. Then *node->data matches, because I said so. So you delete the node by setting *node = deleted->next (which is NULL in this case). So now you have:

node -> &head -> NULL
         tail -> node1

So in this case, your conditional code is correct:

    if (deleted == list->tail)
        list->tail = NULL;

And produces this result:

node -> &head -> NULL
         tail -> NULL

Deleting the 1 node in a 1-node list produces an empty list, which is stored as shown.

But now consider a two node list where the last node is deleted:

head -> node1 -> node2 -> NULL
tail ------------^

After searching, you have:

node -> &(node1->next) -> node2

You set *node = (*node)->next which is NULL, and get:

head -> node1 -> NULL
node ---^.next // node points to &node1.next
tail -> node2

So you run your test:

    if (deleted == list->tail)
        list->tail = NULL;

Which passes, because you did delete the last node in the chain, but now you get:

head -> node1 -> NULL
tail -> NULL

And this is wrong. Tail should point to node1, not to NULL.

How can you fix this? By adding another condition: when updating the tail pointer, check to see if the node pointer is still pointing to &list->head. If so, then go ahead and null it out because you know you have a 1-element list being shortened to an empty list. But if node points to some other location, and you're deleting the tail element, then you can set tail to point to the address of the struct containing the next pointer that is pointed to by node. (Say that five times fast!)

Fortunately, the next pointer is the first element in the struct, so in C you can assume that the two addresses are the same, and just cast one type to the other. (In C++, with a vtable, the addresses wouldn't be the same. In C with any other field at the top of the struct, the addresses wouldn't be the same. That's what the offsetof macro is for! You could subtract the offset, but ... c'mon! This is C! Just hard-code the 0 and move on...)

Something like this:

    if (deleted == list->tail) {
        list->tail = (node == &list->head) ? NULL : (lrsll_node*)node;
    }

Finally:

    return deleted;
};

You don't need that last semi-colon.


Group similar objects into array of arrays

First, using a constructor is overkill. Your Todos don't use inheritance nor share methods (the method is created per instance, thus not shared). You can simply have a factory (a function that returns an object). isSimilar could be just a helper function that has nothing to do with Todo.

function createTodo(value){
  return {
    value: value,
  };
}

var _data = [
  createTodo("hello"),
  createTodo("world"),
  createTodo("foo"),
  createTodo("bar"),
  createTodo("hello")
];

So now, you have a list of objects. You can then use reduce and build up a hash of objects with the value as their key, and an array as the value.

var todosByValue = _data.reduce(function(hash, todo){
  if(!hash.hasOwnProperty(todo.value)) hash[todo.value] = [];
  hash[todo.value].push(todo);
  return hash;
}, {});

// now we have something like:
{
  hello: [{ value: 'hello' }, { value: 'hello' }],
  world: [{ value: 'world' }],
  ...
}

All you need to do is just pull the values out to an array using Object.keys and array.map.

var groupedByTodo = Object.keys(todosByValue).map(function(key){
  return todosByValue[key];
});

In all, it should simply look like this:

function createTodo(value){
  return {
    value: value,
  };
}

var _data = [
  createTodo("hello"),
  createTodo("world"),
  createTodo("foo"),
  createTodo("bar"),
  createTodo("hello")
];

var todosByValue = _data.reduce(function(hash, todo){
  if(!hash.hasOwnProperty(todo.value)) hash[todo.value] = [];
  hash[todo.value].push(todo);
  return hash;
}, {});

var groupedByTodo = Object.keys(todosByValue).map(function(key){
  return todosByValue[key];
});


Creating a real unit test in Karma for Angular code

Since

  router object is a mock, and
  the fact that it calls some method - without checking its result

You have a unit test, more specifically a whitebox test, as opposed to a blackbox test that tests the output of some method.

For it to become an integration test, you would have use a router instead of a mock.


Iterating through a range using lodash/AngularJS and saving data

Please do not make separate calls (Http requests) for saving each container,as this will affect the web application performance. Instead batch the calls ( 5 calls at one time). Store them in an array and make a single call

_.each($scope.batchFields, function(batch) {
  var containersList = [];
  _.each(_.range(batch.batchesQuantity, 0, -1), function(val, i) {

    // store them in the array
    containersList.push(new Container($scope.batchFields));
  });

  $http.post('saveContainers', containersList).then(function(response) {
    $notify.success('purchase.order.edit.created');
    if ($scope.$close) {
      $scope.$close();
    }
  }, function(errorResponse) {
    $scope.errors = errorResponse.data.message;
  });

});


Prompting the user to enter Name value pairs and then printing it out using a Name_value class

Yes, global variables really are that bad. Do try to avoid them.
Personally I find it easier to read if you add some vertical space to your member initializer list like so:

Foo(int a, int b)
    : a{a}
    , b{b}
{}

Don't omit braces as that can lead to hard to find bugs (For example Apple's goto fail bug would have been much easier to spot if braces had been used.
Prefer prefix over postfix
It's okay to use whitespace more leniently

// This might be debatable
pairs.push_back(Name_value(x,y));

// But this just looks strange
catch (exception&e)

Considering that you add a space everywhere else in the code you might as well add one in those cases.
Your naming could be improved. Namely put_in, x and y are not the greatest variable names. Also why is Name capitalized? Why names and scores when they only hold one name/score? Remember that variable names should always reflect intent as your goal is to write self-documenting code.
This code is confusing

pairs = put_in(names, scores); //put the values into the vector list

First get rid of that comment. Second, why are you returning the vector after you already added the values to it? Why even use a function for this in the first place? Simply doing:

pairs.push_back(Name_value(names, scores));

Has the same effect.
While you didn't write it, you still use using namespace std included via the header file provided by Bjarne(?).
Just a reminder that this is considered bad
but hopefully it will be explained further into the book as well.
I'm no expert on exceptions but the way you use them seems wonky, maybe someone else can chime in here.


Suppressing errors

  Edit

Error suppression should be avoided if possible as it doesn't just suppress the error that you are trying to stop, but will also suppress errors that you didn't predict would ever occur. This will make debugging a nightmare.

Other then that, looks nice.


Fill upper triangular matrix from a list

Here are a few methods for your consideration and feedback.

This one uses the core of my "Dynamic Partition" function.  It is the fastest method I know for this problem.  Also, perhaps refactoring the code like this makes it more intelligible.

dynP[l_, p_] :=
 MapThread[l[[# ;; #2]] &, {{0}~Join~Most@# + 1, #} &@Accumulate@p]

#~PadRight~s & /@ {{}} ~Join~ dynP[elems, Range[s-1]]

This one is slightly shorter, using a different way to construct the indices, but also slightly slower, and perhaps less transparent.

#~PadRight~s & /@
 Prepend[
   elems~Take~# & /@
     Array[{1 + # (# - 1)/2, # (# + 1)/2} &, s - 1],
   {}
 ]

This one is terse, but slow.  Legibility is debatable.

SparseArray[Join @@ Table[{i, j}, {i, s}, {j, i - 1}] -> elems, s] // MatrixForm

Here is one I just came up with, and I am quite pleased with it.  I think it may be more understandable than most of the ones above.

Take[FoldList[RotateLeft, elems, Range[0, s - 1]] ~LowerTriangularize~ -1, All, s + 1]


The fact that you're parsing BASH means you're probably not worried about portability, which means you probably don't need the path module since the directory separator will always be /. So, you can replace p.join(__dirname, 'localEnv.sh') with __dirname+'/localEnv.sh'
There's a module for reading stuff line by line already, no need to home-roll it.
This is a better regex because it takes escaped quotes into account: "(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*' see here.

require('readline').createInterface({
  input: require('fs').createReadStream(__dirname+'/localEnv.sh')
}).on('line', function (line) {
  var tokens = line.split(' ')
  if (tokens[0] === 'export') {
    var [ name, value ] = tokens[1].split('=')
    process.env[name] = value.match(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/)[1]
  }
});


Combining a list of realtime responses with a list of static responses

You are constructing a list out of realtimeResponses.

You then iterate over each item in staticResponses, and for each static response, you (slowly) look to see if that key is in your list of realtimeResponses.

Right there is your room for improvement: a list is not the professional data structure of choice for testing if an item is in a collection. For that, you want either a set or a dict.

In your case, you have extra data in your realtimeResponses, but you don't use it. So set seems to be the right choice: put your realtimeResponses key values into a set, and then you can just use code like:

    realKeys = {rtr['key'] for rtr in realtimeResponses}

    for response in staticResponses:
        if response['key'] in realKeys:
            predictionArray.append(response)

Of course, once you have a for and an if in a tight loop, you can replace it with a list comprehension:

predictionArray += [resp for resp in staticResponses if resp['key'] in realKeys]


Problem statement linked above says 'Page numbers will always be in the range 1 to 100', I don't understand why you need to keep size = 1000, size = 101 should work just fine. Correct me if I am missing something here.

I modified your code here

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>

using namespace std;

#define INF 1e9
#define MAX_SIZE 100

int graph[MAX_SIZE + 1][MAX_SIZE + 1], n, mapping[MAX_SIZE + 1];
int main() {
    int u, v, flag=0, testCase = 1;
    while(scanf("%d%d", &u, &v), u||v){
        for(int i = 1; i <= MAX_SIZE; i++) {
            for(int j = 1; j <= MAX_SIZE; j++) {
                graph[i][j] = INF;
            }
            graph[i][i] = 0;
        }
        int n = 0;
        memset (mapping, 0, sizeof(mapping));
        do {
            if (!mapping[u])
                mapping[u] = ++n;
            if (!mapping[v])
                mapping[v] = ++n;
            graph[mapping[u]][mapping[v]] = 1;
        } while(scanf("%d%d", &u, &v), u||v);

        for(int k = 1; k <= n; k++)
            for(int i = 1; i <= n; i++)
                for(int j = 1; j <= n; j++)
                    graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]);

        double s = 0.0;
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)
                s += graph[i][j];
        //cout<<s<<endl;
        s /= (double)n*(n-1);
        //cout<<s<<endl;
        printf("Case %d: average length between pages = %.3lf clicks\n",testCase++,s);
    }
    return 0;
}


PHP Memento design pattern implementation

After a bit of experimenting, I get there

I'm also a self-taught programmer, but I've been at if for 33 years. I've seen a lot of things, but I never heard of a Memento design pattern. So, eventhough it is quite clear from your explanation and code what it is, the first thing to to is to look up what it exactly is. Here for instance:

https://sourcemaking.com/design_patterns/memento

There are just too many fancy names for these things, but I understand what they get at. I think we can also agree that you've tried to make the absolute simplest implementation of this design pattern; Just keeping track of one string, nothing more.

Let us discuss the code, starting from the beginning, which is your last piece of source code.

Your CodeBase class, the originator, internally needs a Repository class, the memento, to keep track of its state. Why do you declare it outside the CodeBase class and pretent it a argument to the construction of it? It is not. So the constructor of CodeBase should be:

public function __construct()
{
    $this->repository = new Repository();
}

Now declaring repository private actually makes sense.

Within CodeBase you have a method called getNewCode(). It works by removing the committed code from all the code in the CodeBase class. Moreso, you use this to commit new code with commitToRepository(). That just doesn't feel right. The state of your originator is basically a single string. You would want to remember that state, so you should commit the whole string, not a part of it. Remember that currently you only append the code strings at the end, but that's probably not how it will stay. If you edit the code string in the middle your method will not work anymore. That's why I get a bad feeling looking at that code. So CodeBase should look like this:

class CodeBase
{
    private $repository;
    private $code = '';

    public function __construct()
    {
        $this->repository = new Repository();
    }

    public function getCode()
    {
        return $this->code;
    }

    public function setCode($code)
    {
        return $this->code = $code;
    }

    public function appendCode($code)
    {
        $this->newCode = $this->newCode . $code;
    }

    public function commitCode()
    {
        $this->repository->commit($this->code);
    }
}

Which looks a lot cleaner. Yes, I have ommitted the roll-back method. More on that later. The point is that you can extend CodeBase to be a full fletched code editor and all these methods will still work.

I will agree that it does look as if we just shifted the problem to the Repository class, and you might be right. But the design pattern is about externalizing the object's internal state, and that's what I've done.

Here's is how I would define the Repository class:

class Repository
{
    private $commits = [];

    public function commit($state)
    {
        $this->commits[], $state);
    }

    public function commitCount()
    {
      return sizeof($this->commits);
    }

    public function rollBack($steps,$permanent = TRUE)
    {
       if ($stepsBack <= 0) throw new Exception('Invalid step back value');
       $commitCount = $this->commitCount();
       if ($steps > $commitCount)) return '';
       $commitIndex = $commitCount-$steps;
       $state       = $this->commits[$commitIndex];
       if ($permanent) $this->commits = array_slice($this->commits, 0, $commitIndex);
       return $state;
    }
}

It's a very basic implementation, mainly to show you the rollBack() method and what's going on with the externalized state of CodeBase. I've left out the Commit class for simplicity. So, yes, I store the complete code on every commit. Not efficient, I know, but necessary. The rollBack() method is what is important here. It normally does a real roll back, in other words, it is permanent. So a roll back method in the CodeBase class would look like this:

public function rollBackCode($steps)
{
   $this->repository->rollBack($steps);
}

Nevertheless this would not be the way I would inplement the Memento Design Pattern. The main thing that I don't like is that the Repository is part of the state of the CodeBase, which is your originator. Moreso, you only use one Memento object to store everything, whereas I think it would be more logical to have one of those objects per state you want to remember. This leads me to the following code:

class CodeState // memento
{
    private $code;

    function __construct(CodeBase $codeBase)
    {
      $this->setCode($codeBase);
    }

    public function getCode(CodeBase $codeBase)
    {
      $codeBase->setCode($this->code);
    }

    public function setCode(CodeBase $codeBase)
    {
      $this->code = $codeBase->getCode();
    }

}

And:

class CodeBase // orginator
{
    private $code;

    function __construct($code = '')
    {
      $this->setCode($code);
    }

    public function getCode()
    {
      return $this->code;
    }

    public function setCode($code)
    {
      $this->code = $code;
    }

    public function appendCode($code)
    {
      $this->code .= $code;
    }
}

And that is all that is needed. I still have to show how the 'caretaker' can use these two classes.

$commits  = array();              // I cannot use '[]' yet
$codeBase = new CodeBase();

$codeBase->appendCode('First day code');
$codeBase->appendCode('Second day code');
$commits[1] = new CodeState($codeBase);
$codeBase->appendCode('Third day code');
$commits[2] = new CodeState($codeBase);

$commits[1]->getCode($codeBase);  // Roll back to the first commit
echo $codeBase->getCode().'
'; // "First day code Second day code"

$commits[2]->getCode($codeBase);  // Roll back to the second commit
echo $codeBase->getCode().'
'; // "First day code Second day code Third day code"

Now this is much cleaner. You might not completely agree with the names of the methods, but I think you can see my basic idea here. You can add in timestamps in the CodeState class and roll back to any commit. There are no akward array or string manipulations.

Let's be clear, there's not much wrong with your implementation, or my first attemp, it's just that they don't comply with the design pattern you were trying to follow. All three ways work. Purists would say that only the last one is correct and the other two are feeble attempts at writing code by amateurs. So be it. Just write the code you are happy with. Following exact design patterns can be useful but it should never hinder you from creating code that does something useful.

Having said all that, I would also like to refer you to this blog posting:

https://blog.svpino.com/2015/04/22/the-thing-with-code-clarity-you-cant-be-proud-of-something-I-cant-read

Yes, this post has become too long, sorry for that.


Handle database validation (exists, unique constraint, etc)

With approach A) you may run in a concurrency problem.
For example process A and process B want to write a new entry. Both load the data from the database and check if their new entry would be valid. Both decide "YES, valid".
Now process A writes the new entry, and then process B tries to write. But A already changed the database, therefor the validation in B was executed on obsolete data.
Be aware that node will execute things concurrently, because as soon as a "process" (task) has some waiting time, another process (task) will be executed until that one is finished or also waiting for something.
With version B) this problem gets (for most db´s) fixed. On the other side, now your business logic is scattered over multiple systems, which makes maintenance harder.
--> As always, there is no YES or NO but a "depends on your context" :-)
About the bonus question:
If your application uses the same entities as the DB, then your whole application (from top to bottom) has a dependency to your database schema.
As a result, a change in your DB then has to be followed by a lot of changes in your application.  If you do the mapping in the service layer (thats where i would expect the business logic), then all changes run at least until there.
Therefor i would "map" the data in the data access layer into the entities i use in my application. Yep, in many cases the entites will look similar, but it decouples my application from my database. And my business logic will not know anything about the format that is used when data gets stored.
By the way, some people use their entities over the whole application, some create new entities for each layer and the data get maped a lot. Both approaches have their reason, personaly i work with a entity set for the whole application.
Just a few thoughts. Pick those that make sense to you and skip the rest. :-)
warm regards


I think this would a great situation to use itertools.groupby in.

datekey = lambda x: x.date
comments.sort(key=datekey)
date_comments = [list(group) for date, group in itertools.groupby(comments, datekey)]

This of course groups all your comments, not only the ones in your date range. I'd use filter to skip the ones out of your range if you can't make use of the extra days comments.


In ES6, when you have a variable that's going to be used as a property of an object, you can use the same variable name as the property so as to use shorthand syntax, if you want:
const data = await readStream(filteredStream); //Reads in a sample of data and closes the connection.
return { data };

You do:
filteredStream = streamConnect();

You are assigning to an outer variable named filteredStream. Do you declare and use filteredStream elsewhere? If not, then this is a bug - you're either implicitly creating a property on the global object, or (if you enable strict mode), an error will be thrown. Always declare variables before using them. You might have wanted to do:
async function readFilteredStream() {
    const filteredStream = streamConnect(); //Connects to API
    const data = await readStream(filteredStream); //Reads in a sample of data and closes the connection.
    return { data };
}

The respondWithSamples function doesn't do anything useful. It calls readFilteredStream and returns it. It would be easier and make more sense to just use readFilteredStream instead, and remove respondWithSamples - all you're doing is creating another wrapper around the Promise, one which will be resolved wherever the Promise is unwrapped.


(1). You can create an exntession method to check that item is within the range.

(2). I'd use Count instead of Sum because you just count the number of days in specified interval. It's more natural.

(3). I'd check performance of this query and try to cache result of this join and/or grouping by using some method that requires eager evaluation. ToList() for example. It can help with a lot of traverals of every group in Sum()/Count() methods.

(4). Note for additional information. Even if Sum() in Linq To SQL is a lot faster than Count() you still can have MyCount() implemented as Sum() inside. This will allow you to have a good performance as your senior programmer mentioned and hide this "? 1 : 0" conidition.

 var tempQuery = from prop in propList
                                       join book in booking on prop.PropertyId equals book.PropertyId into j
                                       from book in j.DefaultIfEmpty()
                                       group book by new { prop.PropertyId, prop.PropertyName }.ToList();

 objLeadTimeReportResult = from tempVar in tempQuery
                                 select new LeadTimeReportResult
                                       {
                                           PropertyId = tempVar.Key.PropertyId,
                                           PropertyName = tempVar.Key.PropertyName,
                                           Today = tempQuery.Count(item => (item.WithinRange()),
                                           Days1_2 = tempQuery.Count(item => (item.WithinRange(1,2)),
                                           Days3_6 = tempQuery.Count(item => (item.WithinRange(3,6)),
                                           Days7_10 = tempQuery.Count(item => (item.WithinRange(7,10)),
                                           Days11_15 = tempQuery.Count(item => (item.WithinRange(11,15)),
                                           Days16_30 = tempQuery.Count(item => (item.WithinRange(16,30)),
                                           Days31_45 = tempQuery.Count(item => (item.WithinRange(31,45)),
                                           Days46_60 = tempQuery.Count(item => (item.WithinRange(46,60)),
                                           Days60Plus = tempQuery.Count(item => (item.GreaterThan(60));
}.ToList();


First I must encourage you to follow java conventions. Local variables and methods should be typed in lowerCamelCase. You shouldn't also assign a variable twice if you can avoid it for example you shouldn't do this

List<String> DBpediaClassesArray = new ArrayList<String>();
DBpediaClassesArray = new ArrayList<String>( ClassesRetrieval.getDBpediaClasses());

You could also guive a better name to this variable, the array sufix isn't doing much there, I would prefer dbpediaClasses.
You should do this instead:

List<String> dbpediaClasses= new ArrayList<String>( ClassesRetrieval.getDBpediaClasses());

About your implementation:

You are in the wrong path! It seems to me that you aren't writing code in the simplest way to achieve the expected behaviour. You are creating way to many maps in order to simply find a max number of intersections.

I wouldn't put my hands on fire for it, because I can't test it, but I think that your code is equivalent to this:

public static void getNdMatches() throws IOException{
    List<String> dbpediaClasses = new ArrayList<String>( ClassesRetrieval.getdbpediaClasses());
    List<String> yagoClasses = new ArrayList<String>( ClassesRetrieval.fileToArrayListYago());
    HashMap<String, Set<String>> cachedYagos = new HashMap<String, Set<String>>();
    String yagoClassWithMaxMatches="";

    for(String dbClass:dbpediaClasses){
      int max = 0;
      Set<String> dbClassSet = Sets.newHashSet(GetDBpediaClassInstances(dbClass));
      for(String yagoClass:yagoClasses){
          Set<String> yagoSet = cachedYagos.get(yagoClass);
          if(yagoSet == null){
            yagoSet = Sets.newHashSet(GetYagooClassInstances(yagoClass);
            cachedYagos.put(yagoClass, yagoSet);
          }
          Set<String> IntersectionSet = Sets.intersection(dbClassSet, yagoSet);
          if(IntersectionSet.size() > max){
            max = IntersectionSet.size();
            yagoClassWithMaxMatches = yagoClass
          }
      }
      if(max == 0){
          System.out.println(dbClass+" Corresponds to nothing");
      }else{
          System.out.println(dbClass+" Corresponds to "+ yagoClassWithMaxMatches+" with : "+max);
      }
    }
}


Extracting information and returning specific data

Just a couple suggestions. Since VBScript isn't a strongly typed language, I would do a recommend doing more to make sure that you are making it clear what underlying types you are working on. I prefer an explicit Array call syntax for one, but that's a matter of taste more than anything:

Dim sVariable() = Array("foo","bar")

Also make sure you declare Option Explicit (although I can't tell if it is declared or not here - this appears to be a snippet from a longer piece of code). I would also use (shudder) some sort of variable notation to let you keep track variable types. You apparently used one character Hungarian notation for your object - why not extend this to other types?  Just because VBScript treats everything as a Variant doesn't mean you shouldn't keep track of how you are using them.

Next is to make sure that when you are performing casts, you are doing them explicitly.  The line that jumps out is:

Select Case oNode/100

This is implicitly doing 2 things that are non-obvious - it takes an XmlNode object, calls its default method (.Value), and then casts it to an undefined numeric type to perform division on it. While it's fairly obvious what you are doing in this case, this is a habit that can cause all types of problems in longer scripts and can be hard to figure out when debugging or re-visiting the code in a couple months.

Speaking of debugging, I would also add error handling or trapping of some sort. Obviously trapping errors would be better than the sample below because you can give more meaningful error messages - i.e., invalid NodeID.

Finally, you can simplify this quite a bit by just indexing into the array directly:

On Error Goto Ooops:

Set oNode = XmlDoc.SelectSingleNode("/Record/CelloXml/Integration/Case/Hearing/Court/NodeID")
Dim sAddresses() = Array(
    "Title /n Street Address /n City, State Zip",
    "Title /n Street Address /n City, State Zip",
    "Title /n Street Address /n City, State Zip",
    "Title /n Street Address /n City, State Zip",
    "Title /n Street Address /n City, State Zip",
    "Title /n Street Address /n City, State Zip",
    "Title /n Street Address /n City, State Zip")

Dim iIndex = CInt(oNode.Value) / 100
sReturnData = sAddresses(iIndex - 1)

Ooops:
'Fall-through is OK as long as you check for an error condition here.
If Err.Number <> 0 Then
    sReturnData = vbNullString
    'Do some other useful things.
End If


Image Compression Using the Singular Value Decomposition (SVD) with MATLAB

If you look at the structure of your matrices of singular values S_R, S_G and S_B, you'll see that the non-zero entries lie on the diagonal. You can check only these entries by using diag, removing the need for your S_R>0 condition.

This also means that for find you don't need to supply the second output argument.

To get the first non-zero entries less than sigma_threshold you can hence use

red_j = find(diag(S_R) < sigma_threshold, 1);
green_j = find(diag(S_G) < sigma_threshold, 1);
blue_j = find(diag(S_B) < sigma_threshold, 1);

Bear in mind that this is the first value which should be cut off, not the last value to include, hence you might want to do

red_j = find(diag(S_R) < sigma_threshold, 1) - 1;

or

red_j = find(diag(S_R) >= sigma_threshold, 1, 'last');


Why is everybody using #include<bits/stdc++.h>? It is so hard to include <cstring> to get memset working?
Why do you need <climits>?
Don't use using namespace std;. It's a bad practice.
Static array of ints with size 500000 is likely too big to fit into stack. Use int * arr = new int[max] and delete [] arr; instead.
Using whole integers to store boolean value is just a waste of memory.
It takes 42 seconds to find result. My version (without sieve) takes about real: 0.015s, user: 0.013s.

#include <iostream>

bool isPrime(int num) {
  for (int i = 2; i*i <= num; ++i) {
    if ((num % i) == 0) return false;
  }
  return num > 1;
}

int main() {
  int i = 2;
  for (int primes = 0; ; ++i) {
    if (isPrime(i)) {
      if (++primes == 10001) {
        std::cout << i << "\n";
        break;
      }
    }
  }
}


Let's start with the critical issues:

You are vulnerable to directory attacks, I can get you to include any file by using the ../ to traverse up the directory structure, revealing details on your system:

example.com/index.php?page=../../../../../../../etc/passwd%00

The %00 represents the null byte character (See Null Byte Injection), which will terminate the string (thus ignoring your .php suffix). If I input that, I got all the users and passwords on the server (assuming the PHP user has read access, which it shouldn't, but most likely has).
The $ext variable is redundant, are you by any chance going to stop using .php extension even though you won't stop using PHP? (Because, you know, the code is PHP)
htmlentities is pointless if you aren't placing the target string in HTML. (And even if you were, htmlspecialchars is probably better)
INCLUDES is magic. Immutable global variables (like constants) are still global!
Consistent spacing and line-breaks - If you started with multiline in functions and control structures, stick with it.


Get nth prime number using sieve of Eratosthenes

First a small stylistic review, followed by an alternative algorithm.

You calculate math.sqrt(incEND) many times, just calculate it once outside of the inner while loop. Similarly, you calculate T**2 + (T*l) two to three times per loop. Do it once and save it to a variable.

Python has an official style-guide, PEP8, which recommends using a space in a comma-separated argument list, so use range(incST, incEND) and for k, v in ...

It also recommends using lower_case_with_underscores for variables and function names and using a space before and after the = in variable assignments.

You did not include the import math, which you should do for completeness.

It is probably more efficient to take a prime number generator and count up to the nth prime than keeping a list of all prime numbers in memory.

For this I would use something like this, which I got from a python cookbook site. Alternative algorithms can be found, for example in this Stack Overflow post. It is basically also a Sieve of Eratosthenes, but one where the yielding and the marking-off are interleaved.

def primes():
    '''Yields the sequence of prime numbers via the Sieve of Eratosthenes.'''
    D = {}
    yield 2
    # start counting at 3 and increment by 2
    for q in itertools.count(3, 2):
        p = D.pop(q, None)
        if p is None:
            # q not a key in D, so q is prime, therefore, yield it
            yield q
            # mark q squared as not-prime (with q as first-found prime factor)
            D[q*q] = q
        else:
            # let x <- smallest (N*p)+q which wasn't yet known to be composite
            # we just learned x is composite, with p first-found prime factor,
            # since p is the first-found prime factor of q -- find and mark it
            x = p + q
            while x in D or x % 2 == 0:
                x += p
            D[x] = p

And then finding the nth prime becomes trivial:

def nth_prime(n):
    if n < 1:
        raise ValueError("n must be >= 1 for nth_prime")
    for i, p in enumerate(primes(), 1):
        if i == n:
            return p

This takes about 1 second to find the 200,000th prime (2750159) on my machine.


Let's get the broad picture right first.

Do you know Schlemiel the Painter? No? Well, read about him on Joel's blog.
Don't follow in his footsteps; they are too deep because he always restarts from the beginning.
You might want to take that opportunity to make your code tolerate zero-bytes.

Now, having gotten that off the agenda, some other gross wastefulness: you are allocating memory on the order of twice the files size. But you could easily avoid that: Only read in a line, transform it, write it to the output.

There you have two basic good choices:

Modify the file in-place, as your transformation does not affect how much space each line needs. You don't even need any additional disk-space.
Write the output to a temporary file, and then atomically update it by moving: rewrite existing file so that it gets replaced by new version atomically, only once fully written

Now, about reducing the tedium of repeating the exact same code. That's one of the (few) places where the C preprocessor shines:

#define TRY(cond) if(cond) {} else goto error;
// Use it
#undef TRY

Now lots of other small things:

Curiously, one normally doesn't extract a functions precondition-checking into another function, as then the precondition is no longer there to see, and anyway the boilerplate is normally longer than what was extracted: main → validate_cmdline_args.
Why do you use strchr to find the end of a string, instead of the better-known (and probably more efficient) strlen?
For completeness, casting the second argument, a character-literal, to int is completely useless because it's already an int.
There's no reason to define tmp in reverse_string outside the loop. Actually, wouldn't that be a good place for a for-loop?

void reverse_string(char* str) {
    for(char* end = str + strlen(str) - 1; str > end; ++str, --end) {
        char tmp = *str;
        *str = *end;
        *end = tmp;
    }
}

Strictly speaking, both your original and my replacement for reverse_string are UB if strlen(str) == 0, because that would create a pointer one before the string. That can be fixed by replacing the first 1 with !!*str or adding an if-condition, but it doesn't matter in practice.
It might make sense to output the filename given to your program on error. That might be useful for anyone trying to understand what went wrong, so perror(argv[1]).


There is no indentation except in the function revers_digits(). The indentation within that function is fine, you should correct the rest of the program because it is basically unreadable.
While this may compile in a free online compiler, the code is broken for 2 reasons. The first is that in a one file program such as this one for the C programming language main() should be the last function in the file so that all of the other functions are defined previously. There is a workaround for this using function prototypes.
The second reason the code is broken is that binary_conversion(int number,int value) is declared with 2 variables, but is only called with one (remove value since it doesn't seem to be necessary).


Checking for a date and compare 2 different files

General issues:

1) You should learn how to create and call batch functions so you have re-usable code. See the batch function tutorial at DosTips.com. (Note that the name of the site is misleading. It is primarily a Windows batch site, not DOS.)

2) You put the current date and time in the temporary "time.bat" file, but you never use that data. Instead you use the last modifed timestamp of the newly created file to get the current timestamp. You could have used the dynamic %TIME% and %DATE% "variables" to get the current timestamp without using any temp file. However, there is a much better way to get the current timestamp.

3) Your temporary file has a .bat extension, so it could be executed (with failure of course, since it does not contain valid batch commands). If you create a temp file to house data, then it should have a benign extension. Often times .tmp is used. But again, you really don't need a temp file at all.

4) There is no guarantee that the user has write access to the current directory. When creating temp files, it is best to place them in the "%temp%" folder. This variable is preset for each user to point to a safe place to write temporary data.

5) You use the "time.bat" literal repeatedly, but then you define mktime and use %mktime% in your FOR statement. Why? You should be consistent. Either use the literal everywhere, or better yet, define a variable early on containing the full path to your temp file, and then use that variable consistently when referencing the temp file.

6) You create an excess of variable names. For example, you define TIMESTAMP, only to transfer the value to TIMENOW (or timeXmlCreated), and you never use the value of TIMESTAMP again. You should simply create TIMENOW and timeXmlCreated directly.

7) All of your time / date manipulation is highly dependent on the locale settings of the machine. Your code will break if it is moved to another machine that uses different formats for date and/or time. You should strive for code that is not dependent on locale settings. WMIC DATAFILE, and WMIC OS can be used to get locale indpendent timestamp information.

WMIC timestamps have the format of YYYYMMDDhhmmss.ffffffSzzz

 where:

   YYYY   = gregorian year
   MM     = month
   DD     = day
   hh     = hour in 24 hour format
   mm     = minutes
   ss     = seconds
   ffffff = fractional seconds (microseconds)
   S      = timezone sign: + or -
   zzz    = timezone: minutes difference from UTC

You can use the following to get the current timestamp:

set "localTime="
for /f "skip=1" %%A in (
  'wmic os get localdatetime'
) do if not defined localTime set "localTime=%%A"

You can use the following to get the last modified timestamp of a file. Note that WMIC requires that backslashes be escaped as \\ within the path.

set "fileTime="
for /f "skip=1" %%A in (
  'wmic datafile where "name='c:\\fullPath\\yourFile.ext'" get lastModified'
) do if not defined fileTime set "fileTime=%%A"

8) Ideally, you want to convert the date and time (timestamp) into an integral number so that you can do simple interval arithmetic. One common format is something called unix time - the number of seconds since midnight Coordinated Universal Time (UTC), January 1, 1970 (disregarding leap seconds). Timestamps before January 1, 1970 have negative unix times. I have written a batch function called :UnixTime to compute the unix time for a given timestamp, or for the current time. You can then simply subtract the file unix time from the current unix time, and look for a value > 900 (15 min * 60 sec/min)

Some important notes about the :UnixTime code.

SET /A can access the value of variables directly without expansion.
SET /A can make multiple computations and assignments with one call.
Batch treats numbers prefixed with 0 as octal. So a value of 09 would be an error, since 9 is not an octal digit. That is why the formula inserts prefixes before the substrings, and then uses modulo arithmetic to derive the correct value.

9) Your code to convert the hour into zero padded 24 hour format is flawed. It gives a value of 12 for 12 AM when it should be 00. It is also needlessly wordy.

Here is one concise way to do it:

if %H_NUM% equ 12 set "H_NUM=00"
if %AM_PM% equ PM set /a H_NUM=1%H_NUM%+12-100
if %H_NUM% lss 10 set "H_NUM=0%H_NUM%"

And here is an even more concise way:

set /a "AM=0, PM=12, H_NUM=(1%H_NUM%-100)%%12+%AM_PM%"
if %H_NUM% lss 10 set "H_NUM=0%H_NUM%"

Here is how I would write the code:

@echo off
setlocal

set "file=my.xml"
set "execTime=15"

:: get full path to file
for %%F in ("%file%") do set "file=%%~fF"

:: escape the backslashes
set "file=%file:\=\\%"

:: get the last modified timestamp for the file
set "fileTime="
for /f "skip=1" %%A in (
  'wmic datafile where "name='%file%'" get lastModified'
) do if not defined fileTime set "fileTime=%%A"

:: convert file timestamp to unix time format
call :UnixTime fileTime %fileTime%

:: get current timestamp in unix time format
call :Unixtime currentTime

:: compute interval in seconds, and convert execTime into seconds
set /a "diff=currentTime-fileTime, execSec=execTime*60"

:: what should we do?
if %diff% gtr %execSec% (
  echo greater than %execTime% min: let's delete
) else (
  echo less than or equal to %execTime% min: just leave alone
)

:: Must exit so we don't fall into the function below
exit /b

:UnixTime  [ReturnVar]  [TimeStamp]
::
:: Computes the Unix time from the current local time as reported by the
:: operating system. The Unix time is the number of seconds that have elapsed
:: since midnight Coordinated Universal Time (UTC), January 1, 1970, not
:: counting leap seconds.
::
:: The result is returned in variable ReturnVar,
:: or the result is echoed if ReturnVar is not specified
::
:: If the TimeStamp is provided in the 2nd parameter, then the Unix time for
:: the TimeStamp is computed, rather then for the current time.
::
:: The TimeStamp must have the same format as used by WMIC:
::
::   YYYYMMDDhhmmss.ffffffSzzz
::
:: where:
::
::   YYYY   = gregorian year
::   MM     = month
::   DD     = day
::   hh     = hour in 24 hour format
::   mm     = minute
::   ss     = seconds
::   ffffff = fractional seconds (microseconds)
::   S      = timezone sign: + or -
::   zzz    = timezone: minutes difference from GMT
::
:: Each component must be zero prefixed as needed to maintain the proper width.
::
:: The ReturnVar parameter must be provided in order to use the TimeStamp.
:: A ReturnVar of "" will function the same as no ReturnVar. This enables the
:: specification of a TimeStamp without an actual ReturnVar.
::
:: Note this function will fail with dates >= 2038-01-19 because the
:: unix time exceeds the maximum value of a signed 32 bit integer.
::
setlocal
set "ts=%~2"
if not defined ts for /f "skip=1 delims=" %%A in ('wmic os get localdatetime') do if not defined ts set "ts=%%A"
set /a "yy=10000%ts:~0,4% %% 10000, mm=100%ts:~4,2% %% 100, dd=100%ts:~6,2% %% 100"
set /a "dd=dd-2472663+1461*(yy+4800+(mm-14)/12)/4+367*(mm-2-(mm-14)/12*12)/12-3*((yy+4900+(mm-14)/12)/100)/4"
set /a ss=(((1%ts:~8,2%*60)+1%ts:~10,2%)*60)+1%ts:~12,2%-366100-%ts:~21,1%((1%ts:~22,3%*60)-60000)
set /a ss+=dd*86400
endlocal & if "%~1" neq "" (set %~1=%ss%) else echo %ss%
exit /b


Retrieving mail attachments given criteria with VBA

Some general review suggestions:

Ditch the Hungarian Notation. Most people implement it incorrectly through no fault of their own.
Add Option Explicit to the top of your code module. There are a couple of undefined variables in there.
Use clear and meaningful variables names. What is h? After spending some time pondering the code, it appears to be the row number where you're writing information in your logging workbook, so call it something like logRowNum. That will make it pretty explicit to the next person (or you in 60 8 days.)
You make reference to ThisWorkbook - it appears that you're expecting it to be your logging workbook, so Dim logWorkbook as Workbook and set it before opening any other workbooks. It appears that you don't have any issues with it for now but if you have an 8-day process running, someone could click on another workbook when it's open and ThisWorkbook now points at something else breaking your code.
Indent your code neatly. Rubberduck (I'm a big fan and hang out in their chat room, but haven't yet started contributing) will help you with that. (It'll also help with renaming variables and a ton of other things.) Also, eliminating a lot of those extra blank lines will make it a bit more readable.
Modify your If statements to test for what you're after instead of what you're not after. Having a blank True "statement" is very awkward to follow.

    'change:
        If olFolder.Items(i).Class <> olMail Then
        Else
          'some code here
        End If
    'to:
        If olFolder.Items(i).Class = olMail Then
          'some code here
        End If

Eliminate empty Else clauses - they make me think you're going to write more code but haven't yet.

Specific to improving speed:

Work with arrays instead of the spreadsheet itself.
Turn off other screen updating things in Excel.
Instead of downloading all attachments, make sure you're only downloading Excel workbooks, no need to download a PDF if you're not going to do anything with it:

    strName = .Attachments.Item(j).DisplayName
    If Instr(0, strName, "xls") > 0 then
      'rest of the code here
    End If
    'loops to next email message

Short-cut your worksheet check, as well as ensuring they both exist:

    Dim AlphaFound as Boolean
    Dim BetaFound as Boolean
    On Error Resume Next
    Set sh = wB.Sheets("alpha")
    If Err.Number = 0 Then    'alpha exists
      AlphaFound = True
    End If
    If not AlphaFound Then
      'only look for "is alpha" if "alpha" isn't there
      Set sh = wB.Sheets("is alpha")
      If Err.Number = 0 Then    'alpha exists
        AlphaFound = True
      End If
    End If
    If AlphaFound Then
      Set sh = wB.Sheets("beta")
      If Err.Number = 0 Then  'beta exists
        BetaFound = True
      End If
    End If
    'turn off error ignoring as soon as possible vvv
    On error goto 0
    If AlphaFound and BetaFound then
      .Attachments(j).SaveAsFile sPathstr & "\" & strName
    End If

Ditch the Set wb = nothing. You're doing it 800,000 times and each time you do, Excel has to free the memory then reallocate it when you hit the next Set wb = something statement. Leave the object in memory until you're done processing. Actually, VBA will Set all objects to Nothing automatically at the end of the Sub for you, so there's no reason to do it for any of them. (Note that wb is the only object you're manually freeing.)
Put the trailing \ on all paths as early as possible to minimize concatenation later. (Don't know how much execution time it will save, but it will save typing time.)

    sPath = Application.FileDialog(msoFileDialogFolderPicker).Show
    If Right(sPath, 1) <> "\" then
      sPath = sPath & "\"
    End If

You have a DoEvents in there, which is being a good Windows citizen, but you may have it a bit too frequently. Maybe move it to outside your attachment count loop so you only do it once per email. I hate to suggest another counter in there, but maybe one that counts processed emails - every time you process 10 emails with attachments, DoEvents and reset the counter. That way other things can still run on the machine, but you're not pausing your process too frequently. If this is running on a dedicated machine (for 8 days!) maybe make it every 100 messages... If the machine is dedicated to this process, you might get away with not having it in there at all.


If you do not want the XML Tags, then do not add them!

This code frustrates me because:

you have not given any indication as to what this code should be doing.
you are embedding presentation-layer logic in the database layer
you convert all the data to an XML document, and then strip all the XML tags from the result because this appears to be a 'cheap' way to get all the data as a single result instead of multiple rows.
you do not document this
you use less-common features of the database (XML manipulation) without good reason, which locks you in to a single provider for the database ;-)
there is no documented reason for why you strip the last character from the @result... this will strip the closing > from the last
, and will thus leave some invalid X?HTML? I presume? A bug?

As for some nit-picks:

You should not be using SELECT @Result = (...), but should, instead be using SET @Result = (...) See the documentation for SELECT.
you capitalize some of your query key-words, but not all. I recommend using whatever case you do not use for your columns. In your case, your db.schema.table.columns are all lower/CamelCase, so your keywords should all be full CAPITALS. Thus, you should have SELECT everywhere. You have one SELECT, and one Select. You have one LEFT, and two replace. Your consistency of convention should be improved.
you do not use table-aliases for your query objects. Not only do table-aliases make the SQL more readable, but, if you need to change a table name for some reason (e.g. to get data from a view, or different schema), then you have to change multiple places, and could lead to bugs....

As far as I am concerned, this function should be removed entirely, and a simple presentation-layer system should be added that simply appends a
 after each bond description from the query:

SELECT uC.Description
FROM Justice.dbo.uCode uC
INNER JOIN Justice.dbo.xBondCondition xBC
        ON uC.CodeID = xBC.ConditionID
WHERE xBC.BondID = ?


MySQL JDBC integration into App from tutorial

You're not following Java naming conventions. Package names should be all lower case.

The JDBC URL is hard coded. This should be provided as a parameter. Or better yet, provide the connection with dependency injection so you can unit test it with mocks.

Worst "offense" is hiding the exceptions from the caller. Instead of printing the stack trace (which is only visible to the end user) you should wrap it in a domain specific exception. This way the application using your library can take proper actions.

When saving the number you list all columns as parameters in the SQL. Including the automatically generated index, which you insert as zero. That was confusing. You should list only the columns that you provide as "INSERT INTO numbers_tabl (number, min, max) ..." and let the database handle the columns that can be generated automatically (index and creation date).

Instead of returning a boolean from saveNumber you could return the RandomNumber object updated with it's new database identifier and creation date.

The names in the database table don't describe their purposes. Table us named "numbers_tabl" but it contains random numbers. The name should tell the reader what the table contains. Also the _tabl suffix is probably a bit pointless. The "created" column name suggests that the value is a boolean. It should be "creation_time". I don't remember MySQL data types from memory but it probably should be a timestamp, not just date.

The method choice comes from the tutorial, right? It's a bit weird to load the numbers into memory and access them from there. After saving a number you have to call loadNumbers before you get the latest number back from getNumbers. The getNumbers should load the numbers from the database. If you want to cache the numbers in memory then the saveNumbers should invalidate the cache, but that's probably a subject for a later tutorial. :) Also there are libraries for that (Ehcache for example).

The standard library for this purpose is JPA (Java Persistence API or Jakarta Persistence). It makes boilerplate SQL so much easier.


Is this reimplemented quicksort correct?

I know you haven't mentioned anything about this, but I think it should still be addressed.

You should not be passing around C arrays in C++.  The entire array is not passed; it merely decays to a pointer to the array.

Instead, use a storage container such as an std::vector.  These will not decay to pointers, and using such containers is more idiomatic C++.  If you have C++, you can use an std::array instead.

Declare and push back the elements:

std::vector<int> values;

values.push_back(6);
values.push_back(6);
// ...

If you have C++11, initialize an std::array instead:

std::array<int, 6> values = { 6, 6, 9, 5, 3, 7 };

Pass either one to a function:

void func(std::vector<int>& values) {}

void func(std::array<int, 6>& values) {}

You will also no longer need n; storage containers know their sizes.  You can access this value with values.size(), which is of the return type std::size_type.  This is also safer because the returned value will be updated as the container changes size.

If you don't have C++11, display the container with (const) iterators:

std::vector<int>::const_iterator iter;
// OR
std::array<int, 6>::const_iterator iter;

for (iter = values.cbegin(); iter != values.cend(); iter++)
{
    std::cout << *iter;
}

If you do have C++11, use a range-based for-loop:

for (auto& iter : values)
{
    std::cout << iter;
}

You can use auto here to give you the correct container type automatically.


Making thousands of DOM elements draggable with JavaScript

Here are some suggestions to improve the fluidity of your app:

Use translate instead of top/left positioning

According to this blog post: https://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/, translate is much more efficient regarding the CPU usage

Use requestAnimationFrame

https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

This function allows you to do the computation only if required (see this SO answer on how to combine it with mousemove: https://stackoverflow.com/a/23658815/3207406)


Dataset Copy, Change, then Write new Rows back

So basically you make a copy of all rows for a specific job, replace the job number and append the changed row back to the database. Sounds like this should be doable in one loop with the help of ItemArray and no need for a temporary table:

nexusDBDataSet.Drawing_Table.Clear();
drawing_TableTableAdapter.Fill(nexusDBDataSet.Drawing_Table);
foreach (DataRow jobRow in nexusDBDataSet.Drawing_Table.Select(string.Format("JobNumber = '{0}'", OldJobcardNumber)))
{
    var newRow = nexusDBDataSet.Drawing_Table.NewRow();
    newRow.ItemArray = jobRow.ItemArray;

    string directoryName = jobRow["DirectoryName"].ToString();
    newRow["JobNumber"] = NewJobcardNumber;
    newRow["DirectoryName"] = DirectoryName.Replace("\\" + OldJobcardNumber + "\\", "\\" + NewJobcardNumber + "\\");

    nexusDBDataSet.Drawing_Table.Rows.Add(newRow);
}
// save table