Is this a good way to download images from json Api?

Maybe the image is in question is a little bit large or the internet connection used is a little bit slow.
I personally would go about it differently.
For UIKit
import UIKit
import Foundation

extension UIImageView {
    func load(url: URL) {
        DispatchQueue.global().async { [weak self] in
            if let data = try? Data(contentsOf: url) {
                if let image = UIImage(data: data) {
                    DispatchQueue.main.async {
                        self?.image = image
                    }
                }
            }
        }
    }
}

For SwiftUI we have to go about it a little bit differently but there are two ways
The very simple one-time usage:
import Foundation
import SwiftUI
import Combine

// Image Loader
class ImageLoader: ObservableObject {
    var dataPublisher = PassthroughSubject<Data, Never>()
    var data = Data() {
        didSet {
            dataPublisher.send(data)
        }
     }

     init(urlString:String) {
        guard let url = URL(string: urlString) else { return }
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data else { return }
            DispatchQueue.main.async {
                self.data = data
            }
        }
        task.resume()
     }
}

// Image View
struct ImageView: View {
    @ObservedObject var imageLoader:ImageLoader
    @State var image:UIImage = UIImage()

    init(withURL url:String) {
        imageLoader = ImageLoader(urlString: url)
    }

    var body: some View {
        VStack {
            Image(uiImage: image)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width:100, height:100)
        }.onReceive(imageLoader.dataPublisher) { data in
            self.image = UIImage(data: data) ?? UIImage()
        }
    }
}

struct ImageView_Previews: PreviewProvider {
    static var previews: some View {
        ImageView(withURL: "")
    }
}

The more advanced way
import Foundation
import SwiftUI
import Combine

// ImageCache
protocol ImageCache {
    subscript(_ url: URL) -> UIImage? { get set }
}

struct TemporaryImageCache: ImageCache {
    private let cache: NSCache<NSURL, UIImage> = {
        let cache = NSCache<NSURL, UIImage>()
        cache.countLimit = 100 // 100 items
        cache.totalCostLimit = 1024 * 1024 * 100 // 100 MB
        return cache
    }()

    subscript(_ key: URL) -> UIImage? {
        get {
            self.cache.object(forKey: key as NSURL)
        }
        set {
            newValue == nil ? self.cache.removeObject(forKey: key as NSURL) : self.cache.setObject(newValue!, forKey: key as NSURL)
        }
    }
}

// EnvironmentValues+ImageCache
struct ImageCacheKey: EnvironmentKey {
    static let defaultValue: ImageCache = TemporaryImageCache()
}

extension EnvironmentValues {
    var imageCache: ImageCache {
        get {
            self[ImageCacheKey.self]
        }
        set {
            self[ImageCacheKey.self] = newValue
        }
    }
}

// Image Loader
class ImageLoader: ObservableObject {
    @Published
    var image: UIImage?

    private(set) var isLoading = false

    private let url: URL
    private var cache: ImageCache?
    private var cancellable: AnyCancellable?

    private static let imageDownloadingQueue = DispatchQueue(label: "image-downloading")

    init(url: URL, cache: ImageCache? = nil) {
        self.url = url
        self.cache = cache
    }

    deinit {
        self.cancel()
    }

    func load() {
        guard !self.isLoading else { return }

        if let image = self.cache?[self.url] {
            self.image = image
            return
        }

        self.cancellable = URLSession.shared.dataTaskPublisher(for: self.url)
            .map {
                UIImage(data: $0.data)
            }
            .replaceError(with: nil)
            .handleEvents(receiveSubscription: { [weak self] _ in
                self?.onStart()
            },
            receiveOutput: { [weak self] in
                self?.cache($0)
            },
            receiveCompletion: { [weak self] _ in
                self?.onFinish()
            },
            receiveCancel: { [weak self] in
                self?.onFinish()
            })
            .subscribe(on: Self.imageDownloadingQueue)
            .receive(on: DispatchQueue.main)
            .sink { [weak self] in
                self?.image = $0
            }
    }

    func cancel() {
        self.cancellable?.cancel()
    }

    private func onStart() {
        self.isLoading = true
    }

    private func onFinish() {
        self.isLoading = false
    }

    private func cache(_ image: UIImage?) {
        image.map {
            self.cache?[self.url] = $0
        }
    }
}

// Image View
struct ImageView<Placeholder: View>: View {
    @StateObject
    private var loader: ImageLoader
    private let placeholder: Placeholder
    private let image: (UIImage) -> Image

    init(url: URL, @ViewBuilder placeholder: () -> Placeholder, @ViewBuilder image: @escaping (UIImage) -> Image = Image.init(uiImage:)) {
        self.placeholder = placeholder()
        self.image = image
        self._loader = StateObject(wrappedValue: ImageLoader(url: url, cache: Environment(\.imageCache).wrappedValue))
    }

    var body: some View {
        self.content.onAppear(perform: loader.load)
    }

    private var content: some View {
        Group {
            if let image = self.loader.image {
                self.image(image)
            } else {
                self.placeholder
            }
        }
    }
}

```


Exception handling in URL builder method

If we are speaking in terms of Clean Code, the entire method should be revised.

Here are the main points that I can criticize:

if ... else if ... branches are used to match Strings: this approach is too verbose and not very flexible.
URL is instantiated in two different places, with same semantics.
The Exception thrown in else block is immediately caught and thus is useless.
The catch blocks hide exception details and trace, which is annoying for debugging.
Returning null is ugly. A better choice would be either to return an Optional or throw the exception outside the method.

This method does two distinct things:

1) Determine which URL to use depending on the requestingService value.

2) Instantiate a URL object with query suffix.

Each of these things should be wrapped in a dedicated method.

So let's first create the getServiceUrl method:

private static String getServiceUrl() {
  switch (requestingService) {
    case "playerProfile": return PLAYER_URL;
    case "search": return SEARCH_URL;
    default: throw new IllegalStateException("Unexpected requestingService value=" + requestingService);
  }
}

Here I suppose that requestingService member of this class can take only a predefined set of values (and even should be transformed into an enum!) and any value that is not in this set denotes an internal problem that puts the application into an invalid state.

BTW, since the original method is static, I suppose that requestingService is also a static member and therefore should be renamed according to style conventions. And I also suspect that there is some misuse of statics, but can't say more about it without having the entire code.

Second, we rewrite the original method:

private static URL addQueryToUrl(String qry) {
  try {
    return new URL(getServiceUrl() + qry);
  } catch (MalformedURLException e) {
    throw new IllegalStateException(e);
  }
}

Since PLAYER_URL and SEARCH_URL are pre-validated constants, I suppose that they cannot represent a cause for a MalformedURLException. But from the original code, it is not clear whether qry is validated as part of URL pattern or not. If so, an IllegalStateException would be appropriate here. Otherwise the catch block should log the exception message and return an Optional.empty() instead (also change the return type to Optional<URL> and the return statement respectively).

I'd also suggest to rename this method to buildUrlWithQuery.


Edit: Tested implementations below.

As jason says, returning either 0 or 1, looks like boolean. Change int to bool and return true or false.

Drop the std::string layer. It doesn't add anything over enum. And enum are just as readable and there is no way typos can appear with enums.

I don't have any experience with SDL myself, but I've written a keyboard -> action controller in an attempt at a game.

I'd also like to drop the std::map in favor of a std::vector. The trick is to use continuous enums and use those as indices for the std::vector.

Something like this:

enum class KeyboardEvents : byte
{
    ON_RELEASE,
    ON_PRESS,

    ORDINAL
};

typedef std::function<void(void)> keyboardFunc_t;

std::vector<keyboardFunc_t> keyboardEvents(KeyboardEvents::ORDINAL);

void bindControls()
{
    auto onReleaseLambda = [&]()
    {
        // Do stuff
    };
    auto onPressLambda = [&]()
    {
        // Do stuff
    };

    // Bind with lambdas
    keyboardEvents[KeyboardEvents::ON_RELEASE] = onReleaseLambda;
    keyboardEvents[KeyboardEvents::ON_PRESS] = onPressLambda;

    // Alternatively, use std::bind
    keyboardEvents[KeyboardEvents::ON_RELEASE] = std::bind(&ClassName::onRelease, classInstancePtr);
    keyboardEvents[KeyboardEvents::ON_PRESS] = std::bind(&ClassName::onPress, classInstancePtr);
}

I just wrote this on the top off my head. I'm not sure if it'll compile, but you get the idea.

I would also prefer lambdas in favor of std::bind.

As for storing std::shared_ptr<ControllerContext> controller_context_; in a raw or shared_ptr, I'd say neither. But DO use std::unique_ptr. Using a unique_ptr will make sure your controller class is not default copyable, which is a good thing when dealing with limited resources.

Like this std::unique_ptr<ControllerContext> controller_context_;

Edit: From here and on:

Note, don't look too closely on main.cpp, it was mainly copied from somewhere to get SDL2 running.

ControllerContext.h:

#ifndef SHMUPPY_HEADER_CONTROLLER_CONTEXT_H
#define SHMUPPY_HEADER_CONTROLLER_CONTEXT_H

#include <vector>
#include <functional>

struct ControllerContext
{

    ControllerContext()
        : keyPressEvents(SDL_NUM_SCANCODES)
        , keyReleaseEvents(SDL_NUM_SCANCODES)
    {
        keyPressEvents.resize(SDL_NUM_SCANCODES);
        keyReleaseEvents.resize(SDL_NUM_SCANCODES);
    }

    typedef std::function<void(void)>   KeyboardFunc_t;
    typedef std::vector<KeyboardFunc_t> KeyEvents;

    KeyEvents   keyPressEvents;
    KeyEvents   keyReleaseEvents;
};

typedef std::unique_ptr<ControllerContext>  ControllerContext_ptr;

#endif

keyboardcontroller.h:

#ifndef SHMUPPY_HEADER_KEYBOARDCONTROLLER_H_
#define SHMUPPY_HEADER_KEYBOARDCONTROLLER_H_

#include <map>
#include <SDL.h>
#include <iostream>
#include <exception>
#include <string>
#include <memory>

#include "ControllerContext.h"

class Controller
{
public:
    Controller();

    bool OnKeyPress(const SDL_Event &e);

    bool OnKeyRelease(const SDL_Event &e);

    // Clear by setting empty func
    void SetReleaseCallback(SDL_Scancode code, const ControllerContext::KeyboardFunc_t & func);
    void SetPressCallback(SDL_Scancode code, const ControllerContext::KeyboardFunc_t & func);

    // Clear both press and release
    void ClearCallback(SDL_Scancode code);

protected:
    ControllerContext_ptr controller_context_;
};

#endif

keyboardcontroller.cpp:

#include "KeyboardController.h"
#include "ControllerContext.h"

Controller::Controller()
    : controller_context_(new ControllerContext())
{
    //Some test initializations
    auto leftPress = [&]()
    {
        // Left press lambda
        int debug=0;
    };
    auto leftRelease = [&]()
    {
        // Left release lambda
        int debug=0;
    };

    SetPressCallback(SDL_SCANCODE_LEFT, leftPress);
    SetReleaseCallback(SDL_SCANCODE_LEFT, leftRelease);
}

bool Controller::OnKeyPress(const SDL_Event &e)
{
    const auto & scancode = e.key.keysym.scancode;

    const auto & pressFunc = controller_context_->keyPressEvents[scancode];

    if (pressFunc)
    {
        // Call callback if valid
        pressFunc();
        return true;
    }

    return false;
}

bool Controller::OnKeyRelease(const SDL_Event &e)
{
    const auto & scancode = e.key.keysym.scancode;

    const auto & pressFunc = controller_context_->keyReleaseEvents[scancode];

    if (pressFunc)
    {
        // Call callback if valid
        pressFunc();

        return true;
    }

    return false;
}

void Controller::SetReleaseCallback(SDL_Scancode code, const ControllerContext::KeyboardFunc_t & func)
{
    controller_context_->keyReleaseEvents[code] = func;
}

void Controller::SetPressCallback(SDL_Scancode code, const ControllerContext::KeyboardFunc_t & func)
{
    controller_context_->keyPressEvents[code] = func;
}

void Controller::ClearCallback(SDL_Scancode code)
{
    controller_context_->keyPressEvents[code] = ControllerContext::KeyboardFunc_t();
    controller_context_->keyReleaseEvents[code] = ControllerContext::KeyboardFunc_t();
}

main.cpp:

#include <SDL.h>
#include <iostream>

class TestMain
{
    public:
        void handlePressW()
        {
            // W press
            int debug=0;
        }
        void handleReleaseW()
        {
            // W release
            int debug=0;
        }
};

#include "keyboardcontroller.h"

int _stdcall WinMain(struct HINSTANCE__ *hInstance, struct HINSTANCE__ *hPrevInstance, char *lpszCmdLine, int nCmdShow)
{
    if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
        /* Handle problem */
        fprintf(stderr, "%s\n", SDL_GetError());
    }
    SDL_Window* window = SDL_CreateWindow("Window caption", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 852, 480, 0);
    if (window == NULL)
    {
        /* Handle problem */
        fprintf(stderr, "%s\n", SDL_GetError());
        SDL_Quit();
    }
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
    if (renderer == NULL)
    {
        /* Handle problem */
        fprintf(stderr, "%s\n", SDL_GetError());
        SDL_Quit();
    }

    Controller keycontroller;

    // Bind testmain methods
    TestMain testmain;
    keycontroller.SetPressCallback(SDL_SCANCODE_W, std::bind(&TestMain::handlePressW, testmain));
    keycontroller.SetReleaseCallback(SDL_SCANCODE_W, std::bind(&TestMain::handleReleaseW, testmain));

    bool running = true;
    while (running)
    {
        /* Clear the buffer of color, setting it to black */
        SDL_RenderClear(renderer);

        /* Draw the buffer into the window */
        SDL_RenderPresent(renderer);

        /* Handle input and events: */
        SDL_Event sdl_event;
        while (SDL_PollEvent(&sdl_event) > 0)
        {
            switch (sdl_event.type)
            {
                case(SDL_KEYDOWN):
                {
                    keycontroller.OnKeyPress(sdl_event);
                    break;
                }

                case(SDL_KEYUP):
                {
                    keycontroller.OnKeyRelease(sdl_event);
                    break;
                }

                case(SDL_QUIT):
                    running = false;
                    break;
            }

        }

        /* Run your logic. For example: */
    }

    SDL_Quit();

    return 0;
}


A "functional" method avoiding recusion would be

from itertools import count

def gen_primes():
    return filter(is_prime, count(2))

def nth(n, iterable):
    return next(val for i, val in enumerate(iterable) if i == n)

def nth_prime(n):
    return nth(n, gen_primes())

To prove that this is functional, here's the Haskell:

enumerate = zip [0..]

primes = filter is_prime [2..]

nth iterable n = head [v | (i, v) <- enumerate iterable, i == n]

nth_prime = nth primes

The trick is to make everything as small as logically possible and see how to extract common functionality.


Add two digit strings and return the result as string

Always Initialize Variables

There is one possible bug in the code, the variables d1 and d2 assume that both num1 and num2 have values, this may not be true. The C programming language does not initialize variables by default like some other languages, especially local variables. All of the variables should be initialized before the loop.

This also creates multiple paths through the code if either num1 or num2 do not have a value and error checking is added.

char * addStrings(char * num1, char * num2){
    int len1 = strlen(num1);
    int len2 = strlen(num2);

    if (!len1 && !len2)
    {
        fprintf(stderr, "Neither string has an integer value.");
        return "0";
    }
    else
    {
        if (!len1)
        {
            return num2;
        }
        if (!len2)
        {
            return num1;
        }
    }

    ...

    return rp;
}

Complexity

With the added error check the function addStrings() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.

There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:

  that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

Probably the best thing to do here is to break addStrings() into 2 functions, one that does the error checking, and one that calculates the value of the string. The addStrings() function  should do the error checking itself, and then call a function to calculate the value of the string.

Missing Headers

In addition to the missing header files noted by vnp an include of the header file string.h is necessary to allow strlen() to compile, at least on my computer with my C compiler (Windows 10, Visual Studio 2019).

DRY Code

There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.

This code is repetitive and the manipulation of the pointers and counters isn't necessary at this point.

    if (len1) {
        d1 = (*p1)-zero;
        p1--;
        len1--;
    }
    if (len2) {
        d2 = (*p2)-zero;
        p2--;
        len2--;
    }

It might be better to just check if pN has a value and use what it points to if it does, change the pointers and the counters at the end of the loop.

    if (p1) {
        d1 = (*p1) - zero;
    }

    if (p2) {
        d2 = (*p2) - zero;
    }

Scope of Variables

The integer variables digit, d1 and d2 are never used outside the loop so they can be declared within the loop itself. Only declare the variables when they are needed.

In Summation

As noted by vnp there is a memory leak.

An example of what how I would write the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static const unsigned char zero = '0';

char addCharacters(char *p1, char *p2, int *carry)
{
    int digit = 0;
    int d1 = 0;
    int d2 = 0;

    if (p1) {
        d1 = (*p1) - zero;
    }

    if (p2) {
        d2 = (*p2) - zero;
    }

    int tmp = d1 + d2 + *carry;
    digit = tmp % 10;
    *carry = tmp / 10;

    return digit + zero;
}

char* calculateStringValue(char *result, char num1[], int len1, char num2[], int len2, int result_len)
{
    char *rp = result + result_len;
    *rp = '\0';
    rp--;

    int carry = 0;
    char *p1 = num1 + len1-1;
    char *p2 = num2 + len2-1;

    while (len1 || len2)
    {
        *rp = addCharacters(p1, p2, &carry);
        --len1;
        --len2;
        p1 = (len1 > 0) ? --p1 : NULL;
        p2 = (len2 > 0) ? --p2 : NULL;
        --rp;
    }

    if (carry) {
        *rp = carry + zero;
    } else {
        rp++;
    }

    return rp;
}

char * addStrings(char * num1, char * num2){
    int len1 = strlen(num1);
    int len2 = strlen(num2);

    if (!len1 && !len2)
    {
        fprintf(stderr, "Neither string has an integer value.");
        return "0";
    }
    else
    {
        if (!len1)
        {
            return num2;
        }
        if (!len2)
        {
            return num1;
        }
    }

    int result_len = len1 > len2? len1: len2;
    result_len += 1;    // allow for carry.

    char *result = malloc(result_len + 1);
    if (result == NULL)
    {
        fprintf(stderr, "malloc failed in addStrings\n");
        return NULL;
    }

    return calculateStringValue(result, num1, len1, num2, len2, result_len);
}

int main() {
    char num1[] = "2048";
    char num2[] = "9999";
    printf("AddStrings returns %s\n", addStrings(num1, num2));
    return 0;
}


Filtering out employees that do not meet some criteria, using list comprehensions

The simplest refactoring is as follows:

CONDITIONS = [
    ('WRK_RLTN_DSC', 'INDEPENDENT CONTRACTOR'),
    ...
]
set2 = [s for s in set2 if s['LEAD_TIME'] >= 0]
for key, excl in CONDITIONS:
    set2 = [s for s in set2 if s[key] != excl]

Note:

You can assign straight back to set2, getting rid of the temporary inScope variable;
I have factored out the multiple checks into a simple loop over a list of keys and values; and
I have consistently used single quotes for string literals, rather than a mix of single and double.

However, although neater than your current code, this is still relatively inefficient, as it builds multiple lists; you could instead try something like:

set2 = [s for s in set2 if s['LEAD_TIME'] >= 0 and
        all(s[key] != excl for key, excl in conditions)]

which reduces it to a single list comprehension. An alternative would be to incorporate e.g.:

INVALID_WRK = {
    'INDEPENDENT CONTRACTOR',
    ...
}

... s['WRK_RLTN_DSC'] not in INVALID_WRK ...

as you check that key multiple times.


Non-const static variables

Your code shows a lot of good practices:

variables are always initialized when possible
variables have proper names (and you stuck to a single naming scheme)
no unecessary std::endl

However, there is one drawback:

static int random_number;

That line right there is, at least from my point of view, a flaw. static variables are a nice escape hatch in some circumstances, but here it's unnecessary. We can easily use another argument to finder, for example:

guess_stats finder(comparison_function && cmp, int random_number) {
   ...
}

Or we could combine the comparison function with the number to be guessed in a struct, similar to guess_stats.

Either variant makes sure that our changes in finder won't spill into the rest of our program flow. While we don't intend to change random_number in finder, it's easy to accidentally write random_number++ or press <Tab> in an IDE with the wrong completion. If we were to use multiple finder variants in separate threads, we would have a hard time to debug the behaviour, especially if there is more than a single static variable.

However, I guess you've used random_number as a static variable to ease the use of compare. There are other ways that we will inspect at the end of this review.

Note that const static or constexpr static variables on the other hand are fine, as they cannot lead to debugging troubles (unless you const_cast them, but at that point we're deep within undefined behaviour territory).

Q&A

  Although I don't expect there will be, are there any edge-cases I may not have seen?

What happens if I use the following comparison?

int compare(int unused) {
    return 1;
}

Sure, that's not a valid comparison, however, there is nothing in finder that blocks us from using such a function. Given that a binary search should take at most \$\log_2(n)+1\$ steps, we can introduce a simple limit of 33 iterations.

  Are there any algorithmic changes that I could make to have less time-complexity? I don't think so (because this is only O(log n) as it is), but I may be surprised to find out.

That's all correct, and from an \$\mathcal O\$ analysis there's nothing to improve.

  Are there any better ways to generate random numbers?

There's the <random> header. We can use the example code from uniform_int_distribution to generate a random number:

int main(void)
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<int> dist(0, std::numeric_limits<int>::max());

    const int random_number = dist(gen);

    ...
}

However, keep in mind that this usually won't seed a mt19937 correctly and there are ways around that issue.

Getting rid of random_number

Given that we use <functional>, we use at least C++11. Therefore, we have lambdas at hand. We can use this to our advantage to get rid of random_number in main:

int main(void)
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<int> dist(0, std::numeric_limits<int>::max());

    const int random_number = dist(gen);

    auto compare = [random_number](int guess) {
        if (guess > random_number) {
            return 1;
        } else if (guess < random_number) {
            return -1;
        }
        return 0;
    };

    guess_stats stats = finder(compare);
    ...
}

We don't even need to change finder to use the new comparison, thanks to std::function<int(int)>&&.


When you create a List, are you forced to provide a capacity? No you're not. I think it should be the same concerning your data structure. There are several occasions where you just don't know how many objects you'll have. Since the underlying Queue and Dictionary can very well adapt to increase your capacity, your data structure has nothing to fear by offering a default empty constructor.

I'm wondering why GetOrAdd exists. When you Get an object from a Queue, you should remove that object, IMO. So you should implement some kind of Exists method, and the client of your object will deal with the scenario where you could want to add an object if it doesn't exist already.

Finally, there is one terrible side effect in your code :

if (_map.Count == _capacity) // capacity reached
{
    RemoveFirst();
}

If you reach capacity, you should either expand your capacity, or throw an exception. Removing the first object is just a way to hide the problem. But if I use your class, I would never expect this situation if the queue was full.


I think overall is good, some bits can be improved but it depends on taste. Take the following comments as suggestions.

As rooms is an array, can be defined in a shorter way as:

local rooms = {
   { south=3, east=2 },
   { south=4, west=1 },
   { north=1, east=4 },
}

Variable currentRoom can be localized:

local currentRoom = 1

In Lua can compare a var to nil or ask not var:

if not room then
   ...
end

Branches are exclusive, use of elseif can be skipped:

if not room then
   room = currentRoom
   print("Invalid move")
end
if room == 4 then
   print("Congratulations, you won!")
end

EDIT:

I would rearrange the code at the bottom as:

-- Update room state.
room = rooms[currentRoom][move]
if room then
  currentRoom = room
else
  print("Invalid move")
end

-- Reached final state?
if currentRoom == 4 then
  print("Congratulations, you won!")
end

that avoids the currentRoom = room or currentRoom statement (currentRoom only gets updated is room is not nil).


Weird limits

I have absolutely no idea of what date is "the 12th of June at 24 hour 60 minutes", yet you consider it a valid date as regard to your bounds. You should assert hours and minutes to be respectively 23 and 59 at max.

Using a two-digit long value for the date seems rather useless too. What century does it encode exactly? And assuming it is for years in the 2000 era, why limit to 2031?

Unused stuff

Both your imports and constant are unused, you should remove them.

Bitfield manipulation

Extracting informations out of a bitfield is generally done using a mask. You need to create the mask corresponding to size bits set using mask = (1 << (size + 1)) - 1 and then you can use data & mask to get the desired value. The advantage being that you can easily add an offset to grab the exact portion you’re interested in:

def extract(data, size, offset):
    mask = (1 << (size + 1)) - 1
    return (data & (mask << offset)) >> offset

def decompress_date(data):
    minute = extract(data, 6, 0)  # minutes are at the end, no offset
    hour = extract(data, 5, 6)  # hours are after minutes (6)
    day = extract(data, 5, 11)  # days are after hours (5) and minutes (6)
    month = extract(data, 4, 16)  # you get it
    year = extract(data, 5, 20)
    return (year, month, day, hour, minute)

Value creation

You can simplify the compressed data creation by dropping useless initialization:

def compress(...):
    data = year
    data = (data << 4) + month
    ...

Knowing the offsets, you can also use them to create the compressed data all at once. To simplify reading and understanding, you can also define a bunch of constants:

MINUTES_SIZE = 6
HOURS_SIZE = 5
DAYS_SIZE = 5
MONTHS_SIZE = 4
YEARS_SIZE = 5

MINUTES_OFFSET = 0
HOURS_OFFSET = MINUTES_OFFSET + MINUTES_SIZE
DAYS_OFFSET = HOURS_OFFSET + HOURS_SIZE
MONTHS_OFFSET = DAYS_OFFSET + DAYS_SIZE
YEARS_OFFSET = MONTHS_OFFSET + MONTHS_SIZE

def decompress_date(data):
    minute = extract(data, MINUTES_SIZE, MINUTES_OFFSET)
    hour = extract(data, HOURS_SIZE, HOURS_OFFSET)
    day = extract(data, DAYS_SIZE, DAYS_OFFSET)
    month = extract(data, MONTHS_SIZE, MONTHS_OFFSET)
    year = extract(data, YEARS_SIZE, YEARS_OFFSET)
    return (year, month, day, hour, minute)

def compress_date(year, month, day, hour, minute):
    assert year <= 31
    assert 0 < month <= 12
    assert 0 < day <= 31
    assert 0 <= hour < 24
    assert 0 <= minute < 60

    return (
        (year << YEARS_OFFSET) +
        (month << MONTHS_OFFSET) +
        (day << DAYS_OFFSET) +
        (hour << HOURS_OFFSET) +
        (minute << MINUTES_OFFSET)
    )

Timestamps

The "classic" condensed representation of a point in time is given by a timestamp: the elapsed time in seconds since January 1st 1970. Since you’re only interested in minutes, you can create a simple wrapper around Python's datetime.timestamp():

import datetime

def compress(date):
    return int(date.timestamp() // 60)

def compressed_date(year, month, day, hour, minute):
    return compress_date(datetime.datetime(year, month, day, hour, minute)

def uncompress(truncated_timestamp):
    return datetime.datetime.fromtimestamp(truncated_timestamp * 60)

And support a wider variety of dates.


Heap's algorithm implementation - permutations

From a short review:

Keep the typeof check out of the recursive part, you only need to do this during the first call of the function
The fat arrow syntax is good for inline functions, in this case I would highly encourage you to use the function keyword
If nis 1, get out of the function after the push, there is no need to execute the remainder
I like verbThing for naming function, so perhaps use swapListElements and permutateList permuteList
"heap" is not a JavaScript thing, I would not use it in your naming unless you actually created a "Heap" object
newArray is not a great name, especially since most of the time it is not actually a new array, but the array that was passed to the function
I had to re-read the code that uses j, the variable is not intuitively named, and the code could use a comment there
Furthermore, the ternary statements over 3 lines are mind breaking, I would keep them on 1 line

This is my version of Heap's algorithm, with the above taken into account

function swap(list, pos1, pos2){
  const temp = list[pos1];
  list[pos1] = list[pos2];
  list[pos2] = temp;
}

//Implements Heap's permutation algorithm
//https://en.wikipedia.org/wiki/Heap%27s_algorithm
function permute(list) {

  var out = [];
  list = typeof list === 'string' ? list.split('') : list;
  permuteList(list, list.length);

  function permuteList(list, n) {
    var i;

    if (n == 1) {
      out.push(list.join(''));
    } else {
      for (i = 0; i < n - 1; i++) {
        permuteList(list, n - 1);
        if (n % 2) {
          swap(list,0, n - 1);
        } else {
          swap(list,i, n - 1);
        }
      }
      permuteList(list, n - 1);
    }
  }
  return out;
}

console.log(permute('abc'));
console.log(permute('abcdef').length);


You're reading the file into memory inefficiently. I can't write the full code currently, but here's the gist:

Instead, use the ioutil package: func ReadFile(filename string) ([]byte, error).

Once you've read the file into a byte array, you can remove extraneous characters (newlines, invalid characters, etc). One way is to use bytes.Replace with n of -1.

Then, you can search the byte array using the bytes package: func Count(s, sep []byte) int.

Also, if you want to correctly time a function, use the testing package.


Search through JavaScript object using a whitelist/filterlist

You could use a simplified version for lookup all needed values and the check against the needle.

function search(needle, haystack, filter) {
    return filter.some(function (f) {
        function iter(o, i) {
            var item;

            if (!(ff[i] in o)) {
                return false;
            }

            item = o[ff[i]];
            i++;

            if (i === ff.length) {
                return item.indexOf(needle) !== -1;
            }

            if (Array.isArray(item)) {
                return item.some(function (a) {
                    return iter(a, i);
                });
            }
            return iter(item, i);
        }

        var ff = f.split('.');

        return iter(haystack, 0);
    });
}

var filter = ['company', 'friends.name'],
    hay = [{ "id": "57db96f4acfaec3218383063", "name": { "first": "Nora", "last": "Cooke" }, "company": "MITROC", "email": "nora.cooke@mitroc.com", "friends": [{ "id": 0, "name": "West Duke" }, { "id": 1, "name": "Williams Kelley" }, { "id": 2, "name": "Amelia Kirk" }] }, { "id": "57db96f4d5cae409054d3a5b", "name": { "first": "Dickson", "last": "Moses" }, "company": "VISUALIX", "email": "dickson.moses@visualix.org", "friends": [{ "id": 0, "name": "Patty Carr" }, { "id": 1, "name": "Bowers Wilkerson" }, { "id": 2, "name": "Fox Kidd" }] }, { "id": "57db96f42215bea719d83036", "name": { "first": "Kerr", "last": "Gray" }, "company": "TUBESYS", "email": "kerr.gray@tubesys.io", "friends": [{ "id": 0, "name": "Rose Pierce" }, { "id": 1, "name": "Matthews Moore" }, { "id": 2, "name": "Brenda Ayala" }] }, { "id": "57db96f435d0f064afc90768", "name": { "first": "Elsie", "last": "Dejesus" }, "company": "KLUGGER", "email": "elsie.dejesus@klugger.us", "friends": [{ "id": 0, "name": "Gina Cruz" }, { "id": 1, "name": "Nieves Carrillo" }, { "id": 2, "name": "Chandler Sanford" }] }, { "id": "57db96f4597631fffff36b6b", "name": { "first": "Chan", "last": "Mcdaniel" }, "company": "AQUACINE", "email": "chan.mcdaniel@aquacine.name", "friends": [{ "id": 0, "name": "Hodge Sweeney" }, { "id": 1, "name": "Sweet Burnett" }, { "id": 2, "name": "Lynn Hunter" }] }];

console.log(hay.map(function (a) {
    return search('Sweet', a, filter);
}));

console.log(hay.map(function (a) {
    return search('Rose', a, filter);
}));
.as-console-wrapper { max-height: 100% !important; top: 0; }


There are only two things I can think of.

Sometimes it's best to pass objects when there are more than 4 parameters for a method call.

Instead of this

function scan_el(el_fin_callback, el, mask, sub_mask, real_height, real_width, push, lines, line) {

Try this.

function scan_el(el_fin_callback, els, metrics, lines, line) {

els and metrics would look something like this.

els = {
    el : jQuery,
    mask : jQuery,
    submask : jQuery
};
metrics = {
    real_width : Number,
    real_height : Number,
    push : Number
}

Try to make functions no longer than 8-12 lines.

You could extract the real_* variables into a function and return a object instead of a list of variables.

function getRealMetrics(el){
      // doesn't work completely
    var real = {};
    real.box = window.getComputedStyle(el);
    real.width = parseFloat(real.box.width);
    real.height = parseFloat(real.box.height);
    real.el = el.getBoundingClientRect();
    real.el_style = window.getComputedStyle(el);
    real.el_padding = parseFloat(real.el_style.padding);
    real.el_padding_left = parseFloat(real.el_style.paddingLeft);
    real.el_margin_left = parseFloat(real.el_style.marginLeft);
    real.el_align = real.el_style.textAlign;

    if (!isNaN(real.el_padding)) {
        real.el_height -= real.el_padding * 2.0;
    }
    var lines = Math.ceil(real.el_height / real.height);
    if (lines > 1) {
        length = real.el.width;
    }
    real.el_push = real.el_margin_left + real.el_padding_left + (real.el.width - length) / 2.0;
    if (real.el_align !== 'center') {
        real.el_push = real.el_margin_left + real.el_padding;
    }
    return result;
}


Makefile for a custom operating system kernel

Disclaimer: I'm not experienced with this field, but this question definitely needs some activity, so this is my attempt at an answer. If there's anything that you want me to cover that I don't mention here, just tell me about it and I'll try my best to see what I can do.

Style/nitpicks

I find that some of your rule indentation is a bit excessive, and makes your code a little harder to read. Right now you're indenting your rules by tabs with a width of eight spaces. I'd recommend that you indent by tabs with a width of four, like this:

some_rule : file.c
    do_something file.c -foo -bar

You also seem to have a lack of blank lines between your rules as well. I'd highly recommend including at least one blank line between each rule, and a comment, if necessary:

# ...
some_rule1 : file.c
    ...

some_rule2 : file.c
    ...

Finally, you're inconsistent in your colon (:) placement in some places. For example, sometimes you place your colons like this:

all: $(KERNEL).bin

Other times, you place them like this:

$(C_OBJECTS):%.o:%.c

I prefer the following style, but as long as you're, again, consistent, any of the above or below are fine:

some_rule : ...


Move the First and second Cte to temp table.

you don't have to refer  ( SELECT InvariantLanguageCultureCode FROM y) more than once in join condition instead use it in one column then join that column with other tables.

Try this.

DECLARE @ReportingInstanceID INT

SET @ReportingInstanceID=34;

SELECT [TRCCore].[dbo].[pr_Language].InvariantLanguageCultureCode
INTO   #temp_InvariantLanguageCultureCode
FROM   [TRCCore].[dbo].[pr_Language]
       JOIN [dbo].[tenant_User_Setting]
         ON tenant_User_Setting.LanguageID = pr_Language.LanguageID
WHERE  tenant_User_Setting.UserID IN (SELECT [dbo].[tenant_Reporting_Instance].UserID
                                      FROM   [dbo].[tenant_Reporting_Instance]
                                      WHERE  tenant_Reporting_Instance.ReportingInstanceID = @ReportingInstanceID)

SELECT [dbo].[tenant_Reporting_Instance].UserID
INTO   #temp_UserID
FROM   [dbo].[tenant_Reporting_Instance]
WHERE  tenant_Reporting_Instance.ReportingInstanceID = @ReportingInstanceID

SELECT r.RoundingTypeInvariantCode,
       a.AgingDateValue,
       cur.CurrencyLabel,
       jz.JobZoneLinkTypeLabel,
       m.MatchPeriodLabel,
       pf.PayFrequencyLabel,
       pt.PayTypeLabel
FROM   dbo.tenant_User_Setting s
       JOIN TRCCore.dbo.pr_Rounding_Type r
         ON r.RoundingTypeID = s.RoundingTypeID
       JOIN dbo.tenant_Aging_Date a
         ON a.AgingDateID = s.AgingDateID
       JOIN TRCCore.dbo.translation_pr_Currency cur
         ON cur.CurrencyID = s.CurrencyID
            AND cur.LanguageCultureCode IN (SELECT InvariantLanguageCultureCode
                                            FROM   #temp_InvariantLanguageCultureCode)
       JOIN dbo.translation_tenant_Job_Zone_Link_Type jz
         ON jz.JobZoneLinkTypeID = s.JobZoneLinkTypeID


Eliminating files that are completely contained within other files

It looks like you want to filter out the dupes, so let's apply that to self.files first.

noDupeFiles = self.files # no dupes at the start, so we initialize it to self.files
for a in noDupeFiles:
    for b in noDupeFiles:
        if a != b and a.isbetter(b):
            b.isDupe = a.name
            # got to remove b once we make it a dupe file
            noDupeFiles.remove(b)

This reduces the number of levels from 6 to 4 (since we removed the not x.isDupe checks). Next, we combine for a in noDupeFiles and for b in noDupeFiles with the help of itertools.permutations.

noDupeFiles = self.files
for a, b in itertools.permutations(noDupeFiles, 2):
    if a != b and a.isbetter(b):
        b.isDupe = a.name
        noDupeFiles.remove(b)

This reduces from 4 to 3 levels while keeping the original logic.

EDIT:

@marcp pointed out that removing elements from the list apparently threw an exception, so here's the new version:

for a, b in itertools.permutations(self.files, 2):
    if not (a.isDupe or b.isDupe) and a.isbetter(b):
        b.isDupe = a.name


You do not provide a testable function that performs the task of returning the desired answer for a specific test case. It is the 'normal number' handling that you intermangled with your test code. The main structure of your program structure should look somewhat like

def fizzbuzz(int):
    #[...]
    return answer

for num in range(1, 101):
    print(fizzbuzz(num))

You are free to do helper functions but you should always provide a complete testable solution.
Completely separate the functionality you want to provide from the tests. even split into different files.


Code that checks if two words are anagrams

The algorithm in isAnagram is far from being efficient.

Consider two strings: each is a letter "a" repeated 1000 times. We will count the occurrences of 'a' in both strings 1000 times - each time getting the same answer. In other words, the worst case complexity is O(len(input)^2).

It's possible to cache the number of occurrences of a given character in a Map while retaining the rest of your current algorithm. This would speed up most cases, but the worst case complexity will still be O(len(input)^2) (consider an anagram where no letter occurs twice, and is a reverse of the first string).

What we could do is something like this:

Iterate once through each string to create a HashMap with the count of each character's occurrences.
If the two maps are equal, we have an anagram. Otherwise, we don't.

The complexity would be O(len(input1) + len(input2)).


Generic implementation of the Quick-Union algorithm with Path Compression

In find() and areConnected(), you should be able to use == rather than .equals() since you are comparing references, not contents.

Your find() loop is a bit inefficient:

You do components.get(component) once during the while condition test, and again during path compression.
You do components.put(component, …) during path compression, then immediately lookup components.get(component) to advance the loop.

The remedy is to introduce two temporary variables, which I call parent and grandparent.

I've chosen to write it as a for loop with side-effect assignments, but of course you can choose to use a while loop without side-effect assignments.

private T find(T c) {
    // Lookup with path compression
    for (T parent, grandparent; (parent = components.get(c)) != c; c = grandparent) {
        components.put(c, grandparent = components.get(parent));
    }
    return c;
}

connect() calls areConnected(), which performs redundant work.  I suggest…

public void connect(T leftComponent, T rightComponent) {
    Objects.requireNonNull(leftComponent);
    Objects.requireNonNull(rightComponent);

    T leftComponentTree = find(leftComponent);
    T rightComponentTree = find(rightComponent);

    if (leftComponentTree == rightComponentTree) {
        return;     // Already connected
    }

    …
}


Find sub-list index with the closest to a given number sum

Ah ha!  Your example output showed the result 6 8.  Using 1-based indexes (common in certain programming challenges), server_lst had in that sub-list the values [6, 7, 8] whose sum is 21, which is close to the target value of 23.  I was looking at total < c_power, and thought I was looking at a bug since it would be ignoring a sub-list that totalled exactly 23 as too large.
Your "very simple input" is actually confusing, since server powers and indices are not distinct values.  Similarly, the sorted order gives no clear indication of whether 0-based or 1-based indices are returned.
The lack of good comments, an inaccessible problem statement, and confusing code made it hard to tell what the code was intended to do, which made "reviewing the code" a difficult and error-prone task.
Now that I understand what is going on, let's do both: review the code and optimize it.

Code Review
Naming
Your functions and variables are a mix of understandable names (num_of_cases, and num_of_servers) and completely opaque names that don't convey any meaning (execute, and mf).
Globals
Global variables have their place.  This isn't it.
The function servers returns nothing, but calls out total and j as global variables it will be reading and writing.  It turns out that it is actually modifying server_total and server_index as well.
More likely that not, the total and j variables need not have been global, and could simply have been initialized to zero at the start of the function.  Except that if the loop inside servers reaches the end of the loop without exceeding c_power, then j and total are not cleared, and the next call to servers will continue where they left off.  Was this intentional?  Some kind of wrap-around?  It doesn't seem likely, since the starting point k on the next call is not the start of the list, so odds are this is actually a bug.
Unnecessary parameters and variables
    def execute(server_lst, k):
        for i in range(len(server_lst)):
            k = i
            servers(server_lst, k)

What is the point of k?  Both of them.
The execute function requires a k argument, but whatever value is given will be ignored, overwritten by k = i before it is ever used.
Inside the for loop, the value of i is stored in k.  Then, neither I nor k is modified inside the body of the loop, nor used outside of the loop.  i == k remains true as long as both variables are in scope.  Which begs the question of: why use k instead of i?
Don't define functions inside of loops
This one can really result in strange behaviour.
for _ in range(2):
    try:
        f()
    except NameError:
        print("f() didn't exist")

    def f():
        print("Hello world")

Output:
f() didn't exist
Hello world

Write for testing
If you structured your code as a function which solved the problem, and used a main guard to run the code when submitted to the programming challenge site ...

def find_minimum_power_sublist(server_powers, required_power):
    # ... implementation omitted ...
    return start, end

def main():
    num_cases = int(input())

    for case in range(1, num_cases+1):
        num_servers, required_power = map(int, input().split())
        server_powers = list(map(int, input().split()))

        start, end = find_minimum_power_sublist(server_powers, required_power)
        print('Case #{}:'.format(case), start, end)

if __name__ == '__main__':
    main()

... then you could write a test program which runs sample cases, something like:
from solution import find_minimum_power_sublist

def test(test_name, powers, required_power, expected):
    actual = find_minimum_power_sublist(powers, required_power)
    if expected == actual:
        print(test_name, "passed.")
    else:
        print(test_name, "failed!  Expected:", expected, actual)

def run_tests():
    test("1-10", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 23, (6, 8))
    # ... more test cases here ...

if __name__ == '__main__':
    run_tests()

There are test frameworks which make testing easier.  Look into pytest, unittest, and doctest.  Those will get you started, but there are many others you can try.
Optimization
Partial Sums
Whenever you see a problem where you are adding up a sequence of numbers, starting and ending at different points, you should stop and ask if there is a better way.
In your example, you have the numbers 1 2 3 4 5 6 7 8 9 10, and you first start with 1, then 1+2, then 1+2+3, and so on, until you arrive at the total of 1+2+3+4+5+6+7 or 28.  Then you reset and start 2, 2+3, 2+3+4, and so on until you reach 2+3+4+5+6+7 or 27.  Then you reset and start at 3 and compute 3+4, 3+4+5, 3+4+5+6, 3+4+5+6+7 or 25.  Then you reset and start 4, 4+5, 4+5+6, 4+5+6+7, 4+5+6+7+8 or 30.
How many times have you added 4 and 5 together?  Or phrased a better way, how many times have you added 5 to a previous sum that included the four term?  Only four times.  Not a lot.  But this is an example with only 10 servers.  You could have one hundred thousand servers and a fairly high power threshold to exceed.  You could be repeatedly add a specific server value to a previous total thousands of times, and since you can have thousands of individual server values, you've got an \$O(N^2)\$ algorithm.
Instead, consider a running total of the values: 1 3 6 10 15 21 28 36 45 55.  We've added the server value to the previous total exactly once.  From that list, you can get the sum of any sublist of servers.  For instance the sum of server values from index 6 to index 8 would be the sum of server values up to index 8, 45, less the sum of server values up to index 5, 21.  45-21=24.  After processing the list of N servers, doing a total of N additions, you can get the sum of any sublist with at most one subtraction!
As exciting as this sounds, this hasn't actually improved anything.  Using the same steps above, algorithm would still start with 1-0, 3-0, 6-0, 10-0, 15-0, 21-0, 28-0, then reset to 3-1, 6-1, 10-1, 15-1, 21-1, 28-1, and then reset to 6-3, up to 28-3, then reset to 10-6 up to 36-6, and so on.  Instead of doing one addition per loop step, we're doing one subtraction per loop step.
Why reset to the beginning?
After adding the server power values until you exceeded the requirement, why reset the sequence and walk up to the threshold again?  Why not simply advance the starting point of the sublist until the threshold is no longer reached?

We move the end-point forward until the difference is greater than or equal to the requirement: 1-0, 3-0, 6-0, 10-0, 15-0, 21-0, 28-0.
Then we walk the start-point forward until we dip below the requirement: 28-1, 28-3, 28-6.
Then we return to walking the end-point forward until the requirement is met again: 36-6.
Then we return to walking the start-point forward: 36-10, 36-15.
Walk end-point forward: 45-15.
Walk start-point forward: 45-21, 45-28.
Walk end-point forward: 55-28.
Walk start-point forward: 55-36
Walk end-point forward: end-of-list

More concisely,

While the total power requirement is not satisfied,

walk the end-point forward

While the total power requirement is satisfied,

If total power is smaller than the smallest found so far:

update the smallest found so far, and memorize the start and end points.

walk the start-point forward

Note we're only walking the start-point and end-point forward through the list once.  This is \$O(N)\$.
Running totals
You don't have to precompute and store the running totals.  You could just keep two running totals as you move the starting point and ending point forward.
You don't even need two totals.  Just add or subtract from a single running total.  Or consider the total a surplus, and initialize it with the negative of the power requirement.  When surplus >= 0, the power requirement is satisfied; when surplus < 0, the power requirement is not satisfied.


Here is my slightly "mathematical" version of the function you have posted:

var checkPositionOnLoad = function (e) {
    var currentPos = 0;
    var listItem = document.getElement('li.current');
    var currentSelected = $('list').getChildren('li').indexOf(listItem) + 1;

    currentPos = -300 * (Math.floor((currentSelected + 2) / 3) - 1);

    $('list').setStyle('left', currentPos);
};

I will try to explain how I got to that succinct version.

I removed the duplication and wrote the function as follows:

var checkPositionOnLoad = function (e) {
    var currentPos = 0;
    var listItem = document.getElement('li.current');
    var currentSelected = $('list').getChildren('li').indexOf(listItem) + 1;

    if (currentSelected <= 3) {
        currentPos = -300 * 0;
    }
    if (currentSelected == 4 || currentSelected == 5 || currentSelected == 6) {
        currentPos = -300 * 1;
    }
    else if (currentSelected == 7 || currentSelected == 8 || currentSelected == 9) {
        currentPos = -300 * 2;
    }
    else if (currentSelected == 10 || currentSelected == 11 || currentSelected == 12) {
        currentPos = -300 * 3;
    }
    else if (currentSelected == 13 || currentSelected == 14 || currentSelected == 15) {
        currentPos = -300 * 4;
    };

    $('list').setStyle('left', currentPos);
};

Then I realized you want to figure where a given selected element falls (in which group of triplets that is {1, 2, 3} {4, 5, 6}, etc..). I played around and came up with a mathematical formula:

Math.floor((i + 2) / 3)

This basically tells you that for i = 7, the selected element falls in the third group {7, 8, 9} which is the third triplet after {1, 2, 3} and {4, 5, 6}

And the left property can be set using:

var currentPos = -300 * (Math.floor((i + 2) / 3) - 1); // (-1 to make it zero-based index)

And that's it.


I would think that you would want to decouple the logic you use to determine what localization to display from the logic you are using to actually render the hreflang links in HTML.

With your current approach, you are going to get into a serious mess as you try to localize additional pages in your application.

You would need to hard-code similar links to what you have shown across every page. You would also need to maintain separate hard-coded versions for each page to show the slight variations in these links based on which page the user is currently on.  For example, if user is on fr page, they should not see alternate hreflang link for fr.

You also probably need to be thinking about generating an appropriate canonical URL tag as part of this same logic.

Also, over time, you may find the need to send hreflang hints in HTTP headers instead of in HTML <head> element.  By decoupling your logic for determining which localizations settings are applicable for a page (more of a routing concern), from how you convey that information to the browser/spider (a display concern), you can make you logic more re-usable across your application.

If you do not already have a central class or library of classes that handle localization logic for your application, you should strongly consider this.

I think what you should be striving for is a usage pattern like the following in your display context.

HTML link example:

<head>
    <!-- other header elements -->
    <?php $localization->displayAltLangLinks(); ?>
</head>

Header example:

<?php
// PHP application bootstrapping here

// send headers
$localization->setAltLangHeaders();

// page output follows

Here I have shown a theoretical Localization class/object where you could encapsulate your logic related to: current localization being requested, localization to be served, outputting localization info to browser, etc.

I think you need a better strategy for determining what language is being requested.  Relying on $_SERVER['REQUEST_URI'] will likely make your app fragile to user input.  For example,  what if I used URI of /PRICING/ in browser?  Your current code breaks.  What if I put /es/pricing/?  Your code would be triggered even though no localization would be served, when perhaps a 404 should be returned, or even a 301 to default page.

You really need to think about handling the logic around URI rewriting/redirecting at the web server and/or application bootstrap level.  A common pattern in providing the type of URI's you are looking to use it to put in a rewrite at the web server level to redirect something like:

/fr/pricing/

to

/* for individual PHP scripts */
/pricing.php?lang=fr

/* for front-controller application with central routing */
/index.php?lang=fr

This allows you to pass the language requested as a parameter to your script.  Also, if the language segment of the URI doesn't match the languages your application supports perhaps the request falls through your rewrite rules and generates a 404 or 301 redirect depending on how you want to handle these requests.

By handling localization settings early in the response processing cycle you could also do things like look at the user's browser Accept-language request headers, any user preferences settings (cookies, session settings, use preferences stored in database, etc.), to determine when localization should be rendered and performing appropriate redirects for those users.

So to summarize:

Handle localization settings and routing for the page much earlier in response process than at display time.
Dynamically generate these link  tags(and probably canonical tag) in response to what localizations are available for the route as well and what current requested localization is.


An implementation for the double factorial

The recursive solution

The z local variable, you can just return directly.

The else could be dropped, as the if before it returns from the function.

Adding some doctests would be useful.

def semif_r(n):
    """
    >>> semif_r(5)
    15
    >>> semif_r(6)
    48
    >>> semif_r(25)
    7905853580625
    """
    if n == 0 or n == 1:
        return 1
    return n * semif_r(n - 2)

The iterative solution

No need to declare N up front. You could declare and initialize when you need it.

VAL is unnecessary, whenever its value is referenced, it's equal to N, so you could use N instead of VAL everywhere.

The start value of a range is 0 by default, so you don't need to specify that explicitly.

In n / 2, you're counting on that integer division will occur with truncation. In Python 3 there is a separate operator // for this.
It's good to make your code ready for Python 3, by using //, and adding this import:

from __future__ import division

The logic in the two range loops are almost the same. It would be good to extract that logic to a helper function.

As with the recursive implementation, doctests would be nice.

Note that in this code:

elif n%2 == 1:
    # ...

elif n%2 == 0:
    # ...

There, the 2nd elif could be replaced with a simple else,
since if n % 2 != 1, then it must be inevitably 0.

Putting it all together:

def semif_i(n):
    """
    >>> semif_i(5)
    15
    >>> semif_i(6)
    48
    >>> semif_i(25)
    7905853580625
    """
    if n == 0 or n == 1:
        return 1

    def multiply(coef):
        val = 1
        for i in range(n // 2):
            val *= (2 * i + coef)
        return val

    if n % 2 == 1:
        return n * multiply(1)

    return multiply(2)

Coding style

Please follow PEP8, the coding style guide (see the writing style in my sample implementations).


Check Three Dom Elements to See if they are empty or not and return detailed result

After speaking with some friends, this is seen as the best solution. One adjustment to the return values was required however; change the casing from camel case to title case. I am also using constants to make sure that return values can be consistently used properly.
/**
 * Check the three dom elements to see if they are empty or not and return detailed result.
 * @param {jQuery|HTMLElement} area Area input field.
 * @param {jQuery|HTMLElement} city City input field.
 * @param {jQuery|HTMLElement} text Text input field.
 * @return {string} Detailed result of which input fields are empty.
 * If all are filled, returns "all".
 * If none are filled, returns empty string.
 */
export const processValues = (area, city, text) => {
    const a = (area.val()) ? 'Area' : '';
    const c = (city.val()) ? 'City' : '';
    const t = (text.val()) ? 'Text' : '';
    if (a !== "" && c !== "" && t !== "") {
        return "all";
    } else {
        return a + c + t;
    }
};

export const ALL = "all";
export const AREA_CITY = "AreaCity";
export const AREA_TEXT = "AreaText";
export const AREA = "Area";
export const CITY_TEXT = "CityText";
export const CITY = "City";
export const TEXT = "Text";
```


Class that represents starting points and endpoints of a game

You can create EndPoint as a more specific version of MajorPoint and move the extra logic there.

var MajorPoint = function(game, x, y, state, callback, callbackContext) {
  Phaser.Sprite.call(this, game, x, y, 'start-end', 0);
  this.state = state;
  this.anchor.setTo(0.5, 0.7);
  this.scale.setTo(0.5, 0.5);
};

MajorPoint.prototype = Object.create(Phaser.Sprite.prototype);
MajorPoint.prototype.constructor = MajorPoint;

var EndPoint = function(game, x, y, state, callback, callbackContext) {
  MajorPoint.call(this, game, x, y, 'start-end', 0);

  //If end is not reachable, hides this object.
  //If end is reachable, enables input for this object.
  this.frame = 1;
  if (!game.data.isEndReachable()) {
    this.visible = false;
  } else {
    this.inputEnabled = true;
    if (callback !== undefined) {
      this.events.onInputDown.add(callback, callbackContext);
    }
  }
};

EndPoint.prototype = Object.create(MajorPoint.prototype);
EndPoint.prototype.constructor = EndPoint;

If callback is only valid when it's omitted or a function, you can drop the !== undefined and just test that it's truthy. This will avoid setting an invalid callback when someone accidentally passes null.

if (callback) {
  ...
}


Speeding up string splitting in Rcpp/Cpp

Remove unnecessary steps

for (int i = 0; i < field_number - 1; ++i)
{ /*read discard*/ }
double value;
// read the needed value now

This will make sure that it will not do unnecessary steps if the value needed is the very first one.

Do not copy around

I believe Rcpp would provide some way to access underlying char*. That can be used to construct std::string_view, or use the char* directly.

Use better standard library functions

My first candidate is famous (infamous) function called std::from_chars. It was accepted in C++17, but the support for that is only available with VC++'s standard library (I'm as surprised as you are, the reader, though getting FP parsing right is very hard). Basically it ignores all of the limitations of standard streams, from buffer structures to locales.

The second candidate would be std::strtod, or some such. Notice that std::stod is not a good alternative, because it requires copying parts of the string.

Going beyond standard

One of the good options is fmtlib. It has convenient interface, and is actively developed. Part of it is event coming to standard library, but unfortunately not the one we are interested in.

I'm not sure how faster it will get, but perhaps Boost.Spirit may be a good candidate. It will certainly be strong spirits to your compiler.

Facts

Of course, the benchmarks will tell which way is better. May be everything I've told is heresy.

Alternative implementation

#include <charconv>
#include <string_view>
#include <cmath>

double strparse(std::string_view s, int field, int a, int b) {
    double candidates[3];
    auto format = std::chars_format::fixed;
    auto start_point = s.data();
    auto end_point = s.data() + s.size();
    switch (field) {
    case 0:
        start_point = std::from_chars(start_point, end_point, candidates[0], format);
    case 1:
        start_point = std::from_chars(start_point, end_point, candidates[1], format);
    case 2:
        start_point = std::from_chars(start_point, end_point, candidates[2], format);
    }

    double ad = a;
    double bd = b;
    return std::abs(ad + bd - candidates[field]);
}

Well, here you have it. No copying around, manual loop unroll to prevent unnecessary steps, exact flags to maximize performance in standard library calls.

Godbolt link.

Unfortunately I do not have convenient access to a windows machine to test the implementation.


The error from ioutil.TempFile is unhandled, should also return err since everything after it won't work if the temporary file
couldn't be created.
The strings.Contains check is definitely the least preferred option
to check for the kind of error.  If at all possible avoid it since
it's actually fairly easy for that string to change with, say, a
library upgrade without any notice, which would break the logic here.
Same with status.Info.Status.String() == release.StatusFailed - are
you sure it can't just be compared without the String() conversion?
tmpfile.Name() is used twice, could already be moved to a variable.
In fact, one of tmpfile and kcfgFilePath is redundant, I'd suggest
directly assigning to kcfgFilePath.
IMO new is obsolete and could very well be replaced by a regular
variable declaration.
statusAction could be inlined.

Actually it would be great if the imports were mentioned, that would
give readers a chance to find the actual signatures and such.  Without
that I'll leave it at those points.
Apart from these details it looks okay, though at some point you might
want to refactor things into smaller functions to bring a little order
into it.  Right now it's still a rather long block of code.  E.g. it
might be worth moving the inner part of the loop into a new function.
Or creating functions for each "action" that's currently only marked
with a comment, say runInstall, runUpgrade.  The temporary file bit
at the start could also very well be its own function (keeping the
os.Remove call at this level of course).
Edit: As requested to elaborate on the second point, it's better to do a
direct comparison of error values instead of string comparisons, since
they're just values too, this will be faster and not depend on string
values which might change in unexpected ways, like so:
// this is defined in the helm API
var ErrReleaseNotFound error = errors.New("release: not found")

// ...

// some time later, we get an error
{
    statusAction := action.NewStatus(ac)
    status, err := statusAction.Run(releaseName)
    if err != nil {
        if err == driver.ErrReleaseNotFound {
            releasePresent = false
        } else {
            return err
        }
    }

    // ...
}

But, actually, we should all probably start using
errors.Is so that even nested
errors would be correctly handled:
// ...
if errors.Is(err, ErrReleaseNotFound) {
    releasePresent = false
} else {
    return err
}
// ...


First is variable names. Most of them make sense... except ac. Everything is so verbose, but ac doesn't really make sense at first glance. One needs to read the code to find out ac is actually a timer ac = setTimeout(_f,interval);.

Next thing I notice is that all your actions seem to do print. The problem here is that the functions are implicitly changing state by calling print. That is, calling out any of the functions implicitly changes the value of displayMinutes, displaySeconds as well as some element's text. Best if add, subtract and the others actually just add and subtract. Leave the printing out of them, and do it separately.

displayMinutes = (minutes.toString().length == 1) ? "0" + minutes : minutes;  //ternary operator: adds a zero to the beggining
displaySeconds = (seconds.toString().length == 1) ? "0" + seconds : seconds;  //of the number if it has only one caracter.

Looks like you're trying to convert numbers into strings padded by zeroes, if needed be. A neat trick to convert numbers into strings is to just add a string before it. Type coercion does the rest for you. Then you can use slice with a negative index to slice starting from the end of the string.

// We assume all numbers are at least 1 digit. Thus we need one zero and 2
// digits to slice off from the right. If it were 3 digit padded numbers,
// we'd need two zeroes and 3 digits to slice off from the right.
var paddedTwoDigitNumber = ('0' + number).slice(-2);

Now I notice your timer relies on setTimeout to count. There are 2 problems here. First, native JS timers aren't precise. That means putting 1000ms delay guarantees that it executes at least 1000ms, but not exactly at 1000. This means, every "tick" may drift off a few ms. The next problem is that you're using setTimeout for each tick. The problem is that internally, it keeps queueing a function as a callback, and every execution, it gets popped off.

A better approach would be to use setInterval, so that you only queue your tick once and you don't have to rely on some recursion call. Next is instead of relying on the timer ticks, you should get the real time using Date.now(). Every timer tick, you store the time andyou check the real time, if a full second has elapsed since last timer tick. Only then do you update your timer. There will always be "drift" on each interval, so you should take that into account as well.

Not sure if you should pepper your variables in "InSeconds" and that's because I suggest you should work with milliseconds in JS. Most Date functions return millisecond time. Also, it's easier to convert milliseconds to seconds (a matter of division) rather than convert seconds to milliseconds (a code overhaul).

I notice that your code relies on jQuery (I see $(element).text()). I think it's best that either jQuery stays out of it (your timer is merely a timer library) or you make it a jQuery plugin. Either way is fine.

If you go with the pure timer route, I suggest you let Timer be an instance of an event emitter class (There's tons of them online. I even created one in 21 lines.) That way, your timer can just emit events when interesting things happen (on start, on stop etc.) and the DOM manipulation code is outside the Timer. You could just have something like timerInstance.on('complete', fnToExecuteOnComplete). jQuery is no longer a concern for the Timer code. It's external.

If you make it a jQuery plugin, it's a matter of doing the following to your code. There are a lot of approaches in building jQuery plugins online. Find one that suits your taste.

$.fn.timer = function(){
  // "this" here is a reference to the element, not wrapped in jQuery.
  // Then put your operations here.
}

// To use, it would be something like
$(element).timer({ mins: 60, seconds: 00 });

// To operate
$(element).timer('add', 1, 2);


MySQLi query and error handling for select, insert, and update

Sorry to say, but you are doing it all wrong, from getting a mysqli connection to your ideas on the error reporting. I've got an article on this latter topic, Error reporting basics but it is rather long, so here is a gist:

On a live site, not a single word from the error message should be shown to a site user. Because:

for the casual user it is pretty cryptic and confusing.
it it essentially useless for the site programmer/admin as they likely won't be browsing the site at the moment and will have no idea that error has been occurred.
the information provided in the error message extremely useful for a potential hacker, as it provides them with the feedback for their actions and may leak some sensitive information on the site.

Instead, the error message should be logged for the future reference, whereas just a generic error page should be shown.

From this you can tell that your idea of showing the complete error message to the site user is essentially flawed. Instead of manually handling every single error message, you should just let it go, and then create a handler that will dispatch the error message according to the current mode.
The idea of adding the query type is rather useless as well. Given PHP will always provide you with the file name and line number where the error occurred, you can always find the problem query and thus learn its type.
Now, to the code review.
First, I would put mysqli into Exception mode, to make it report all errors automatically. To do so, I will add the following line to mysqli connection code:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

So, given you are using a function to get the mysqli connection, it could be written this way
function DB_Connect {
    static $conn;
    if (!$conn) {
         mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
         $conn = mysqli_connect('your credentials');
    }
    return $conn;
}

this function will ensure that we are using only a single connection and also will turn Exception mode for mysqli
Then I would make it only one function,
function DB_query($Query) {
    $DB_Connection = DB_connect();
    $result = mysqli_query($DB_Connection, $Query);
    return $result;
 }

with such a function you'll be able to perform any query and also get any result type you need. For example,
// select query returns an array with rows
$users = DB_Query("SELECT * FROM users")->fetch_all();

// update query returns the number of rows affected
$rows_updated = DB_Query("UPDATE users SET active=1")->num_rows();

However, there is another drawback. In fact, for such a function it is mandatory to support prepared statements. Otherwise it will be wide open to SQL injection. Therefore, we will change it to make it allow variables used in the queries
function DB_query($query, $params = [])
{
    $conn = DB_connect();
    if ($params)
    {
        $stmt = $conn->prepare($query);
        $types = str_repeat('s', count($params));
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
    } else {
        $result = mysqli_query($conn, $query);
    }
    if ($result)
    {
        return mysqli_fetch_all($result);
    } else {
        return mysqli_affected_rows($result);
    }
}

This function will return you an array of rows for SELECT and other queries that return any data, and the number of affected rows otherwise. Examples:
$workers = DB_query("SELECT * FROM workers WHERE salary >= ?",[$salary]);

DB_query("INSERT INTO workers SET name=?, salary=?",[$name,$salary]);
$id = DB_connect()->last_insert_id();

As for the $NAV_DB_Failure - create the error handler like this
set_error_handler("myErrorHandler");
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    error_log("$errstr in $errfile:$errline");
    header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
    readfile("NAV_DB_Failure.html");
    exit;
}

and this file will be shown in case of any error, while keeping the error message for your eyes only.


Algorithm maths quiz + write to a text file

A few advices :

Python has a code style called PEP8. It is a worth reading. Also, you'll find various tools to check that your code is PEP8-compliant like pep8. You'll also find various other tools to check the quality of your code : pyflakes, pychecker, pylint, etc.
avoid useless comments. It can be tempting to comment every line you write as you start programming. However, what you are doing adds more noise that it actually helps. As a rule of thumb, "Code Tells You How, Comments Tell You Why". Also, comments are easy to get out of sync with the code (you have places where your code says "25" and the comment says "10", how confusing).
you can add an argument to input so that you don't have to call print before.
your while question < 10 loop looks like it could/should be a for loop : for question in range(10): (and no need for an initialisation nor for a incrementation in the loop). Also, as a side-note, the convention in Python is to use _ for throw-away values, thus, the loop could be written : for _ in range(10):.
you should try to use the with keyword whenever you handle files. If you do so, you don't have to call close explicitly.
you should try to ask yourself if your variable describe how you use it. For instance, class_name is a proper name for what you do at the beginning. However, it doesn't sound like a proper filename. You could simple create a new variable : filename = class_name + ".txt"
avoid useless tests : in elif viewscore != "yes".lower(), the condition will always be true. You could simply write else.
calling lower() on "yes" doesn't seem really interesting does it ?

Now, for more "complicated" advices.

You can try to split the logic in small reusable units like functions (or classes). For instance, you could write :

def get_int_input():
    while True:
      try:
        return int(input())
      except ValueError:
        print ("That is not a valid answer")

Instead of having some code to handle the different possible operations, you could have a structure containing the relevant information : the symbol to be printed and the corresponding operation. You could use a list of tuple to store everything and then, it's easy to pick one at random and use it :

import operator

OPERATIONS = [
    (operator.add, "+"),
    (operator.mul, "*"),
    (operator.sub, "-")
    ]

for _ in range(10):
    num1 = random.randint(1,25)
    num2 = random.randint(1,25)
    op, symbol = random.choice(OPERATIONS)
    print("What is", num1, symbol, num2)
    if get_int_input() == op(num1, num2):
        print("Correct")
        score += 1
    else:
        print("Incorrect")

If you ever need to add one, it's quite easy.

It is also a good habit to use a if __name__ == '__main__': guard.

Similarly to what we've done to get an integer input, we can define a function to get a boolean input.

The final code looks like :

import random
import operator

OPERATIONS = [
    (operator.add, "+"),
    (operator.mul, "*"),
    (operator.sub, "-")
    ]

NB_QUESTIONS = 10

def get_int_input(prompt=''):
    while True:
      try:
        return int(input(prompt))
      except ValueError:
        print("Not a valid input (integer is expected)")

def get_bool_input(prompt=''):
    while True:
        val = input(prompt).lower()
        if val == 'yes':
            return True
        elif val == 'no':
            return False
        else:
            print("Not a valid input (yes/no is expected)")

if __name__ == '__main__':
    name = input("What is your name?").title()
    class_name = input("Which class do you wish to input results for? ")
    print(name, ", Welcome to the OCR Controlled Assessment Maths Test")

    score = 0
    for _ in range(NB_QUESTIONS):
        num1 = random.randint(1,25)
        num2 = random.randint(1,25)
        op, symbol = random.choice(OPERATIONS)
        print("What is", num1, symbol, num2)
        if get_int_input() == op(num1, num2):
            print("Correct")
            score += 1
        else:
            print("Incorrect")

    print("Well done", name, "you scored", score, "/", NB_QUESTIONS)

    filename = class_name + ".txt"

    with open(filename, 'a') as f:
        f.write(str(name) + " : " + str(score) + '\n')

    if get_bool_input("Do you wish to view previous results for your class"):
        with open(filename, 'r') as f:
            print(f.read())
    else:
        input ("Press any key to exit")


I know this is not 100% spot on, but you should be able to take something from it and apply it in your own repository.

Here's a piece of code I use for one of my EF repositories, which I find very useful. I use a lot of Razor templating which won't lazy-load entities, so whenever I need to eagerly-load, I just include whatever relational entities I need before passing it to razor.

    public IQueryable<T> FindByInclude<T>(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] include) where T : class
    {
        IQueryable<T> query = _context.Set<T>().Where(predicate);

        foreach (var item in include)
        {
            query = query.Include(item);
        }

        return query;
    }

Example:

var user = Repo.FindByInclude<User>(z=>z.Name = "Joachim Nordvik", "Address","Properties.Extended");

Now both the Address relation and Properties.Extended relations are eagerly loaded.


Overall, this seems to be some well-crafted code that is clear, concise and doesn't leak memory.  Here are some things that may help you improve your code.

Use the appropriate #includes

In order to compile and link, this code requires the following two lines:

#include <stdio.h>
#include <stdlib.h>

For the program to be complete, these should be listed, too.

Fix node deletion

There is a problem with the remove_item code.  In particular, if we construct a tree with just three items and then attempt to remove the root, the current code causes a crash because the left subtree is added before the call to remove_min(r). To fix that, simply swap the lines in remove_item so that this part of the code looks like this:

    node* m = find_min(r);
    m -> right = remove_min(r);
    m -> left = l;

This is likely to be the problem that causes the time limit to be exceeded.


1. Review

There are no docstrings. What do these functions do?
The Python style guide says, "limit all lines to a maximum of 79 characters." If the code followed this recommendation, then we wouldn't have to scroll it horizontally to read it here.
The board is not represented consistently. Looking at printBoard, it seems that each cell is represented by a list [a, b] where b is False if the cell is empty, and True if it contains the number a. But the initialization of the board in attemptBoard looks like this:

board = [[None for _ in range(9)] for _ in range(9)]

which represents empty cells as None, so that if I try to print this board, I get:

TypeError: 'NoneType' object is not subscriptable

I would recommend using a consistent board representation. In this case I think it makes more sense to use None for an empty cell and a number for a full cell (rather than a list). That's because (i) None and small numbers don't need any memory allocation, whereas a list needs to be allocated; (ii) testing a None or a number is quicker than testing a list.
In printBoard you have very repetitive code:

print ("|| {} | {} | {} || {} | {} | {} || {} | {} | {} ||".format(
            line[0][0] if line[0][1] else ' ',
            line[1][0] if line[1][1] else ' ',
            line[2][0] if line[2][1] else ' ',
            line[3][0] if line[3][1] else ' ',
            line[4][0] if line[4][1] else ' ',
            line[5][0] if line[5][1] else ' ',
            line[6][0] if line[6][1] else ' ',
            line[7][0] if line[7][1] else ' ',
            line[8][0] if line[8][1] else ' ',))

This can be rewritten using a loop:

print("|| {} | {} | {} || {} | {} | {} || {} | {} | {} ||"
      .format(*(number if full else ' ' for number, full in line)))

or, after simplifying the board representation as recommended above:

print("|| {} | {} | {} || {} | {} | {} || {} | {} | {} ||"
      .format(*(cell or ' ' for cell in line)))

The nested loops:

for i in range(9):
    for j in range(9):

can be combined into one using itertools.product:

for i, j in itertools.product(range(9), repeat=2):

The variable loopStart is never used.
Instead of this complex while loop:

x = -1
while board[i][j] is None:
    x += 1
    if x == 9:
        #No number is valid in this cell, start over
        return None
    checkMe = [checking[x],True]

    # ... loop body here ...

    #If we've reached here, the number is valid.
    board[i][j] = checkMe

write a for loop with an else:

for x in checking:
    # ... loop body here ...

    # If we've reached here, the number is valid.
    board[i][j] = x
    break
else:
    # No number is valid in this cell, start over.
    return None

The column check:

checkis = False
for checkRow in board:
    if checkRow[j] == checkMe:
        #If it's already in this column
        checkis = True
if checkis: continue

can be simplified using the built-in function any:

if any(row[j] == checkMe for row in board): continue

The code for checking against other cells in the 3×3 block is very repetitive:

if i % 3 == 1:
    if   j % 3 == 0 and checkMe in (board[i-1][j+1],board[i-1][j+2]): continue
    elif j % 3 == 1 and checkMe in (board[i-1][j-1],board[i-1][j+1]): continue
    elif j % 3 == 2 and checkMe in (board[i-1][j-1],board[i-1][j-2]): continue
elif i % 3 == 2:
    if   j % 3 == 0 and checkMe in (board[i-1][j+1],board[i-1][j+2],board[i-2][j+1],board[i-2][j+2]): continue
    elif j % 3 == 1 and checkMe in (board[i-1][j-1],board[i-1][j+1],board[i-2][j-1],board[i-2][j+1]): continue
    elif j % 3 == 2 and checkMe in (board[i-1][j-1],board[i-1][j-2],board[i-2][j-1],board[i-2][j-2]): continue

The reason you go to this trouble is to avoid testing against board[i-1][j] and board[i-2][j], which you know would be useless, because you already tested these cells when you checked the column. But in fact that's a false economy. You avoid an unnecessary test, but at the cost of a lot of extra code. It turns out to be just as fast, but a lot simpler, to test all the entries in previous rows of the block, like this:

i0, j0 = i - i % 3, j - j % 3 # origin of 3x3 block
if any(x in row[j0:j0+3] for row in board[i0:i]):
    continue

The code only works for 9×9 Sudoku grids made up of 3×3 blocks. But there's nothing special about the numbers 3 and 9 here: the algorithm would be essentially the same for 2 and 4, or 4 and 16. So why not make the code general?

2. Revised code

This isn't any faster than the original code, but it's a lot shorter and simpler, which makes it a better place to start when speeding it up:

import itertools
import random

def attempt_board(m=3):
    """Make one attempt to generate a filled m**2 x m**2 Sudoku board,
    returning the board if successful, or None if not.

    """
    n = m**2
    numbers = list(range(1, n + 1))
    board = [[None for _ in range(n)] for _ in range(n)]
    for i, j in itertools.product(range(n), repeat=2):
        i0, j0 = i - i % m, j - j % m # origin of mxm block
        random.shuffle(numbers)
        for x in numbers:
            if (x not in board[i]                     # row
                and all(row[j] != x for row in board) # column
                and all(x not in row[j0:j0+m]         # block
                        for row in board[i0:i])):
                board[i][j] = x
                break
        else:
            # No number is valid in this cell.
            return None
    return board

3. Backtracking

If attempt_board finds that there are no valid numbers for some cell, then it throws away all its work and starts all over again from the beginning. But all that work is not necessarily invalid: most likely the mistake was made only in the last few steps, and so if the algorithm were to go back a little bit and try some different choices, then it would find a solution. This approach is known as backtracking.

Backtracking is easily implemented by using recursion:

def make_board(m=3):
    """Return a random filled m**2 x m**2 Sudoku board."""
    n = m**2
    board = [[None for _ in range(n)] for _ in range(n)]

    def search(c=0):
        "Recursively search for a solution starting at position c."
        i, j = divmod(c, n)
        i0, j0 = i - i % m, j - j % m # Origin of mxm block
        numbers = list(range(1, n + 1))
        random.shuffle(numbers)
        for x in numbers:
            if (x not in board[i]                     # row
                and all(row[j] != x for row in board) # column
                and all(x not in row[j0:j0+m]         # block
                        for row in board[i0:i])):
                board[i][j] = x
                if c + 1 >= n**2 or search(c + 1):
                    return board
        else:
            # No number is valid in this cell: backtrack and try again.
            board[i][j] = None
            return None

    return search()

I find that this is about 60 times faster than the original code.

4. Algorithm X

There's a reformulation of Sudoku in terms of the "exact cover" problem, and this can be solved using Donald Knuth's "Algorithm X". See this blog post of mine for a detailed explaination of the how this algorithm can be used to solve Sudoku, and see this post on Code Review for an implementation in Python.


Small issues:

Personally I'd indent things in between by curly braces
I'd use string.Empty instead of ""
I'd probably put my default public properties before my custom ones

As a higher level question, do you need to use an XML settings file with an explicit lock? Could you not use a custom section in .config file of some kind?


In think you can improve the render by following the React philosofy of writing reusable components.

If you look closer at your code:

render() {
    const {hours, minutes, seconds, ampm} = this.state.currentTime;
    return (

            {hours == 0 ? 12 : (hours > 12) ? hours - 12 : hours}:
            {minutes > 9 ? minutes : `0${minutes}`}:
            {seconds > 9 ? seconds : `0${seconds}`} {ampm}

    )
}

Here you have duplication in printing a digit. You have it with minutes and seconds, but I think hours should be printed the same way too.

You can introduce a display component as a plain function:

const PrintDigit = ({ digit }) =>
    (<React.Fragment>{digit < 9 && '0'}{digit}</React.Fragment>)

The function have props as an input parameter, that here I spread with a variable digit to document the only props expected from the component.

So your render() method could be rewritten:

render() {
    const {hours, minutes, seconds, ampm} = this.state.currentTime;
    return (

            <PrintDigit digit={hours === 0 ? 12 : hours % 12} />:
            <PrintDigit digit={minutes} />:
            <PrintDigit digit={seconds} /> {ampm}

    )
}

Is not that big improvement, but as your code is an exercise to learn React, I think is good to start thinking in that way.

The functional component could stay just in the same file of your main component or you can put it in a different file and then import where you need it.


Catch-style unit testing in JavaScript (phase 1)

Overall Design

For such a small amount of code, I find the logic extremely difficult to follow. I understand what is happening at a high level, but it seems every function is responsible for managing everything, and program control bounces around a lot.

As an example, the final function assigned to SECTION has several responsibilities:

Capture the enclosing section and current next task.
Do nothing if this new section should be skipped.
Create a new next task that will either

rerun the test case (if more sections have been added),
run the previous next task (if there is one), or
do nothing.

Add the new section to the enclosing section.

BTW, under what condition does updateSubsection not create a new section? I can see it looks for a section with the same name, but is that supposed/allowed to happen?
Finally, run the new section.

That's way too much work for one nine-line function to do.

As a first step, add a TestCase class (subclass of Section) to own the overall state of running a single test case, and move the logic from the last two functions into it, breaking them up into smaller functions. While test cases are run sequentially, I would move context and nextTask into this new class as I believe they belong to a single test case run.

Names

Most of the variable names are pretty clear, but as I dig into the code some are misleading.

context sounds more like a map of values passed to each section rather than a stack of running sections. I would rename it to reflect that nature, e.g., activeSections.
subsectionsEncountered is a little cumbersome; how about the more standard subsectionCount? And subsectionIndex only tells me it's an index into some container--not why that subsection is special. I'd go with activeSubsectionIndex though I would prefer to store the actual Section instance in it and drop the Index suffix if possible.
You're creating a tree of sections, and parent is more obvious than outer.

Other Thoughts

I'd be tempted to drop the stack of sections (context) in favor of storing just the active section since that's all you need. To pop a completed section off the stack, a) store a reference to the parent section in each section instance and b) assign the parent to activeSection after each section completes.

Finally, you need to handle exceptions so other sections can be run. You should be able to do it once in Section.prototype.run.

On to Phase Two!

I'm very curious to see this in action. With QUnit I am often forced to perform the same actions on the fixture as a previous test did in order to set up the current test. This causes code duplication whereas the whole point of setting up a fixture is to avoid it.

In Java I've been building separate fixture classes that provide methods for setting up common fixture states that can be reused across many tests. While that's helpful, it's not as easy to do in JavaScript.


Recursive Web Scraping with Python Beautiful Soup

There is a simpler way to filter out the "style" links - using a CSS selector with a partial match on the href attribute:

style_urls = {anchor['href'].replace('/style/', '')
              for anchor in soup.select('a[href^="/style/"]')]

where ^= means "starts with".

Here we, of course, lose the check we had on the style name part of the href. If this check is really needed, we can also use a regular expression to match the desired style links directly:

pattern = re.compile('/style/([a-zA-Z0-9\-]*)[^/]')
style_urls = {pattern.search(anchor['href']).group(1)
              for anchor in soup('a', href=pattern)

soup() here is a short way of doing soup.find_all().


Simple input class change with vanilla JS

Review

The biggest critique about the Javascript I have is that collapsedInput could be declared with const because it doesn't get re-assigned.

It is possible that the code in the event listener for the input event could be simplified using classList.toggle().

If there is only one element with class name collapsed then perhaps it would be better to use an id attribute and use document.getElementById() to select it. Those older methods are faster than the querySelector() varieties.

Dramatic simplification

The question contained this text:

  There's probably another way to solve it with pure CSS.

That is correct. One way is to use the required attribute on the first <input> element along with the :valid and :hover pseudo-selectors :

input {
    width: 20px;
    transition: width 1s;
}

input:valid,
input:hover,
.expanded {
    width: 256px;
}

    2 inputs, 1 is collapsed
    the other is expanded

collapsed

    <input type="text" class="collapsed" required>

    expanded

    <input type="text" class="expanded">

Perhaps someday the CSS pseudo-class :blank will be supported by some browsers... If that is the case, then the required attribute wouldn't be needed.


Only a small review

Alignment not guaranteed

temp = (size_t*) ((char*)temp + member_size); attempts to convert a char* to size_t *, yet (char*)temp + member_size is not known to be properly aligned for a size_t*.  Insufficient alignment is undefined behavior.

Detect overflow

As the true product of nmemb * member_size may exceed SIZE_MAX:

if (SIZE_MAX/nmemb > member_size) {
  Handle_Overflow();  // clean-up, return NULL;
}
... =  malloc(nmemb * member_size);

Strange uses of size_t as pointer

// The last member points to NULL *temp = (size_t)NULL; implies something wrong.  If codes needs a pointer, use a pointer, not size_t.  If code needs a size, doesn't use a pointer.  Note that size_t and pointers do not necessarily covert well back and forth.  They might not be the same memory width either.

This use of size_t as a place to encode a pointer is simply broken.  Code needs a new approach.


You could write this code in Java first, it would not be much different from a C++ implementation. It seems that your problem is not the language, but rather the algorithm: E.g. you only update the next pointer, not the prev pointer. The following must be true for every link between two nodes: node->next->prev == node.

Let me try to answer your questions:

The "doubly" part is not required to write something that can be flattened, but it is explicitly asked for so you must maintain it. It will allow you to traverse the list in two directions, instead of just one. This can be valuable in many situations.
The question states that the child pointer is to a list similar to the first list. This means that it can also have child pointers of its own. A recursive solution would be easy to write and easy to understand.
Why do you want a non-recursive algorithm? This is not stated in the question.
I believe you can use any language you like in this forum.