Is this the Clojure way to web-scrape a book cover image?

@abuzittingillifirca made a good point in that you can leave the parentheses off of the -> forms that are just a single element.

html/html-resource is actually quite flexible; it can take a variety of different kinds of arguments, including strings, URLs, input streams, etc. Assuming the url argument to your function is a string, you can take out the java.net.URL. part and just feed url directly into html/html-resource. In fact, I would begin the -> part like this:

(-> (html/html-resource url)
    ...

So (html/html-resource url) is like the "first step" in the threading macro. Less steps makes your code appear simpler and easier to read, just as long as the steps aren't overly complicated.

For the (first) (:attrs) (:src) part, you might consider using get-in. This function comes in handy for navigating nested associative structures like vectors and maps -- it's perfect for something like enlive. You could re-word this part of your code as:

(get-in [0 :attrs :src])

It isn't much shorter than the original, but I think it reads better, and it "feels" shorter because you're only calling one function.

It's probably not very Clojurian to have a ->> macro among the steps to a -> macro. If you have a situation like this, where one of the steps to the -> requires you to put the argument last instead of second, you can do something like (#(str "http:" %)) -- create an anonymous function literal with the % wherever you want the argument to go, and then call it by putting parentheses around it.

So, here is how I would refactor your code:

(defn scrape-book-cover [url image-filename]
  (let [out-stream (io/output-stream image-filename)
        image (-> (html/html-resource url)
                  (html/select [:div.bookcoverXXL :> :div :> :img])
                  (get-in [0 :attrs :src])
                  (#(str "http:" %))
                  (http-client/get {:as :byte-array})
                  :body)]
    (with-open [out out-stream]
      (.write out image))))

EDIT: To answer your question: No, I don't think this function is overloaded. When you simplify like I did above, it doesn't seem too long or complicated.

EDIT 2: Of course, there's nothing stopping you from pulling out the -> part and making it a separate function. It might make your code easier to read. You could call the function something like imgurl->bytes.

(defn imgurl->bytes [url]
  (-> (html/html-resource url)
      (html/select [:div.bookcoverXXL :> :div :> :img])
      (get-in [0 :attrs :src])
      (#(str "http:" %))
      (http-client/get {:as :byte-array})
      :body))

(defn scrape-book-cover [url image-filename]
  (let [out-stream (io/output-stream image-filename)
        image (imgurl->bytes url)]
    (with-open [out out-stream]
      (.write out image))))

Come to think of it, I like this better. If you look at a lot of Clojure code on github, you will see a lot of things broken up into simple helper functions. I suppose it is generally idiomatic in Clojure to break things up in helper functions.

EDIT 3 (5/16/14): Someone just upvoted my answer, which made me remember this code and have a quick re-visit. You could actually further refactor this version of the scrape-book-cover function by taking out the let statement:

(defn scrape-book-cover [url image-filename]
  (with-open [out (io/output-stream image-filename)]
    (.write out (imgurl->bytes url))))


Same function but use different array data

Beyond the repetition in the JS, you've got some repetition across the HTML and JS; I'd avoid having both the array and the empty divs. If you have more divs than you have images in the array, weird stuff starts happening. There's no reason to manually have to manage both of those "lists" when you can just add divs as necessary.

Here's how I might write it, to include that while avoiding the repetition

function randomizeCarousel(selector, images) {
  var i, l, carousel = $(selector);

  function shuffle(images) {
    var i, shuffled = [];
    while(images.length) {
      i = Math.floor(Math.random() * images.length);
      shuffled = shuffled.concat(images.splice(i, 1));
    }
    return shuffled;
  }

  function addImage(src, href) {
    var container = $("
"),
        link      = $("").attr("href", href).appendTo(container),
        img       = $("").attr("src", src).appendTo(link);
    carousel.append(container);
  }

  images = shuffle(images.slice(0));
  for(i = 0, l = images.length; i < l; i++) {
    addImage("/pic/" + images[i][0], "/url/" + images[i][1]);
  }

  carousel.jsCarousel({
    onthumbnailclick: function(src) { load(src); },
    autoscroll:       true,
    circular:         true,
    masked:           false,
    itemstodisplay:   3,
    orientation: 'h'
  });
}

$(function () {
  randomizeCarousel("#carousel1", [...]); // add your 1st array here
  randomizeCarousel("#carousel2", [...]); // add your 2nd array here
  // ... etc.
});


Create a histogram of the lengths of words

Do not be shy on horizontal spacing. Add space after the keywords (e.g. while (, or if (). Insert space into ){.

If you place an opening curly bracket on the same line as if, be consistent with else:

  if () {
      ....
  } else {
      ....
  }

currentWord actually refers to the current word length. Consider renaming.
Instead of testing state == OUT, consider adding a word immediately, as soon as state become OUT:

    if (c == '\n' || c == ' ' || c == '\t') {
        if (currentWordLength < MAXVAL) {
            ++wordLengths[currentWordLength - 1]; {
        } else {
            ++greaterThanMax;
        }
        currentWord = 0;
    }

Notice that with this approach you don't need to maintain state explicitly.
Every output line, except last one, starts with a single-digit number, but the last one starts with 10, and looks unaligned. Consider printing letter count with "%2d".
The greater-than-max line doesn't end with a newline. Some shells (like cmd.exe) automatically add a newline to the last output. Unixish shells do not. On my system an output looks like

....
>10: ==vnp>

Even on Windows, try to redirect your output into a file.

It is usually a good idea to terminate the output with a newline.


Popping from a list in state while a condition is true

You can simplify the code by using span:

  span :: (a -> Bool) -> [a] -> ([a], [a])

  span, applied to a predicate p and a list xs, returns a tuple where
  first element is longest prefix (possibly empty) of xs of elements
  that satisfy p and second element is the remainder of the list

popWhile :: (Char -> Bool) -> StateT String Maybe String
popWhile p = do
    s <- get
    let (xs, ys) = span p s
    put ys
    return xs

Thanks to @bisserlis for the suggestion to use state

popWhile = state . span


How to improve readability of a big lisp function

Superficial

Your find-node is actually (almost) assoc or, if you prefer, (find node graph :key #'first).

Use mapcar instead of map 'list because it makes the intent clearer (the difference is that mapcar takes only lists and map any sequence).

You need just one do in loop; you can even fold all your setfs into one (setf a b c d e f).

In loop, with should (stylistically) come before for.

Deep

Your code looks too complicated for what it does.

None of your flet local functions is really necessary.
E.g., (remove-if #'is-head-p ...) should be (remove node-1 ...),
and (remove-if #'starts-with-tail-p ...) should be (remove node-2 ... :key #'first);
this would make the code both faster and cleaner.

Your loop should be

(loop for node in (remove-duplicates (rest node-list-2))
      for match = (find-node node graph)
      for repcd = (if (eql node node-1)
                      (remove-if #'is-tail-p (rest match))
                      (map 'list #'replace-tail-for-head (rest match))))
      do (setf (rest match) (sort repcd #'<)))

General

Usually it is better to use the most specific function you need. E.g., use setq on simple variables (instead of setf which also supports general references). Use mapcar instead of map 'list when working with lists (as opposed to vectors).


Convert all dates in an array to date format

Firstly, regardless of whether you actually want to transform the fields into dates,you will need to format them for display. This formatting should be applied in the template. In such cases, the idiomatic approach is to define a filter.

angular.filter('formatAsDate', ...);

and then inject the filter into the views controller to make it available.

MyController.$inject = ['formatAsDate'];
function MyController(formatAsDate) { }

However, date formatting is such a common scenario that AngularJS provides a built in, globally available (does not need to be injected) date filter out of the box.

Its first argument is a value representing a date. This may either be a Date, an ISO formatted date string such as you have, or a number in milliseconds.
Its second argument is a format string which specifies how the date should be displayed.

for example

{{'2016-09-02T23:00:00.000Z' | date: 'EEEE MMMM dd, yyyy'}}

will render

Friday September 02, 2016


Find maximum in sorted and rotated array

Math.abs in Math.abs(high - low) == 1 is suspicious. high should always be not less than low. Remove it.
middle = (low + high) >> 1 may (and will) overflow. Do middle = low + (high - low) >> 1.

That said, >> 1 is no better than) / 2.
Java is notorious in not eliminating the tail recursion. You should do it manually. First, rewrite it in a tail-recursive form:

    if (low == high) {
        return arr[low];
    }
    if ( Math.abs(high - low) == 1 ) {
        return Math.max(arr[low], arr[high]);
    }

    middle = (low + high) >> 1;
    if (arr[middle] > arr[middle + 1]) {
        return arr[middle];
    }
    if (arr[low] > arr[middle]) {
        high = middle - 1;
    } else {
        low = middle + 1;
    }
    return findMax(arr, low, high);

then eliminate a recursive call:

    while (high - low > 2) {
        middle = low + (high - low) / 2;
        if (arr[middle] > arr[middle + 1]) {
            return arr[middle];
        }
        if (arr[low] > arr[middle]) {
            high = middle - 1;
        } else {
            low = middle + 1;
        }
    }
    return Math.max(arr[low], arr[high]);


I would create a class for the Planets for a more scalable and Object Oriented design, as detailed below

The class would store Earth's G in a constant, because it does not change in any planet's calculation.
The constructor should require the planet's own G value and it's name (for the Print statements, discussed further below).
You can also add a method to calculate the resultant weight based on a given weight value, to follow along with the Object Oriented approach.

public class Planet {

final double earthG = 9.81;
double myG;
public String planetName;

public Planet(String planetName, double myG){
    this.myG = myG;
    this.planetName = planetName;
}

public double calculateWeight(double weight){
    return weight * myG/earthG;
}
}

In the main method I would create an array of Planets for readability,

Planet[] planets = new Planet[]{new Planet("Moon", 1.622),
                                new Planet("Mercury", 3.7),
                                new Planet("Venus", 8.87),
                                new Planet("Jupiter", 24.79)};

And use a Do-While loop to populate the loop instead of the While loop. The Do-While checks for the condition at the end, so the first print doesn't requires an input.

do{
   ...
  } while(expression);

You can also use the array to populate the menu itself using for loop. This is especially helpful if you have a large number of planets/items in the array.

do {
    System.out.println("/////MENU/////");
    for(int i=0;i<planets.length;i++){
        System.out.println(i + " - " + planets[i].planetName);
       }
    System.out.print("Pick a number 0 - " + planets.length + ": ");
    choice = input.nextInt();
    } while (choice <= 0 || choice >= 5);

Using the array has a massive advantage here for the output statement. Since the choice corresponds to the planet's position in the array, you can simply call the appropriate planet's method as planets[choice].calculateWeight(weight). Following two lines will suffice the purpose of the previous Switch-Case.

System.out.println("You selected " + planets[choice].planetName + ", your weight on " + planets[choice].planetName + " is: ");
System.out.println(planets[choice].calculateWeight(weight) + " Lbs");


I went ahead and refactored your code a lot. However, before I get into that, lets talk about what you did and what you could have done differently.

Feel free to let me know if you want me to expand on something specific.

Logic regarding: function calculateAverage(tests) {}

Calculate average function should not take in parameters a list of HTMLInputElements and should not return a string.

Why? Well it doesn't make sense. calculateAverage should take a list of values and calculate an average.

function calculateAverage(values){
  return values.reduce((a,c)=>a+c,0)/values.length;
}
const avg = calculateAverage([1,2,3]);

console.log(avg);

Because you return a string... later on you have to do this:

physicsAverage.value.slice(9)

Not good ! And can become extremely buggy !

Use querySelectorAll

querySelectorAll is your friend. It allows you to transform this:

document.getElementById('physics').getElementsByTagName('input');

into this:

document.querySelectorAll('#physics > input');

Declare static variables globally:

In your calculator listener callback, you declare a list of variables.

var physicsTests = document.getElementById('physics').getElementsByTagName('input');
var physicsAverage = document.getElementById('physicsAverage');
//etc

But these variables never change. So don't declare them in your callback, move them outside and at the top of your file.

Create generic code !

With the current code you have, a lot of manual labor is needed if you wish to add another subject. In my final solution, everything is built in a way where adding a new subject requires NO changes in the javascript.

To able to do this, use data-* HTML properties. It's super powerful when you need to add some extra info like the coefficients of each subject.

const subjects = document.querySelectorAll("div[data-coef]");

subjects.forEach(subject=>{
  console.log(subject.id, subject.dataset.coef);
});

Another powerful tool is Map. It allows you to easily keep track of specific subjects and other variables.

Solution:

const inputContainers = document.querySelectorAll('form#form > .subject');

const finalGradeElement = document.getElementById('finalGrade');
const form = document.getElementById('form');

const m = new Map();

inputContainers.forEach((container,i)=>{
  const output = container.querySelector(".output");
  const inputs = Array.from(container.getElementsByTagName("input"));
  const coef = Number(container.dataset.coef);

  const data = Array(inputs.length);
  m.set(i, {
    output, data, coef
  });

  inputs.forEach((item,j)=>item.addEventListener("input", function(){
    if(!this.value.length > 0){
       data[j] = undefined;
    } else {
       data[j] = Number(this.value);
    }
  }));
});

document.getElementById('calculator')
.addEventListener('click', function() {

  const res = Array.from(m.values()).reduce( (a,{output, data, coef})=>{

      const values = data.filter(item=>item!==undefined);

      if(values.length > 0){
        const avg = values.reduce((a,c)=>a+c, 0)/values.length;
        a.avgTotal  += avg * coef;
        a.coefTotal += coef;

        output.value = `Average: ${avg.toFixed(1)}`;
      } else {
        output.value = "Please enter a number";
      }

      return a;
  }, {avgTotal: 0, coefTotal: 0})

  const averagesTotal = res.avgTotal/res.coefTotal;

  finalGradeElement.value = `Final Grade: ${averagesTotal.toFixed(1)}`

});

function isEdited(){
  return !Array.from(m.values()).every(({data})=>{
    return data.every(i=>i===undefined);
  });
}

document.getElementById('resetter')
.addEventListener('click', function() {
  if (isEdited() && confirm('Your changes will be lost.\nAre you sure you want to reset?')) {
    form.reset();
    m.clear();
  }
});

window.addEventListener('beforeunload', function(event) {
  if (isEdited()) {
    event.returnValue = 'Your changes may be lost.';
  }
});
form > div {
  display: flex;
  flex-direction: column;
}
<form id="form">

    Physics:
    <input type="number">
    <input type="number">
    <input type="number">
    <output class="output"></output>

    History:
    <input type="number">
    <input type="number">
    <input type="number">
    <output class="output"></output>

  <button type="button" id="calculator">Calculate</button>
  <button type="button" id="resetter">Reset</button>
  <output id="finalGrade"></output>
</form>


Thread safe algorithm for arrays information manipulation

Contention

There is only one std::mutex, and every thread is permanently in contention for that same lock for every small partial operation. Thus, all the threads are permanently in contention over that lock, and at most one thread at a time is actually doing any work. A single threaded implementation should be faster - it has to do the same work, but doesn't have to fight over lock control.

So, how can this be fixed?

1) Separate independent data per thread

In the usage example, elements of V are split between threads so that no two threads are accessing the same elements. So, accesses to elements of V don't need a lock - if this convention is followed strictly.

If this is possible, locks aren't needed for those parts!

2) Finer granularity locks

Right now, taking the lock stops every thread from doing any work at all. Even with the improvement of option 1, only one thread at a time can access elements from B. This can be improved by introducing locks at a finer granularity:

simple: one lock per array element (so one for each DataB object)
more advanced: one lock for a subset of each array (e.g. one lock for every 10 array elements)

Doing so allows other threads to perform work on all unrelated elements.

3) Read/Write exclusivity

What's the difference between reading and writing B{0]? Reading can be done concurrently, writing can't. There is a lock that helps for this special case: std::shared_mutex allow multiple threads to read the related object(s), but only allows one thread to write to it (while no one else can access it). The catch? It's only available since C++17. Before that, there might be other libraries providing that functionality, though (e.g. boost), or you make do with a normal std::mutex.

Small problem

In the current version, every changes to an element of B is done in one transaction - no thread can see any partial state. If this property is required, this can be implemented with some special considerations. How do you change a BData object in one transaction?

Create a copy, change the copy, take the lock, overwrite the original with the copy, release lock (aka RCU = Read Copy Update, requires an external lock)
Lock the object, perform changes, unlock the object (this requires giving access to an internal lock)

Implementation

Headers are missing, At least <string>, <mutex> and <thread> need to be included.
using namespace std; is considered bad practice and should be avoided.
Some member functions of DataB and some variables could be marked const (e.g. DataB::getFieldCount(), DataB::getField(), compare, count, every function parameter). Doing so might help reasoning about code and enables the compiler to verify said reasoning and might enable it to generate better machine code.
Inconsistent naming: DataB::getFieldCount and DataB::setCountField.
DataB doesn't encapsulate any behavior, it just provides some getters and setters. Maybe make it a POD struct instead?
Prefer list initialization in the constructor(s).
The void in function_name(void) isn't needed in C++.

Fixed contention code

  For this, I made one internal mutex per DataB object and chose the second option for transactions. Also, I changed DataB to a POD struct to easily provide access to all internals (having getters and setters acquire locks on their own doesn't fit well with having a lock for a transaction).

#include <string>
#include <thread>
#include <shared_mutex>

struct DataB {
    mutable std::shared_mutex mut{}; // mutable so sonst DataB object can still be locked
    std::string name;
    double field;
    int fieldCount;

    DataB() { }
    DataB(const double sF, const int sC, const std::string& n) : name{n}, field{sF}, fieldCount{sC} {}
};

void threadRemove(const int dataStart, const int dataEnd, const int dataCount, const DataB B[], const DataB V[], const int &sortedCount) {
    bool changed = true;

    while (changed || sortedCount != dataCount) {
        changed = false;

        for (auto i = dataStart; i < dataEnd; i++) {
            if (V[i].fieldCount > 0) {
                for (auto x = 0; x < dataCount; x++) {
                    double compare;
                    {
                        std::shared_lock<std::shared_mutex> read_lock{ B[x].mut }; // shared_lock = read only access
                        compare = B[x].field;
                    } // read_lock goes out of scope and gets released
                    if (compare == V[i].field) {
                        std::unique_lock<std::shared_mutex> write_lock{ B[x].mut }; // unique_lock = write access
                        --B[x].fieldCount;
                        --V[i].fieldCount;

                        if (B[x].fieldCount == 0) {
                            B[x].fieldCount = -1;
                            B[x].field = -1;
                        }

                        changed = true;
                    }
                }
            }
        }
    }
}

Note

This could maybe be enhanced by strategic use of atomics. However, that would require more knowledge about the members and usages of DataB than I could gather/guess from the code given.


if-elseif chain. Is there a better pattern?

Simple pattern: Set up a hash table or map that maps the incoming byte to a function that returns the correct response.

(C++ pseudocode - can be done in C# as well - don't have time now for all the implementation details:)

__statusType responseFunc(_statusType,byte);

map<byte,responseFunc> responseMap;

private void ProcessByte(byte b)

{
  _status= responseMap[_status](_status,b);
}

Although you have some nested conditions, etc, your handler functions can deal with those conditions - but you may have to rethink your design and set up some classes that properly represent and understand your conditions. A long switch case or 'if else if' is invariably the result of poor design. You need to think carefully about your architecture.

Another thing to consider is abstracting your conditions a bit and setting up an enumeration or class hierarchy to represent them. They can then be used as the key for your map or a parameter to your handler functions.

Yes - this is work - but clean design does require some effort. If you don't like long conditional statements (and you shouldn't) put in the effort to clean them up.

You should think along those lines - maps, dictionaries, enumerations, class hierarchies, factories, etc - whenever you run into a situation that seems to require an extended 'if else if..' or 'switch case';


Creating CAPTCHA in ColdFusion then showing image in Vue.js

Be careful with storing intermediate data to disk, including RAM disk. Because it is shared by the whole server, it is even worse than a global variable! The data you write may not be the data you read.


Loading an animation with an Ajax request

As far as basic implementation. You've got it down pat. That being said, I do have a few suggestions that could allow your app to run more fluently. I assume that you are uploading these photos and that they aren't photos already on the server being accessed.

If my above assumption is true, I highly suggest you use the <input type='file' />. This will display the name of the file and will better maintain the file object for you when you pass it to the server. That being said, with the current implementation you actually don't upload any photos. All you do is give a name, but you don't physically package up the photo data and send it to the server to be processed.

Mizech makes a good point in his comment, though. Typically, you don't want to pass special characters unless you absolutely have to. That being said, the tagging system means you will having # showing up so why force the user to input it? Why not just have them input the tag without it? On the server side you can take the input and append the # in front because you know it should be there. It's about only having to do as much work as necessary and if you have to regex before sending then it would be easier to just send and then add it on the server.


Change the background color of the console with the help of enum

As has been mentioned using a Dictionary<RanngDe,Color> will make your code much simpler:

public enum RanngDe
{
    Blue = 0,
    Green = 1,
    Yellow = 3
}
static Dictionary<RanngDe, ConsoleColor> colors = new Dictionary<RanngDe, ConsoleColor>()
{
    {RanngDe.Blue,ConsoleColor.Blue },
    {RanngDe.Green,ConsoleColor.Green },
    {RanngDe.Yellow,ConsoleColor.Yellow }
};
public static void SetColor(RanngDe R)
{
    Console.BackgroundColor = colors[R];
}

Depending on your implementation you might be able to do away with the method completely and just use the assignment.

I came up with another approach.  If you change the values of Ranngde to be the same as the ConsoleColor enum, you can cast the Ranngde value to ConsoleColor:

public enum RanngDe
{
    Blue = ConsoleColor.Blue,
    Green = ConsoleColor.Green,
    Yellow = ConsoleColor.Yellow
}
public static void SetColor(RanngDe R)
{
    Console.BackgroundColor = (ConsoleColor)R;
}


A few more possibilities to consider:

pre-compille your regular expressions

Compiling a regular expression is (potentially) a somewhat expensive operation. In this case, the regular expressions remain constant throughout the program, so you might as well compile them once, and use the compiled regular expression after that:

bool checkRegex(string & str)
{
    static std::regex pattern{"^\\s{0,}<td\\salign.{0,}$"};

    return regex_match (str , pattern);
}

use operator overloading where sensible

For example, your compare function:

bool compare (PROBLEM & p1 , PROBLEM & p2)
{
    return p1.users < p2.users;
}

...really makes more sense as an overload of operator<:

bool operator<(PROBLEM & p1 , PROBLEM & p2)
{
    return p1.users < p2.users;
}

const correctness

Taking the operator above a step further, we don't want x < y to modify either x or y, so we should pass the operands by const reference:

bool operator<(PROBLEM const &p1 , PROBLEM const &p2)
{
    return p1.users < p2.users;
}

This way, when we sort our vector of Problem objects, we don't need to explicitly specify how to compare them:

sort(v.rbegin(), v.rend());

Use the force library, Luke

In addition to a command line utility, cURL is available as a library that you can use in your program. There's also a cURLpp library that provides a C++ wrapper around libcurl, which you may prefer. Either can help you write code that's quite a bit simpler and more readable.

Work with the library, not against it

Right now, you have (for example) a readFile to read the contents of a file into a vector of PROBLEM. That's not really how the standard library is meant to work though. To work optimally with it, you really just want to overload operator>> to read one PROBLEM from the file. Once you have that, you can (for example) use stream iterators to read from a file into a vector.

class Problem {
    // ...

    friend std::istream &operator>>(std::istream &is, Problem &p) {
        // code to read one Problem from the stream goes here
        return is;
    }
};

Then we can initialize our vector from a pair of iterators:

std::ifstream in("input.txt");
std::vector<Problem> v{ std::istream_iterator<Problem>(in), {} };


Parse WAP-230 "variable length unsigned integers"

To get the bits out of a byte without converting to a string and back again, use Python's bitwise operations and shift operations. To get the high bit of a byte, shift it right by 7 bits:

>>> data = open('/dev/urandom', 'rb').read(128)
>>> data[0]
193
>>> data[0] >> 7
1

To get the low seven bits of a byte, mask against 0b1111111 (that is, 127):

>>> data[0] & 127
65

Finally, if we maintain a running value for content_length, we can extend it with these seven bits of payload by taking the running value, shifting it left by 7 bits and or-ing with the payload. In summary:

content_length = 0
while True:
    byte = self.data[curr_index]
    curr_index += 1
    content_length = (content_length << 7) | (byte & 127)
    if byte >> 7 == 0:
        break


Get object in a Set that is an instance of a generically specified type

As your current code now indirectly forces the set to only contain one of each component, then you could use a Map instead. This would also reduce the need for the loop

public class Load {
    Map<Class<? extends LoadComponent>, LoadComponent> lc;

    public <T extends LoadComponent> T getLoadComponent(Class<T> type) {
        return (T) lc.get(type);
    }
}

Other comments:

Make sure the Map is set to private final
lc is not a good name. There's really no need to save bytes by shortening variable names. A better name would be loadComponents
When adding items to the map, you can use loadComponents.put(obj.getClass(), obj);


From a processing efficiency perspective, they are largely indistinguishable. But if I were forced to choose between these two approaches, I might lean towards the latter, wrapping the whole if-else test in a single dispatch to the main queue, for two reasons:

There is a timing issue:

Let’s assume you ran this from a background thread and active was false, so you asynchronously dispatch the activity indicator update back to the main queue. What if, by the time the main queue gets to the dispatched block, that active is now true? Do you still really want to turn off the activity indicator? No, you almost certainly want to treat the combined test of active and the corresponding updating of the activity indicator as a single operation.
There is a thread safety issue:

When dealing with this boolean (and I’m assuming it’s a simple boolean, not wrapped in some synchronization mechanism), you should think about how you ensure thread-safe access to it. One really should synchronize access to one’s properties when writing multi-threaded code, and the first approach makes it unclear from which thread are you retrieving active (much less from which thread(s) is it being updated). One very simple synchronization technique to ensure that all reads and writes to active are done on the main queue, which, by virtue of being a serial queue, ensures thread-safety.

A few observations regarding other possible patterns/considerations:

You might want to consider whether, rather than writing a routine that you manually call to check active and update the activity indicator accordingly (meaning that every time you update active, you have to remember to call this routine), whether you might prefer to just supply the active property an observer that does the updating of the activity indicator for you. If you can have your property automatically trigger the UI update, then it eliminates the possibility of them getting out of sync.
There are special concerns if the changes to active are happening very quickly:

First, if active changes are happening extremely quickly (e.g. thousands of times per second), you risk flooding the main queue. You can address these sorts of issues with things like dispatch sources.
Second, even if it’s only a couple of times per second, you might want to avoid starting and stopping the activity indicator too quickly (because it yields a spinner that is constantly restarting, yielding a “Max Headroom” style of stuttering effect). For example, if active changes every ¼ second, and keeps doing that for 10 seconds, you may want to just want to keep the spinner going for that full 10 seconds, not starting and stopping it repeatedly. You can accomplish this by programming some latency in the “stop activity indicator” routine. E.g. when active is set to false, add non-repeating timer to stop the activity indicator in ½ second, but only after canceling any prior timer, if any. Likewise, when active is set to true, only “start” the activity indicator if you know it’s not already started.

Bottom line, be aware that the right implementation might depend upon the frequency of changes.


Function to return subword of a camelcase string

Review

Add docstrings and tests... or both in the form of doctests!

def find_word(s, index):
    """
    Finds the CamalCased word surrounding the givin index in the string

    >>> find_word('CamelCaseString', 6)
    'Case'
    >>> find_word('ACamelCaseString', 0)
    'A'
    """

    ...

Loop like a native.

Instead of going over the indexes we can loop over the item directly

range(index, 0, -1)

We can loop over the item and index at the same time using enumerate

for i, s in enumerate(string[index:0:-1])

However this would be slower since it will create a new string object with every slice.
If we can be sure that the givin string is a CamalCase string

Then we can drop some of your second if statement

if s[i].islower() and s[i+1].isupper() or s[i:i+2].isupper():

Would be

 if s[i+1].isupper():

Actually your code (from a performance aspect) is quite good

We could however use a while loop to increment both side at once, for a little performance gain.

(slower, yet more readable) Alternative

A different approach to finding CamalCase words can be done with regex,

We can find all CamalCase words with the following regex: r"([A-Z][a-z]*)"

And we can use re.finditer to create a generator for our matches and loop over them, and return when our index is in between the end and the start.

import re

def find_word_2(string, index):
    for match in re.finditer(r"([A-Z][a-z]*)", string):
        if match.start() <= index < match.end():
            return match.group()

NOTE This yields more readable code, but it should be alot slower for large inputs.


Using LINQ to group social networking links for each user

You could use a Dictionary and make properties of UserViewModel to address elements of this dictionary as follows:

public class UserViewModel
{
    private readonly Dictionary<SocialType, string> SocialLinks;

    public UserViewModel(User user)
    {
        SocialLinks = (user.SocialLinks ?? new SocialLink[0])
                      .ToDictionary(x => x.Type, x => x.Url);
        Name = user.Name;
    }

    private string GetUrl(SocialType socialType)
    {
        string url;
        return SocialLinks.TryGetValue(socialType, out url) && url != null ? url : "#";
    }

    public string Name { get; set; }

    public string Facebook
    {
        get { return GetUrl(SocialType.FaceBook); }
        set { SocialLinks[SocialType.FaceBook] = value; }
    }
    public string Twitter
    {
        get { return GetUrl(SocialType.Twitter); }
        set { SocialLinks[SocialType.Twitter] = value; }
    }
    public string Youtube
    {
        get { return GetUrl(SocialType.Youtube); }
        set { SocialLinks[SocialType.Youtube] = value; }
    }

    ...
}

Then your query will looks like:

users.Select(u => new UserViewModel(u)).ToList();


An object exposed to directives that need to track changes on it

return function filtersReturn() {
    return {
        current: currentFilters,
        applied: appliedFilters,
        apply: apply,
        clear: clear
    };
};

This piece of code looks odd to me,  could you simply return the object itself, like this:

var returnFilters = {
    current: currentFilters,
    applied: appliedFilters,
    apply: apply,
    clear: clear
;}
return returnFilters;

I just don't see the point of returning a function that doesn't do "function" stuff,  it really returns a function that returns an object, so why not just return the object to begin with?

One more thing, I didn't like the name of the function, so when I changed it to an object I changed the naming as well.  The name returnFilters sounds better than filtersReturn  I mean when I say "filters return"  I am thinking "filters return ... what?"  but these are the return filters so I want the name to express that for me so when I read the code later I don't get confused as to what this filter is doing.


TL;DR

Use strictness annotations at the right point to get rid of thunks:

largepowmod :: Integer -> Integer -> Integer -> Integer
largepowmod num pow modbase = (operate num opList) `mod` modbase
  where
    opList = drop 1 $ binarizeE pow
    operate !k    []   = k
    operate !k (0:ops) = operate (k^2         `rem` modbase) ops
    operate !k (1:ops) = operate ((k^2 * num) `rem` modbase) ops
--          ^

Note that this is equivalent to using foldl'.

Proper benchmarks

First of all, let's get reliable benchmarks. We can use Criterion for this:

import Criterion.Main
import Text.Printf (printf)

main :: IO()
main = defaultMain [
  bgroup "largepowmod" $
    flip map ([1,3..5] ++ [9999]) $ \i ->
      bench (printf "10^1000 + %d" i) $
        let n = 10^1000 + i :: Integer
        in whnf (largepowmod 2 ((n - 1) `div` 2)) n
  ]

On my machine, I get about 16.4ms per call with -O2:

benchmarking largepowmod/10^1000 + 1
time                 16.14 ms   (16.07 ms .. 16.22 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 16.18 ms   (16.13 ms .. 16.23 ms)
std dev              124.6 μs   (99.83 μs .. 164.8 μs)

benchmarking largepowmod/10^1000 + 3
time                 16.44 ms   (16.26 ms .. 16.63 ms)
                     1.000 R²   (0.999 R² .. 1.000 R²)
mean                 16.35 ms   (16.29 ms .. 16.42 ms)
std dev              168.3 μs   (135.2 μs .. 223.2 μs)

benchmarking largepowmod/10^1000 + 5
time                 16.24 ms   (16.19 ms .. 16.30 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 16.35 ms   (16.30 ms .. 16.41 ms)
std dev              138.4 μs   (89.59 μs .. 182.9 μs)

benchmarking largepowmod/10^1000 + 9999
time                 16.45 ms   (16.34 ms .. 16.58 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 16.37 ms   (16.30 ms .. 16.43 ms)
std dev              165.2 μs   (129.3 μs .. 235.4 μs)

But let's not stop here. Let's have a look at the profile:

$ ghc --make Test.hs -O2 -prof -auto-all && ./Test +RTS -s -p && head -n20 Test.prof

        Tue Sep 27 13:32 2016 Time and Allocation Profiling Report  (Final)

           Test +RTS -s -p -RTS --output benchmark.html

        total time  =       19.65 secs   (19652 ticks @ 1000 us, 1 processor)
        total alloc = 8,760,057,056 bytes  (excludes profiling overheads)

COST CENTRE         MODULE                %time %alloc

largepowmod.operate Main                   91.9   83.5
getGCStats          Criterion.Measurement   5.1   10.6
getOverhead         Criterion.Monad         2.2    1.5
applyGCStats        Criterion.Measurement   0.1    1.5

                                                                                individual     inherited
COST CENTRE                                  MODULE                                   no.     entries  %time %alloc   %time %alloc

MAIN                                         MAIN                                     273           0    0.0    0.0   100.0  100.0
 main                                        Main                                     550           0    0.0    0.0   100.0   99.9
  main.\                                     Main                                     745           0    0.0    0.0    91.9   83.5
   largepowmod                               Main                                     746        1208    0.0    0.0    91.9   83.5
    largepowmod.operate                      Main                                     752     4011768   91.9   83.5    91.9   83.5
    largepowmod.opList                       Main                                     751        1208    0.0    0.0     0.0    0.0

So most of the time is used in operate. It's allocating most of the data. However, that's a little bit of a red herring, since binarizeE is inlined at this point, and poor operate is merely allocating the list that will be generated lazily.

Getting stricter

However, we're not strict enough. In operate we create a large chunk of intermediate data:

operate k    []   = k
operate k (0:ops) = operate (k^2         `rem` modbase) ops
operate k (1:ops) = operate ((k^2 * num) `rem` modbase) ops
--                           ^^^^^^^^^^^^^^^^^^^^^^^^^

Haskell is lazy, therefore (k^2 * num) `rem` modbase isn't evaluated until it's actually needed. Therefore we allocate \$\mathcal O(\log_2 p)\$ additional terms. This isn't necessary. We can provide a small fix to make sure that k has been fully evaluated:

largepowmod' :: Integer -> Integer -> Integer -> Integer
largepowmod' num pow modbase = (operate num opList) `mod` modbase
  where
    opList = drop 1 $ binarizeE pow
    operate !k    []   = k
    operate !k (0:ops) = operate (k^2         `rem` modbase) ops
    operate !k (1:ops) = operate ((k^2 * num) `rem` modbase) ops

This needs -XBangPatterns. How does this fare? We change our main:

main :: IO()
main = defaultMain [
  bgroup "largepowmod" $
    flip map ([1,3..5] ++ [9999]) $ \i ->
      bench (printf "10^1000 + %d" i) $
        let n = 10^1000 + i :: Integer
        in nf (largepowmod 2 ((n - 1) `div` 2)) n
 , bgroup "largepowmod'" $
    flip map ([1,3..5] ++ [9999]) $ \i ->
      bench (printf "10^1000 + %d" i) $
        let n = 10^1000 + i :: Integer
        in nf (largepowmod' 2 ((n - 1) `div` 2)) n
  ]

And run it again (without -prof):

benchmarking largepowmod/10^1000 + 1
time                 16.14 ms   (16.07 ms .. 16.22 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 16.18 ms   (16.13 ms .. 16.23 ms)
std dev              124.6 μs   (99.83 μs .. 164.8 μs)

benchmarking largepowmod/10^1000 + 3
time                 16.44 ms   (16.26 ms .. 16.63 ms)
                     1.000 R²   (0.999 R² .. 1.000 R²)
mean                 16.35 ms   (16.29 ms .. 16.42 ms)
std dev              168.3 μs   (135.2 μs .. 223.2 μs)

benchmarking largepowmod/10^1000 + 5
time                 16.24 ms   (16.19 ms .. 16.30 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 16.35 ms   (16.30 ms .. 16.41 ms)
std dev              138.4 μs   (89.59 μs .. 182.9 μs)

benchmarking largepowmod/10^1000 + 9999
time                 16.45 ms   (16.34 ms .. 16.58 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 16.37 ms   (16.30 ms .. 16.43 ms)
std dev              165.2 μs   (129.3 μs .. 235.4 μs)

benchmarking largepowmod'/10^1000 + 1
time                 14.54 ms   (14.49 ms .. 14.60 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 14.51 ms   (14.46 ms .. 14.54 ms)
std dev              101.0 μs   (64.28 μs .. 177.1 μs)

benchmarking largepowmod'/10^1000 + 3
time                 14.53 ms   (14.49 ms .. 14.58 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 14.53 ms   (14.50 ms .. 14.56 ms)
std dev              78.32 μs   (62.67 μs .. 95.66 μs)

benchmarking largepowmod'/10^1000 + 5
time                 14.42 ms   (14.36 ms .. 14.48 ms)
                     1.000 R²   (1.000 R² .. 1.000 R²)
mean                 14.56 ms   (14.51 ms .. 14.65 ms)
std dev              180.4 μs   (92.90 μs .. 298.2 μs)

benchmarking largepowmod'/10^1000 + 9999
time                 14.60 ms   (14.49 ms .. 14.85 ms)
                     0.998 R²   (0.993 R² .. 1.000 R²)
mean                 14.61 ms   (14.53 ms .. 14.87 ms)
std dev              314.4 μs   (69.97 μs .. 618.3 μs)

We went from 16.14ms to 14.77ms (0.89 of original time), or if we extrapolate this to your 110s to 98s, which is closer to Mathematica's time.


Count the number of leaders in both sides (slices) of an array in C#. Codility EquiLeaders task

If you need to get a value of a Dictionary<TKey, TValue> you shouldn't us ContainsKey() together with the Item property getter but TryGetValue(), because by using ContainsKey() in combination with the Item getter you are doing the check if the key exists twice.
From the refernce source

public bool ContainsKey(TKey key)
{
    if (key == null) throw new ArgumentNullException("key");

    TValue throwAwayValue;
    return TryGetValue(key, out throwAwayValue);
}

public TValue this[TKey key]
{
    get
    {
        TValue value;
        if (!TryGetValue(key, out value))
        {
            throw new KeyNotFoundException();
        }
        return value;
    }
    set
    {
        if (key == null) throw new ArgumentNullException("key");
        TValue dummy;
        TryAddInternal(key, value, true, true, out dummy);
    }
}

Multiple declarations of variables on a single line should be avoided because it reduces the readability of the code.
If the type is clear from the right-hand-side of an assignment one should use var instead of the concrete type.
You should declare the variables as near to their usage as possible. This makes reading the code easier as well.
Althought this is from a programming excercise please note that methods should be named using PascalCase casing and method parameters should be named using camelCasecasing. Meaning solution should be Solution and A should be a if we talk about casing.

Implementing the mentioned points (without casing stuff) will look like this

public int solution(int[] A)
{
    var leftPartition = new Dictionary<int, int>();
    var rightPartition = new Dictionary<int, int>();

    for (var index = A.Length - 1; index >= 0; index--)
    {
        var candidate = A[index];
        rightPartition.TryGetValue(candidate, out int value);
        rightPartition[candidate] = value + 1;
    }

    var leadersCounter = 0;
    var leftPartitionSize = 1;
    var rightPartitionSize = A.Length;
    var leader = A[0];

    for (var index = 0; index < A.Length; index++)
    {
        var candidate = A[index];

        leftPartition.TryGetValue(candidate, out int value);
        leftPartition[candidate] = value + 1;

        rightPartition[candidate]--;
        rightPartitionSize--;

        if (leftPartition[candidate] > leftPartitionSize / 2)
        {
            leader = candidate;
        }
        if (leftPartition[leader] > leftPartitionSize / 2 && rightPartition[leader] > rightPartitionSize / 2)
        {
            leadersCounter++;
        }
        leftPartitionSize++;
    }
    return leadersCounter;
}


Check if strings are substrings of another string in Python

The problem of finding matches for multiple fixed search strings in a corpus is solved by the Aho–Corasick algorithm in time proportional to the length of the corpus plus the number of matches.

Python doesn't come with an implementation of the Aho–Corasick algorithm (as far as I know), but the Python Package Index has the pyahocorasick package. Or you could write your own.

Alternatively, if you are on a Unix system, you can use the -F (fixed strings) option to grep and avoid Python altogether.


The answer to your primary question is yes, methods already exist in libraries that can do this. Reference this StackOverflow post.

Your method can then be simplified to what's shown below:

#include <string>

bool strfound(const std::string &in, const std::string &substr) {
    return in.find(substr) != std::string::npos;
}


Elevation to power function using class templates

Headers and namespaces

Don't using namespace, especially a big and growing namespace like std that's not designed for it.

There's no need to include <cmath>.  On the other hand, there is a clear need for <iostream>, which has been omitted.

Structure

There's no need for the Power class; it maintains no state.  The functions should simply be free functions, perhaps in a namespace.

Consider full range of types

raiseToPower() only works with non-negative exponents; it should either accept an unsigned type or be modified to work correctly with negative inputs.  Perhaps like this:

    if (power < 0) {
        return raiseToPower(1/x, -power);
    }

Improve the algorithm

For large power, the loop is executed many times.  We can use binary exponentation to reduce that to log₂ power iterations of the loop.

Avoid over-complication

floor0() doesn't need that if/else; simply add 0.5 before truncating:

constexpr double floor0(double num)
{
    return int(num + 0.5);
}

It might be better to use long or long long there; in any case, you'll still suffer bugs when the value is too big for the integer type.  std::floor() doesn't have that problem.

Validate inputs

If I enter a non-number, I don't get a clear error message.  Instead, the program uses uninitialised values, which is Undefined Behaviour.  Don't do that; instead check that std::cin is still good before using x or i.

Avoid std::endl unless you need output flushing

None of the uses of std::endl here are necessary, and we can use \n instead.  (Remember that using std::cin flushes the output streams, and returning from main() also flushes outputs).

Modified code

double raiseToPower(double x, int power)
{
    if (power < 0) {
        return raiseToPower(1/x, -power);
    }

    double result = 1.0;
    double m = x;

    for (;  power;  power /= 2) {
        if (power % 2) {
            result *= m;
        }
        m *= m;
    }
    return result;
}

constexpr double floor0(double num)
{
    return int(num + 0.5);
}

#include <iostream>

int main()
{
    double x;
    int i;
    std::cout << "Please enter the number\n";
    std::cin >> x;
    std::cout << "Please enter the integer power that "
                 "you want this number raised to\n";
    std::cin >> i;
    if (!std::cin) {
        std::cerr << "Input format error\n";
        return 1;
    }
    auto const result = raiseToPower(x,i);
    std::cout << x << " raised to power " << i << " is equal to "
              << result << '\n';
    std::cout << "The result rounded is "
              << floor0(result) << '\n';
}


Returning distinct characters in combined Strings

What comes to performance, you can improve it significantly:

public static String getDistinctCharString(String s1, String s2) {
    Set<Character> set = new HashSet<>(s1.length() + s2.length());

    char[] chars1 = s1.toCharArray();
    char[] chars2 = s2.toCharArray();

    for (char c : chars1) {
        set.add(c);
    }

    for (char c : chars2) {
        set.add(c);
    }

    StringBuilder sb = new StringBuilder(set.size());

    for (char c : set) {
        sb.append(c);
    }

    return sb.toString();
}

The point is that you deal with characters rather than substrings of length 1.

My demonstration gives me the following output:

longest() in 2558 ms.
getDistinctCharString() in 342 ms.
Algorithms agree: true

Hope that helps.


Some comments:

Firstly the interface is odd.  Normally when you pass an array, you pass it's
size and a pointer to the first element.  In the context of your function this
means:

int* maxmin(const int list[], size_t size, int max, int min);

Then you call this with:

maxmin(list, mid, max, min);
maxmin(list + mid, size - mid, max1, min1);

or from main

values = maxmin(list, size, list[0], list[0]);

This saves a call parameter (fewer is always preferable) and makes the
function more 'normal'.

Beyond that, what stand out are the return of a static array and the use of
globals.  Maybe thread safety is not on your mind and this can be ignored, but
bear in mind that returning a static is rarely done.  And globals are often best avoided, if they can be.

The other thing that strikes me is the awkwardness of the code.  Arguably a
matter of opinion, there are many variables and their names are hard to tell
apart.  More importantly the need to find both max and min values complicates
the function enormously.

Consider the same task but only looking for the minimum value:

int min(const int list[], const size_t size)
{
    if (size == 1) {
        return list[0];
    }
    else if (size == 2) {
        return list[0] < list[1] ? list[0] : list[1];
    }
    size_t half = size / 2;
    int n = min(list, half);
    int m = min(list + half, size - half);
    return n < m ? n : m;
}

This is so much simpler!  And the max version just involves reversing the
two comparisons.  I would be looking for an excuse to use these rather than
your combined function.  Against my functions is the fact that calling max
and min will be slower than just calling yours (but less than 2:1).  In
their favour, you might not always want both values.

As this is just an exercise, you don't have to care.  But in practice I
believe strongly that it is always worth simplifying the
requirement/specification if it results in simpler code.


Wrapping single line string to multiple lines with specific length

I think you shouldn't build a new string there because it's a new responsibility. The method should only split the text and return its parts with the specified length.

The user should decide what to do with the results next. Maybe he does not want to use the Environment.NewLine but some other new-line?

I prefer it to be a split-only method:

public static IEnumerable<string> Split(this string text, int partLength)
{
    if (text == null) { throw new ArgumentNullException("singleLineString"); }

    if (partLength < 1) { throw new ArgumentException("'columns' must be greater than 0."); }

    var partCount = Math.Ceiling((double)text.Length / partLength);
    if (partCount < 2)
    {
        yield return text;
    }

    for (int i = 0; i < partCount; i++)
    {
        var index = i * partLength;
        var lengthLeft = Math.Min(partLength, text.Length - index);
        var line = text.Substring(index, lengthLeft);
        yield return line;
    }
}

I need to complain about the missing {} but I guess you probably know that ;-)

The names of the variables could also be a little bit clearer.

Technically you don't need this if:

    if (partCount < 2)
    {
        yield return text;
    }

The result will be the same with out it because the for would execute only once .


I don't see a better than \$(O(N^2M))\$ (that is, brute force) solution; however an asymptotic constant could be improved significantly.

First, I recommend to represent an individual knowledge as an integer rather than a list. This way computing a team knowledge is a matter of a single bitwise or, and a number of topics covered is the amount of bits set.

To obtain an integer representation of knowledge, recall that int() takes base as a second argument:

    for _ in range(ppl):
        knowledge.append(int(input(), 2))

Then analyze a combined team of x, y knowledge as

    team_topics = bit_count(knowledge[x] | knowledge[y])

There are many ways to implement bit_count. Here is a good place to start.

Observations not related to performance:

Naming is not particularly good. I expect current_topic to be a loop index running through topics, not the count of topics covered by team. Similarly, max_topic is named as if it represents the maximal index in topics table.
Dummy loop variable (x in the input loop) is by convention denoted by _. Seeing _ the reader knows it is dummy, and doesn't look for how it might be used in the code.


Python has many great ways to iterate.  In general if you find yourself looping on an integer, like in the following code, there is a good chance you are doing it wrong.  It is generally better to iterate on the data structure itself.

Sample code:

I will use this loop as an example:

len_of_longest_name = 0
i = 0
while i < len(table):
    if len_of_longest_name < len(table[i][1]):
        len_of_longest_name = len(table[i][1])
    i += 1

Don't iterate on the length of a data structure:

This is probably not what you want:

while i < len(table):

It would likely be better as something like:

for row in table:

Or, if for some reason you really need the index, then:

for i, row in enumerate(table):

Example with looping on length removed:

So removing i, and looping on table, we get:

len_of_longest_name = 0
for row in table:
    if len_of_longest_name < len(row[1]):
        len_of_longest_name = len(row[1])

Use builtin functions.

Python have a max() function.  Using max(), the example becomes:

len_of_longest_name = 0
for row in table:
    len_of_longest_name = max(len_of_longest_name, len(row[1]))

Comprehensions:

Since max() can take a comprehension the example loop can be reduced to:

len_of_longest_name = max(len(row[1]) for row in table)

That is six lines of code reduced to one.


Incrementing and displaying a field if not empty

$vidnum = 'video_';

Presumably $vidnum is short for $video_number, but this isn't a video number.  It's the prefix before the video number.

     $video_number_prefix = 'video_';

You can go ahead and call it what it is.

     for($n=0; $n<=9; $n++) {
     $next = $vidnum.($n +1 );

You say that you have ten fields but you write 9.  There are two ways to write it with 10.

     for ( $n = 0; $n < 10; $n++ ) {

But the second works better with your $next variable, which I'm going to rename to $video_identifier.

     for ( $i = 1; $i <= 10; $i++ ) {
         $video_identifier = 'video_' . $i;

You don't need to save the value of the string literal.  You only use it once, so you can just use it.

Starting with 1 instead of 0 means that you don't have to add 1 to the value before using it.

I switched from $n to $i, as $i is a more common loop iteration variable.

     $video = get_field('' . $next . '');

This seems more complicated than it needs to be.

         $video = get_field($video_identifier);

Adding the empty strings doesn't seem to accomplish anything.

         if (!empty($video))
             echo '
' . $video . '
';

The single statement version of an if is harder to read and maintain.

         if ( ! empty($video) ) {
             echo '
' . $video . '
' . "\n";
         }

I also added a line break at the end.  Functionally this won't matter, but it makes the HTML easier to read.

The whole thing:

<?php
     for ( $i = 1; $i <= 10; $i++ ) {
         $video_identifier = 'video_' . $i;
         $video = get_field($video_identifier);
         if ( ! empty($video) ) {
             echo '
' . $video . '
' . "\n";
         }
     }
?>

This also fixes your indentation issues.

Note that I'm not commenting on your use of get_field.  Looking at the documentation, it seems that get_field depends heavily on the configuration.  Without the configuration, that is off-topic for review.


Basic console calculator with four operations

Compactness

use a switch statement rather than verbose if-elseif-.. statements
get rid of redundant blank lines

Readability

Avoid escaping characters.

Console.WriteLine("Type \"+\" for addition");
Console.WriteLine("Type \"-\" for subtraction");
Console.WriteLine("Type \"*\" for multiplication");
Console.WriteLine("Type \"/\" for division");

You could go with..

Console.WriteLine("Type '+' for addition");
Console.WriteLine("Type '-' for subtraction");
Console.WriteLine("Type '*' for multiplication");
Console.WriteLine("Type '/' for division");

Or..

Console.WriteLine(@"Type ""+"" for addition");
Console.WriteLine(@"Type ""-"" for subtraction");
Console.WriteLine(@"Type ""*"" for multiplication");
Console.WriteLine(@"Type ""/"" for division");

User Experience

If you ever wish to design end-user interfaces, you have to work on your lingo.

You're off to a good start:

Console.WriteLine("Hi! What is your name?");

You slip up slightly next (forgot a question mark):

Console.WriteLine(name + " What do you wanna do");

But then you start pressuring the end-user. You expect a number, not in a moment, but Now! And you are not asking, you are demanding.

Console.Write("Now, Give me number one: ");

Also, one time with a comma and capital after it, and one time the other way around:

Console.Write("Now give me number two: ");

The user may also expect this application to crash on:

double num1 = Convert.ToDouble(Console.ReadLine());
double num2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(num1 / num2); // when num2 is 0
Any other overflow

And nothing happens when an unknown operator is provided by the user.

The user is not able to verify the results, since the application immediately terminates after the calculation is evaluated.


Code review needed for my Prime factorization code

def factorize(num):
    res2 = "%s: "%num

You'd be much better off to put the string stuff in a seperate function. Just have this function return the list of factors, i.e. res and have a second function take res as a parameter and return the string. That'd make your logic simpler for each function.

    res = []

Don't needlessly abbreviate. It doesn't save you any serious amount of typing time and makes it harder to follow your code.

    while num != 1:
        for each in range(2, num + 1):

To be faster here, you'll want recompute the prime factors of the numbers. You can use the Sieve of Eratosthenes. Just keep track of the prime factors found, and you'll just be able to look them up.

            quo, rem = divmod(num, each)
            if not rem:
                res.append(each)
                break
        num = quo

Your function dies here if you pass it a zero.

    pfs = set(res)

Rather than a set, use collections.Counter, it'll let you get the counts at the same time rather then recounting res.

    for each in pfs:
        power = res.count(each)
        if power == 1:
            res2 += str(each) + " "
        else:
            res2 += str(each) + '^' + str(power) + " "

String addition is inefficient. I'd suggest using "{}^{}".format(each, power). Also, store each piece in a list and then use " ".join to make them into a big string at the end.

    return res2


How do I lessen the memory usage of my solution to LeetCode 495: Teemo Attacking

Disclaimer: Not a Code Reviewer

Just tested your code, it has a 1ms runtime with 99.97% faster than other solutions.

Don't pay too much attention to these runtime/memory data provided by LeetCode especially when:

it comes to memory; or
test cases are too limited (such as Teemo) because their benchmarkings are not so accurate.

Maybe instead we'd format the code, just a bit making things based on Java's conventions:

public class Solution {
    public static final int findPoisonedDuration(
        final int[] timeSeries,
        final int duration
    ) {

        int i = 0;
        int oldGoalpost = 0;
        int newGoalpost = 0;
        int diff = 0;
        int numberOfSeconds = duration;

        if (timeSeries.length > 0) {
            oldGoalpost = timeSeries[0] + duration - 1;

        } else {
            numberOfSeconds = 0;
        }

        if (timeSeries.length > 0)
            for (i = 1; i < timeSeries.length; i++) {
                newGoalpost =  timeSeries[i] + duration - 1;

                diff = (newGoalpost - oldGoalpost) > duration ? duration : ((newGoalpost - oldGoalpost));

                numberOfSeconds = numberOfSeconds + diff;
                oldGoalpost = newGoalpost;

            }

        return numberOfSeconds;

    }
}

Your solution has an order of N runtime with constant memory O(1).
Algorithmically speaking, which is a key point on solving LeetCode questions, I don't think much can be done to make it any further efficient, I might be wrong though.

public class Solution {
    public static final int findPoisonedDuration(
        final int[] series,
        final int duration
    ) {
        if (series.length == 0 || duration == 0) {
            return 0;
        }

        int totalTime = duration;

        for (int i = 1; i < series.length; i++) {
            totalTime += Math.min(series[i] - series[i - 1], duration);
        }

        return totalTime;
    }
}


Find all row combinations which sum elements equal to any given number

Take a look at Python Performace Tips and search for list comprehension. As far as I can understand your code you can use it.

An example would be this function.

def __create_matrix(self):
    max_count = self.__cash // self.__cheapest_cocktail
    return [ [Cocktail(cocktail.group,cocktail.name,cocktail.sell,i)
         for i in xrange(0, max_count)] for cocktail in self._menu]

You don't need to create a list if you are not using it elsewhere. In the find_combinations function you can avoid the overhead of list creation because you are only interested in the sum of the elements.

def find_combinations(self):
    for check in itertools.product(*self.__matrix):
        if sum((c.sell * c.count) for c in check) == self.__cash:
            self.correct.append(check)

I think there is a bug in your code. You are using a classCocktail but using cocktail in your code. I understand they are different but I think you have messed up C with c in your code in the __read_menu function. It is confusing whether or not you have messed it up.

That is all I can think of because I don't understand what the code is doing unless. Please edit your question to add sample input and output.


@Josay's and @Reinderien's answers both give useful advice, with @Josay's being particularly comprehensive. However, there is one point that I've noticed neither of them have covered

Generation of the secret number

# Generate secret number with SECRET_NUMBER_SIZE digits and no duplicates
secret_number = ""
while len(secret_number) < SECRET_NUMBER_SIZE:
    new_digit = str(random.randint(0, 9))
    if new_digit not in secret_number:
        secret_number += new_digit

This is an inelegant way of generating the secret number for two reasons:

You concatenate to a string, an immutable type. This is much more expensive than necessary, which does not a notable impact on a program of this size, but could become problematic as you scale up; it's better to practice good techniques, even at small scales. Additionally, you should never need to iteratively concatenate to a string in situations where the string's contents are generated all at once, because there are two successively more efficient ways:

Since Python uses dynamic lists, you can create a list with the string's contents, and then use "".join(str(i) for i in src_lst)
To improve the efficiency even further, you can utilize the fact that you know the list's size already, and "pre-allocate" the list using lst = [None] * SECRET_NUMBER_SIZE and then iteratively fill in its contents using a numerical index variable. This is a bit unpythonic, as @Josay goes over in their answer, and is probably a bit of premature optimization, but it's a good trick to have up your sleave if you want to eek out a bit more performance, and may be extremely useful depending on the situation.
But there's an even better way, which we'll get to in a second...

Every number is checked to ensure it hasn't already occurred in the result list. The reason this is not ideal is because at larger scales, one could end up generating many numbers before they stumble upon one that hasn't already been chosen. To mitigate this, one could lower the generation range each time, and offset the numbers accordingly, but it's probably not worth the effort because this isn't much of a practical concern, even at larger scales; generating random numbers using the Mersenne Twister is very cheap. But this concern helps lead to an elegant solution...

random.sample() is your friend here. It allows you to generate multiple distinct random numbers quite easily; all you have to provide is a population sequence and the size of the sample. For this situation, a population sequence is quite simple: range(10) supplies all the numbers between 0 and 9 inclusive. You can now simplify your 5 lines above into ~1 line:

secret_number = "".join((str(i) for i in
    random.sample(range(10), SECRET_NUMBER_SIZE)))


It is a hashmap, using linear probing on an array

Use unsigned int for the keys/hashes.
Make functions like get, display or exists const, so you make clear that they are not modifying the map and you can pass the map as const& to a function, which may uses this functions but does not use add or remove or other functions modifying the map.

void display() const;

You can add operator[] which returns a reference to the value, here are the signatures:

int& operator[](int key); // this can be used for assignment (``map[3] = 5``) and to get a value (``std::cout << map[3] << '\n'``). This needs to insert an element, if there is no element with the key and initialize its value to a default value like ``int()``/``0``
int operator[](int key) const; // this is used when the map is accessed when it is const. No need for reference, but for other value-types like std::string, use std::string const& to avoid copying

You can make the class generic, to allow other value-types.
Make whitespace after each function or class, to seperate.


Print out a student's former name if it is not empty

Why not just

echo $student->former_name

If its empty, it will be an empty string and thus the same thing. There is no way to remove the else from a ternary statement. The only other way to write that would be like so:

echo empty( $student->former_name ) ? '' : $student_former_name;

Edit: Actually, I sort of lied above, you could remove the empty check altogether.

echo $student->former_name ? $student->former_name : '';

And of course, if your PHP version is >= 5.3, then you could use short ternary, assuming that your statement returns the same value that your if section should return.

echo $student->former_name ?: '';


Input validation for text boxes in a Form

Another option would be to handle the Validating event:

private void textBox_Validating(object sender, CancelEventArgs e)
{
    TextBox currenttb = (TextBox)sender;
    if(currenttb.Text == "")
        MessageBox.Show(string.Format("Empty field {0 }",currenttb.Name.Substring(3)));
        e.Cancel = true;
    else
    {
        e.Cancel = false;
    }
}

Adding the handler to the textboxes is easily done with a foreach loop in the form constructor:

foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))
{
    tb.Validating += textBox_Validating;
}

Now the user can't leave a textbox empty.  The handler returns the focus back to the textbox.  To exclude a textbox from being validated simply set the CausesValidation property to false.


Using $parent is an anti-pattern and sign of bad architecture. What if you code changes together with your parent chain - it will instantly break your code.

Also, have you thought about how you are going to test it?

To have a clean readable code, you want someone looking at it immediately see the meaning. What is the meaning of this object? -

ng-model = "$parent.$parent.$parent.type"

Would you not rather see

ng-model = "selectedItem"

or something more concrete like

ng-model = "myCar"

Naming something "current" makes me wonder what it is. From your code, I have no idea, so it forces me to spend time on looking around and getting clues, for what should be made clear right up front.


The code in example is violating following principles:

Single Responsibility Principle(SRP):
The responsibility of Notifying is spread thin across Clients and the classes are not clear with their intentions and it is also not reflecting through the behaviours. Now, it is not clear whether the client is also supposed to do other jobs.
Liscov Substitute Principle(LSP):
'Is-A' Relationship should be replaced with 'Is-Substitue-for' relationship. notification is CloudClient is violating LSP.
Dependency Inversion Principle(DIP): is violated since program class is dependent on client implementations and Notify class.

IMO, code can be restructured as follows. Please note, it can be also improved with better DI Implementation. By judging the code listing, I am not clear what is intended output of this program. Whether it is sending two different notifications or three notifications. Still,trying to provide the answer as per my understanding and assumptions below. Please let me know in comments the intent of the program so that I can modify the program as per the intent.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeSmellQuestion
{
    public class Notification
    {
        private readonly List<INotify> _providerList;
        public Notification(List<INotify> providerList)
        {
            _providerList = providerList;
        }

        public void SendAll()
        {
            foreach (var notificationProvider in _providerList)
            {
                notificationProvider.Notify();
            }
        }
    }

    public interface INotify
    {
        void Notify();
    }

    public class OnPremiseNotifier : INotify
    {
        public void Notify()
        {
            Console.WriteLine("You're getting these notifications because you opted for OnPremise Notifications....");
        }

    }

    public class CloudNotifier : INotify
    {
        public void Notify()
        {
            Console.WriteLine("You're getting these notifications because you opted for Cloud Notifications....");
         }
    }
}


Makefile for a x86 operating system in C++

Dependency Propagation

One thing that's missing is dependency propagation. So each .o file will be recompiled only if its corresponding .cc file has changed. This is good, I don't want to have to recompile foo.o just because I changed bar.cc. However, what if both foo.cc and bar.cc include some other file quux.h, and you changed some of the function signatures. Currently, neither foo.o nor bar.o will be recompiled! This is bad. However, you don't want to manually have to go through and add:

bar.o : quux.h
foo.o : quux.h

Since that is tedious, error-prone, and unmaintanable. You want to make the compiler do this for you.You can start with reading about automatic prerequisites, but rather than follow the guidelines there, note that gcc can both build the .o files and generate the .d files concurrently with -M (check out all the -M* arguments).

Targets

run and clean should be .PHONY targets.

I also like to get in the habit of setting .DEFAULT_GOAL instead of just making sure that all is at the top. You never know.

Comments

Very helpful for the most part. But I would omit these:

# $< : Names the first prerequiste
# $@ : Names the current Target

People who don't know what those mean likely won't understand anything about the makefile anyway, not sure the comments will help. Those are very commonly used.


Adding a new record to the beginning of the approval chain from the delegation chain

My suggestion is to create a "RowID" computed column on the workflow.delegation_engine table.

ALTER TABLE workflow.delegation_engine ADD [RowID] AS
    cast(de.ApprovalOrder + 1 as varchar(4))
    + cast(de.EntityCode as varchar(8))
    + cast(de.DelegationCode as varchar(12))

Your comment indicates that you might be ordering the query on this column.  In that case, you might also want to apply an index on this column.  I haven't tried this out, so I don't know for sure whether an index on this column is allowed, but I think it does satisfy all of the requirements.

Also, you might want/need to pad your values with leading zeros in order to ensure that your calculated RowID is unique.  In that case, you might want to try the following:

    right('0000' + cast(de.ApprovalOrder + 1 as varchar(4)), 4)
    + right('00000000' + cast(de.EntityCode as varchar(8), 8)
    + right('000000000000' + cast(de.DelegationCode as varchar(12), 12)

This would provide uniqueness and would preserve ordering (i.e. ApprovalOrder 10 comes after ApprovalOrder 2).  If you don't care about ordering, then you might not need the leading zeros; you could just insert delimiters to ensure uniqueness.

    cast(de.ApprovalOrder + 1 as varchar(4))
    + '|' + cast(de.EntityCode as varchar(8))
    + '|' + cast(de.DelegationCode as varchar(12))

This would protect against a scenario where one row has ApprovalOrder: 1, EntityCode: 'ABC', DelegationCode: 'DEF' and another row has ApprovalOrder: 1, EntityCode: 'AB', DelegationCode: 'CDEF'.  In that case, the RowID for both rows would be '2ABCDEF'.  Adding the delimiters ensures that the first row would have RowID: '2|ABC|DEF' and the second row would have RowID: '2|AB|CDEF'.

Alternatively, if you can't or don't want to put a "RowID" computed column on the table, then you should be able to just structure the query as shown below.  Note that I've included an "order by" clause that was left out of the original query.  Comments indicate that the reason for the subquery in the original query was to order by the "RowID" column.  The order by 1 clause in the query below accomplishes the same result.

select
    cast(de.ApprovalOrder + 1 as varchar(4))
        + cast(de.EntityCode as varchar(8))
        + cast(de.DelegationCode as varchar(12)) as 'RowID' ,
    cast(de.ApprovalOrder as int) + 1 as 'ApprovalOrder' ,
    de.EntityCode ,
    de.CostCentre ,
    de.DelegationCode ,
    de.ProjectCode ,
    de.RoleGroup ,
    de.Position ,
    de.DelegationText ,
    de.DelegationAmount ,
    de.Active
from
    workflow.delegation_engine de
where
    de.EntityCode = @entity
    and de.ProjectCode = @project_code
    and de.DelegationCode = @delegation_code
order by
    1


Defines and prints shortest word in set, sorts the rest by length, and gives average word length

Up to, and including the line list_of_words, your code looks good. But then it gets confusing.

To summarize what your program is supposed to do:

4 times: read a word from the user
put all these words in a list
sort this list by the word length
print the first element of the list (which is the shortest)
take a break (in other words, no need to sort the rest of the list, since it is already sorted)
ask your teacher about the unclear specification:

the average word length of what exactly: the whole list, or the rest?
why should the rest of the words be sorted when there is no requirement to print them afterwards?

Your definition of the average function was already good, you just didn't use it.

In Python, the above instructions could look like:

words = [first_word, second_word, third_word, fourth_word]
sorted_words = sorted(words, key=len)
sorted_lengths = [len(word) for word in sorted_words]

print('Shortest word: {}'.format(sorted_words[0]))
print('Remaining words: {}'.format(sorted_words[1:]))
print('Longest word: {}'.format(sorted_words[-1]))
print('Average word length: {}'.format(average(sorted_lengths)))
print('Average remaining word length: {}'.format(average(sorted_lengths[1:])))

Basically, you already had all the ingredients for solving the problem, you just mixed them up a bit.


Random seeding

        srand(time(NULL));

You call this inside a loop (or two loops actually).  But here's the problem, time returns the current number of seconds since an arbitrary historical point of time (1970 January 1st at midnight).  Most of the time in your loop, that will be the same number.  So you are seeding the number the same.  But occasionally you will tick over to the next second.
You should either create a variable
    time_t invocation_time = time(NULL);

that you can then use
        srand(invocation_time);

Or just move that seeding call outside the loops.
You would create the variable if you want to always seed with the same number so you get the same "random" sequence each time.  You could even set the value to something fixed rather than the current time.  I just used the current time because that's what you had been using and I have no particular reason to prefer a different value.  By creating the variable, you ensure that you will be seeding with the same value each time and will get the same sequence of numbers.  You won't sometimes repeat and sometimes not, as you do now.
If you want a different sequence each time, then just seed the randomness once per invocation of your program.  Repeated calls to srand make things less random rather than more.  You would only do this if you wanted to repeat the original results.  And frankly, if that's what you wanted, it would probably be easier to just generate the data once and make a copy for each iteration.
Calling srand once at the beginning of the program is the more typical approach.  Calling it multiple times with the same value is an option if you want to make the values repeatable in some way.  The way that you are doing it now is neither of those things.  It is neither random nor repeatable.  Sometimes it repeats and sometimes it is from a pseudorandom sequence.  Which is somewhat unpredictable, although there likely would be patterns.
I think that what you want in this situation is to seed once at the beginning of the program, so you get different values in a each time.  But it really depends on exactly what you are trying to test.
Readability

            *(a+k)=rand()%50;

It would be more common to write this
            a[k] = rand() % 50;

Now we can easily see that you are doing an array dereference.  It's also conceivable that this might have performance impact.  Because iterating over an array is something that would be done frequently and might be optimized.  Whereas pointer addition is rarer and might not be, even if identical in effect.  But I still think that the primary reason to write it this way is that it is easier for people reading your code to see what's happening.
You will also notice that I added whitespace.  This also makes it easier to see what things go together and what are different.  The compiler will remove this during tokenization, so it has impact on the executable.  But for the source code, it makes it easier for the person reading the code to figure out what it is doing.
Consistent indentation
Similarly, it will be easier to read your code if you always indent inside a block and reduce the indentation when the block ends.  This makes it easier to see where your code starts and ends.
Counting
Now to get to the question that you were actually asking.

        for( i = 2, j; i < n; i++)
        {
            int x = a[i];
            j = i;
            while(j > 1 && a[j-1] > x)
            {
                comps += 2;
                swaps++;
                a[j] = a[j-1];
                j--;
            }
            comps += 2;
            a[j] = x;
        }

Whether this is counting the comparisons correctly or not depends on exactly what you want to count.
You are not counting a comparison i < n that you are doing on each iteration of the outer loop.  I would usually think of this as something that you should measure.
You are counting two comparisons on the failure of the inner loop even when only one is done.  I.e. when j is equal to 1, you count two comparisons even though short circuiting will only do the j > 1 and not the a[j-1] > x.  Perhaps you want to count as if short circuiting does not occur.
In terms of swaps, you aren't counting either

            int x = a[i];

or

            a[j] = x;

but you are counting each

                a[j] = a[j-1];

What's a swap?  If it is an assignment, then you should count the first two.  If it is an exchange, you should not count the last one, as it is not a swap.  You are doing no "swaps" in that loop.  You are moving a block of memory.
Note that what I'd actually call a swap involves three assignments (although it's quite possible that only two of them hit memory, as one can be held in a register).  So if your improvement to insertion sort is that you are doing fewer assignments, you are counting the wrong thing.  You should be counting assignments, not swaps.

        for(i = 0; i < n-1; i++)
        {
            if(a[i] > a[i+1])
            {
                comps++;
                swaps++;
                int temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
            }
            comps++;
            i++;
        }

Comparing
I'm having trouble understanding what you consider to be "classic" insertion sort and what your revision is.  This would be easier to understand if you used functions.  Then you could call each with the same data and compare those results.  And for those of us reading your code, we could see what was different between the two functions.
That would also create more of a separation between your test setup and the sorting.  As is, those things are pretty much run together.  There isn't a clear demarcation between what is setup and what is sorting.  If your sorting were entirely in functions, then it would be clearer.  The stuff outside the functions is setup.  The stuff inside is sorting.
It would also be easier if we could see the results from both the classic and revised versions.  Perhaps they are showing data as expected.  Perhaps not.  Without the classic version, it's hard for me to see what you are trying to compare.  So it's difficult to critique it.


You should try below query, also let me know what indexes are on your tables.
  WITH cte1 as (select SUBSTR(nome_evento, instr(nome_evento, '-') + 1) as nome_evento  from contatore)
SELECT count(b.codice),
        b.codice
FROM cte1 a
INNER JOIN
sorgente b
ON (a.nome_evento = b.codice)
group by b.codice;


I would go down the simple road:

1) Converting both lists to sets

2) Use set operations:

    Set<Integer> update = new HashSet<>(list1);
    Set<Integer> insert = new HashSet<>(list1);
    Set<Integer> delete = new HashSet<>(list2);
    update.retainAll(delete);
    insert.removeAll(delete);
    delete.removeAll(update);

Done.

Even if it is not the fastest solution, it should not be too bad for only 5k objects. It is simple, readable and not errorprone.


Finding minimal number of items from an array

Scope

    static int[] solve(int arr[], int i, int esum, int csum, int size) {

You leave this as the default scope.  For Java, this is package private.

In this case, I would go with

    private static int[] solve(int arr[], int i, int esum, int csum, int size) {

The reason being that three of these parameters (i, csum, size) reflect internal knowledge of how the method works.  So I would make this private to make it clear that only people editing this class should use this method.  I would then add an additional method:

    public static int[] solve(int targetSum, int... numbers) {
        return solve(numbers, numbers.length, targetSum, 0, 0);
    }

This offers a public face to the private implementation.

I find names like numbers and targetSum easier to read than arr and esum.  In fact, I still don't know what esum is except by inspecting what it does.  Ideally, names should make it easier for me to understand the code.

This also allows solve to be called in more ways.  You can still call it

    solve(108, arr);

But you can also say

    solve(108, 70, 30, 33, 23, 4, 4, 34, 95, -50, -10, -10, -7);

If that happens to be easier.

This may not matter in real usage, but often it's easier to test in the latter form.

Object oriented

I would also consider making a class to hold the solution.  As is, the solution is held in a magic version of an int array.  What's in the array?  Which element is which?  Again, we have to go read the code to know.  I'd rather just be able to read an interface.  E.g.

public class PartialSum {

     private int distance;
     private int count;

     public PartialSumDistance(int distance, int count) {
         this.distance = distance;
         this.count = count;
     }

     public getDistance() {
         return distance;
     }

     public getSize() {
         return count;
     }

}

Now, instead of saying a1[0], I can say a1.getDistance(), which is much clearer about what is being discussed.

Optimizing the end condition

        if (i == 0) {

Consider

        if (i == 0 || esum == csum) {

If we have found a matching partial sum, we can never get closer to a solution.  We can only add additional items.  But smaller solutions are better.  So once we've found a matching sum, we can return.  This branch has nothing more to show us.  We've already found the best solution that it could find.

Sorting

If the input array were sorted (ascending), we could say

        if (csum < esum && arr[i - 1] < 0) {

And return the current solution.  We are currently as close to a solution as we could be.

Overall, there are \$2^n\$ sums to check where \$n\$ is the number of items in the array.  This is because each item can either be in or not in the sum.  So enumerating all the sums is \$\mathcal{O}(2^n)\$.  Sorting is only \$\mathcal{O}(n \log n)\$.  So we can sort for a trivial cost compared to the overall time to process the problem.  Meanwhile, we can potentially prune \$2^i\$ checks, where i is the number of elements remaining in the array as we process it.  Since i is potentially equal to \$n\$, this seems worthwhile.

Further optimization

To optimize further, we'd need to know more about how the data was meant to be used.  For example, if the number of targets to search is larger relative to \$2^n\$, it might make sense to pregenerate all the partial sums and put them in a NavigableMap or NavigableSet.  Then we could just fetch the appropriate value.  But that would be a lousy solution if we're only going to look up one target per array.


Small method for saving student attendance

First of all, minor beef. I'd reccommend that you change your index names to be more descriptive, particularly the inner one. For instance you could make your repo query

DateTime date = new DateTime(year, month, **day**);

Much more readable. When an index has a name, name it.

If you're having performance issues, try separating out the queries. In psuedocode:

foreach day in month
   get students_with_records from database

   foreach student in the_class
      if student NOT in students_with_records
         add record

This method will put the search through the student records on the client...it should be faster, since you will only have one query per day rather than one query per day per student. You really should profile the app and see if it's an issue, though.


Counting maximum number of elements in right order

This is a classical LCS problem, which can be solved in DP as suggested by earlier post. Time Complexity of the implementation is O(mn) which is much better than the original code implementation. (An exercise for the reader to study. ;-)
The next code fragment assumes that the source/target are both strings.
Here is the DP approach:
class Solution:

def lcs(self, source: str, target: str) -> int:
    n,  m = len(source), len(target)
    dp = [[0] * (m + 1) for _ in range(n + 1)]

    for i in range(n):
        for j in range(m):
            if source[i] == target[j]:
                dp[i + 1][j + 1]= dp[i][j] + 1
            else:
                dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])
    return dp[-1][-1]


play_card() method in an Exploding Kittens card game

(This is a new version of the answer based on feedback from iScrE4m who asked the question. Feel free to consul the history for the original, wrong answer.)

Readability

First, it's confusing to write code like this:

if condition:
    do_stuff()
if other_condition:
    do_other_stuff()

Because it can be mistaken with the same code using elif where only one branch is executed. And indeed, that's how I read it first. The solution is simple: add a new line between the two conditions. That's a matter of personal preference though, and some developers prefer to write compactly as you did.

What's not captured by cyclomatic complexity?

Nevertheless, it's difficult to reason about this function, simply because you're using ifs and no elsifs. So we have to think about all options: for each if that's not an elif, what happens if both conditions are true? And I don't know if card.selfcast and player is None, card.targetable and target is None and not self.ask_for_nope() can be all true or not. I'm lucky here because you're raising an exception in the first two so I can infer that you consider them exclusive, but that's more reasoning that I would have liked to make.

However, cyclomatic complexity, as defined by Thomas J. McCabe in his 1976 paper, and used by modern tools, does not capture this information. He says in the beginning of section 2 ("A complexity measure"):

  The complexity measure approach we will take is to measure and control the number of paths through a program. This approach, however, immediately raises the following nasty problem: "Any program with a backward branch potentially has an infinite number of paths." Although it is possible to define a set of algebraic
  expressions that give the total number of possible paths through a (structured) program (1), using the total number of paths has been found to be impractical. Because of this the complexity measure developed here is defined in terms of basic paths - that when taken in combination will generate every possible path.

(1) The appendix explains how it can be done.

It's not entirely clear why it's considered impractical, but I guess it makes it harder to compare programs even if does not capture the issue here. (When McCabe wrote his paper in 1976, Fortran did not have ELSE IF: it only appeared in Fortran 77, but it already had a case satement, like the switch statement in C).

Leaving cyclomatic complexity aside, what are all the paths the original code can take? Two options per if, so that's 2*2*2, ie. 8. Now, using elsif, you only have 4 options, all of them with only one statement. Much better, right?

What's captured by cyclomatic complexity?

One thing that cyclomatic complexity does capture is that "complicated" conditions count more than simple ones. So when you write if card.selfcast and player is None, this actually counts as two ifs. This is why you reach 6: 5 ifs + 1. If you want to stay within the limit, you can simply encapsulate the conditions in their own functions, which would lower the complexity to 4.

Solving your immediate issue

I'm not sure encapsulating the conditions is worth it. In this case, consider just raising the limit: 6 is quite low, and I've seen 10 used elsewhere successfully (maybe because this is the number McCabe used in his original paper, even if he says it's arbitrary). This is just at tool, and if it does not help, then stop using it. :)


A more efficient/cleaner way of scrolling a div's contents in HTML

Here are a couple of recommendations on the JS side if you choose not to use the CSS-only solution:

Use private vars with the var statement instead of instance vars
with the this statement unless you need to actually expose this
properties for public inspection or use by another object.
Don't make vScroll into a global - it is only used in the scope of setup so it can be defined inside of setup, and if it isn't global, you can pass vScroll.move by reference to setInterval instead of using setInterval's quote syntax, which requires an extra parsing step.
Use a cross-browser compatible document.ready like jQuery's, or in the very least use DOMContentLoaded. The onload event can wait for the entire document to load, including CSS, but DOMContentLoaded occurs when the DOM is available (will increase load speed).


template <typename T,
          typename = std::enable_if_t<std::is_floating_point<T>::value>>
T lerp(T a, T b, T t) noexcept;

Looks fine.  I'd prefer to see static_assert than enable_if since there's no other overloads (and if there are I'd rather fine out with a compilation error).

T lerp(T a, T b, T t) noexcept {
  return a + t * (b - a);
}

How about std::fma?

Note that GCC and Clang both do this differently...  They do b * t + a * (1-t) and have special cases for t at 0 and near 1.  Maybe it's better to just copy their code exactly so the compiler version doesn't change the output?

template <typename T,
          typename = std::enable_if_t<std::is_floating_point<T>::value>>
std::vector<T> interp(const std::vector<T>& xp, const std::vector<T>& yp,
                      const std::vector<T>& x);

There's nothing in this function that directly needs T to be a floating point type.  I think it's better to remove the enable_if and let the compiler show a traceback with the "real" reason T needs to be an FP.

This function takes vectors and returns a new vector.  That is a fine and very common pattern, but it's not optimally efficient.  If this is a hot function, you could return an iterator/some sort of range that computes the next result when it is incremented.  Boost example of this kind of thing: https://www.boost.org/doc/libs/1_66_0/libs/iterator/doc/html/iterator/specialized/transform.html.

If you want to generalize this to other iterables, then don't take std::vector... instead take a templated T const& and same for ListLerp.

[[nodiscard]] T interp(const T x) noexcept;

Suppose I want to discard the result?  Maybe I only want to store every nth item?  interp is not a const member function (one might want the mutation to happen...) and T is not an "undiscardable" type.  I don't see why this needs to be here.

I don't think you've separated your interests very well between ListLerp::interp and the free function interp.

I think there are two good options:

make ListLerp::interp a const member function and get rid of ListLerp::b.  Then the free function interp just does a "pure" transformation of a single list.
iterate all three lists in a single function (my preference).

E.g.

auto interp(vec const& a, vec const& b, vec const& t) {
    for idx = each index in a, b {
        ... Possibly emit a value corresponding to t ...
    }
}

This is very basic pseudo code, but the key idea is you iterate everything in one go rather than doing some iteration in a free function and some iteration in a class that holds potentially dangerous references.

const std::vector<T>& xp;

This (and the lines like it) is moderately dangerous since you need to ensure the vector that is passed in outlives the class.

E.g. you cannot do this:

auto fn() {
     vector<double> v;
     ListLerp ll(v); // take reference to local variable v
     return ll; // v goes out of scope; ll has dangling reference to dead v
}

Often times the best option is to take the const& and be careful about how you use it, but in this case I think it's easy enough to compute the full result in a function, not expose a class that can hold a reference to a ctor argument, and make it impossible to end up with a dangling reference.

  It assumes everything is sorted before hand - x and f(x) are the same length.

How about asserting this?

// find b position
while (x > *b) b++;

If your input is sorted, this could be a binary search.  May or may not be better.

I think your calculation at the end would be simpler if you use indices rather than iterators.  Many of the lines are basically "find the iterator in A that has the same index as this iterator in B" ... easier to say "A[i]"