Question responses

if there is a better to approach the OO design here?

It seems okay. As was pointed out in answers to your other recent questions there currently is no use of OO features like inheritance.

Did I do a good job at separating the concerns here?

The separation seems okay.
Suggestions
Simplify move method
The Rectangle method move is currently implemented as this:

move(dx, dy) {
    for (const position of this.positions) {
      const nx = position[0] + dx
      const ny = position[1] + dy
      position[0] = nx
      position[1] = ny
    }
  }

Variables nx and ny are only used once. The method could greatly be simplified:
position[0] += dx;
position[1] += dy;

functional approach to print
In the Canvas method print two for loops are used. A functional approach, similar to how the canvas is created in the constructor, would allow fewer lines and the variable rows could be assigned in one statement, which would allow const to be used, though this would not be wise to change if performance is a major concern.
print(palette) {
    const rows = this.canvas.map(column => column.map(cell => {
      if (cell === null || !cell.length) {
        return '*';
      }
      return palette[cell[cell.length - 1]];
    }).join('') + "\n" ).join('');

check parameter types
Since JavaScript is loosely typed, there isn’t much support for ensuring a method is called with parameters of certain types. However, if a method expects to be called with certain types of arguments (e.g. Canvas::draw() and ::remove() expect a Rectangle instance) then the type of those arguments can be checked - e.g. using the typeof keyword. If an argument doesn’t match an expected type then perhaps an Error should be thrown.


Getting value from a property according to some parameters

Probably the direction is correct but the class API is inconsistent for now. DateFrom is available, DateTo is not.
As for me, the following way looks more consistent.
public class MainApplication : Application
{
    public DateTime DateFrom { get; set; } = DateTime.Now;
    public DateTime DateTo { get; set; } = DateTime.Now;

    public DateTime GetSearchDate(bool isDailySearchEnabled)
        => isDailySearchEnabled || !PurchaseFunctions.HasPurchasedDateRangeSelection() ? DateFrom : DateTo;
}


I don't think that using pattern matching is necessary in this case, you only have a few simple conditions that can be better represented with a simple if. See what you think about this solution:

def getImportance(token: String, stopWords: Set[String]) =
  if (token.length() == 1 || token.length() > 15 ||
    token.matches("\\p{Punct}+") ||
    stopWords.contains(token.toLowerCase()))
      0
  else
      1

I believe it is simpler and easier to read. I think using patter matching for these simple cases only hinders the understanding of the code ;)


Nicely done, I have very little negative to say!
Most of this answer will be an exploration into some more advanced ways of doing what you are doing, overkill for this case, but very useful in larger projects.

The day as usize everywhere is a bit of a distraction. I definitely understand the desire to store a small int when your data is known to be small (i.e. at most 11), but in this case you are only using Day as an index, so using type Day = usize directly seems like better design.

However, if you want to be fancy (and/or learn a bit about implementing your own types in Rust), you have an alternative which I will describe below: the basic idea is to implement your own types (use struct A(B) instead of type A = B), then implement the Index trait to index using Day directly.
For a small piece of code like this, it doesn't make a huge difference, but for large projects it's really helpful to avoid accidental mistakes like indexing an array with the wrong variable (i.e. in your case, indexing with some random usize in context instead of a Day between 0 and 11).
If you do that you get a type error, and this also allows you to abstract better: treating Day as an opaque type that is used to get the lyrics from your lyrics objects, rather than as an integer with arbitrary functionality. As an added bonus, this also helps avoid the magic number 12 problem that you mention.
Diving in, we start by defining new types (struct A(B)) for Day and for a list indexed by Day.
The #[derive(...)] is telling Rust that we want Days to be able to be copied, checked for equality, and printed out, copying over that functionality from u8.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Day(u8);

#[derive(Debug)]
struct DayList<T>([T; 12]);

const FIRST_DAY: Day = Day(0);
const LAST_DAY: Day = Day(11);

const LYRICS: DayList<&str> = DayList([
    ...

Then, we implement the ability to index DayList objects with Day.
For a variable of type A where we defined struct A(B), we use x.0 to get the underlying B data.
(This explicitness is part of the point of doing this, we make sure to keep A variables and B variables separate.)
impl<T> Index<Day> for DayList<T> {
    type Output = T;
    fn index(&self, day: Day) -> &T {
        self.0.index(day.0 as usize)
    }
}

Finally, we want to be able to iterate over days, something like this utility function seems most useful for your code:
fn days_upto(day: Day) -> impl DoubleEndedIterator<Item = Day> {
    (0..=day.0).map(Day)
}

This takes a Day and iterates over all days up to and including it. Perhaps this seems like overkill! But we get a lot  of benefit out of it: now we can modify the rest of your code to not have indices at all, and only iterate over Days directly and index DayList with Day. Type safety! Here's how it looks:
fn main() {
    for day in days_upto(LAST_DAY) {
        if day != FIRST_DAY {
            println!();
        }

        print_first_line(day);
        print_lyrics(day);
    }
}

fn print_first_line(day: Day) {
    println!(
        "On the {} day of Christmas my true love gave to me",
        ORDINALS[day],
    )
}

fn print_lyrics(day: Day) {
    for line in days_upto(day).rev() {
        if line == FIRST_DAY && day != FIRST_DAY {
            println!("And {}", LYRICS[line]);
        } else {
            println!("{}", capitalize(LYRICS[line]));
        }
    }
}

Finally: the if block
if day != FIRST_DAY {
    println!();
}

can be avoided if you print a title with the lyrics as well, which seems realistic. E.g.:
println!("The Twelve Days of Christmas");
println!("----------------------------");
for day in days_upto(LAST_DAY) {
    println!();
    print_first_line(day);
    print_lyrics(day);
}


This is not OOP, your comment is hard coupled with mysqli. What if you would write the exact same program but now with PDO? you will have to change the Comment class.
Then performance wise: you are now opening a mysqli connection for every comment.
You seem to think that using the word 'class' and method names as 'getMyVar()' equals OOP. It doesnt.
Programming is always about problem solving, and a good program is about solving a problem in such a way you can easily reuse that solution for other sort of the same problems.
OOP is very dangerous, because it alows us programmers to write even crapper code as before. That is why some really smart guys came up with loads of rules to live by in OOP land, called SOLID: http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)
Now, lets place your code next to the SOLID rules.
1 Single responsibility principle
The Comment class fails on this account. It does multiple things as far as I can see. It works as a storage object for a Comment with methods to retrieve the parameters of the comment AND it also retrieves the comment from the Database. So we allready have a little problem here.
2 Open/closed principle
Again, not so good. An example: say I have a special sort of comment that has an extra field called 'permissions':
class PermissionComment extends Comment {}

Uh oh, In order to save the permission field into the object, I will have to rewrite the entire __construct while I only added 1 field. Not so good.
Also, all your variables are public variables. I don't need to use the get() methods to access a variable. I can access it directly. We thus violate the above rule in multiple ways. We cannot easily extend the comments functionality and we dont encapsulate it correctly
3 Liskov substitution principle
As I allready wrote somewhere at the top, say we want to change mysqli with PDO. Or we have written an extension of the mysqli object that does some caching of queries, I would now have to rewrite my Comment class because mysqli is hard coded into the object. Not so good again.
4 Interface segregation principle
This one, I will let go since it is not really in order here
5 Dependency inversion principle
Again, could be better. The Comment class i tightly coupled with your database connect. Your comment class 'knows' about the database-connection. It knows how to connect to a database. It knows how comments are stored while in fact it's just a container of comment data.
What now?
Back to the drawing board. You write you want to write a class that represents a Comment. Ok good. As example I omitted a lot of parameters in the code below, in fact, mostly because I'm lazy :p
So lets write a class that represents a basic Comment:
class Comment {

    private $id;

    private $content;

    private $title;

    public function __construct($data) {
        $this->id = $data['id'];
        $this->content = $data['content'];
        $this->title = $data['title'];
    }

    public function getId() {
        return $this->id;
    }

    public function getContent() {
        return $this->content;
    }

    public function getTitle() {
        return $this->title;
    }
}

Good, a Simple class that represents a Comment and only a Comment. But, one problem. What happend if we change the way the data is passed in. Or the key's change. and how can we be sure that that Comment class will only extract the data it needs. How does another programmer know what key's that $data array needs to have without having to read your entire code?
Let's change the constructor into:
public function __construct($content, $title) {
    $this->content = $content;
    $this->userId = $userId;
}

Ooeeh, cheecky. But huh? where did $id go?
Well, let's just say I want to create a Comment and later add it to the database, or I want to create a Comment object for testing purposes, or just a default comment to pass to the the frontend, my Comment doesn't have an id. I can now easily create a Content without needing a database id.
And for those Comments who do have an ID, we create an additional class:
class DbComment extends Comment {

    private $id;

    public function __construct($content, $userId, $id) {
        $this->id = $id;
        parent::__construct($content, $userId);
    }

    public function getId() {
        return $this->id;
    }
}

See how little code I had to write to simply add a Field to the Comment object?
But now your thinking: What a load of bull. This code can't even fetch a Comment from the database. True, but a 'Comment' object is a Comment and not a CommentFetcher.
We could now write a CommentFetcher class that fetches and saves Comments and returns a DbComment. Example:
class CommentFetcher {

    private $mysql;

    public function __construct(mysqli $mysql) {
        $this->mysql = $mysql;
    }

    public function fetch($id) {
        $stmt = $this->mysql->prepare("SELECT id, title, content FROM comment_comments WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->bind_result($id, $title, $content);
        $stmt->execute();
        return new DbComment($content, $title, $id);
    }
}

Note how i pass in a mysqli object in the constructor. All the class says is I need a mysqli object. If I now write my ThisClassCachesMysqliQueries extends Mysqli class I can simply pass it in, the CommentFetcher will have no idea I passed in a different class because it's still a mysqli object. But I will have added super duper caching into my program without having to change the CommentFetcher, cool huh?
So now we have a generic Comment class, we have a special case Comment, the DbComment. This is also a Comment but one that exists in a database somewhere and thus has an Id and we have a CommentFetcher that fetches comments from the Database.
Now a note: The code that I have written here is still crap. Don't use it ;)
A Class that can only fetch comments isn't really usefull. But you get the point, a CommentController that can update, fetch and insert Comments is something really nice.
Also I would advice you to rething how you are saving comments. Know, a comment has to know about users, ip, legacy,... While in fact all a Comment needs is a Title, data and content. A different table and controller would then look up hte user that postes the comment in the user_posted_comment table etc etc etc.
Once in a while, I take a step back an think, what am I writing? because at the end of the day, a Comment is a Comment and not some exotic objet that knows about users, ip-adresses and legacy.
But hey, atleast you are using bound params and prepared statements! Big up yoself.
I hope this answer helps you. else simply flame me in the commentbox below


Rails controller method to create a customer with credit card info

Personally, I wouldn't want to see this in a model either (at least not an ActiveRecord model).

I'd probably go with something more like this:

app/controllers/customers_controller.rb

def create
  create_customer = CreateCustomer.new(params)
  create_customer.perform
  if create_customer.success?
    redirect_to some_path, notice: 'success'
  else
    render :err_show, status: :payment_required, json: create_customer.err
  end
end

app/interactors/create_customer.rb

class CreateCustomer

  attr_reader :customer, :card, :err

  def initialize(customer, parms)
    @customer = customer
    @card = {
    'object' => 'card', 'number' => card_number, 'exp_month' => card_expire_month, 'exp_year' => card_expire_year,
    'cvc' => card_cvc, 'address_zip' => parms['zipcode'], 'name' => "#{parms['first_name']} #{parms['last_name']}",
    'address_line1' => parms['street_address_1'], 'address_state' => parms['state'],
    'address_line2' => parms['street_address_2'], 'address_city' => parms['city']
    }
    @err = nil
  end

  def perform
    resp = Stripe::Customer.create(
      description: 'Customer for DoctorNow',
      metadata: { customer_id: @customer.id },
      email: @customer.email,
      source: card)
    @customer.assign_attributes(
      stripe_customer_id: resp['id'],
      stripe_card_id: resp['sources']['data'][0]['id'],
      stripe_card_last4: resp['sources']['data'][0]['last4'],
      stripe_card_type: resp['sources']['data'][0]['brand']
    )
    event('card_preauth', 'customer_id', @customer.id)
  rescue Stripe::CardError => e
    log_error('creating_card_card_error')
  rescue Stripe::InvalidRequestError => e
    log_error('create_card_invalid')
  rescue Stripe::AuthenticationError => e
    log_error('create_card_authentication')
  rescue Stripe::APIConnectionError => e
    log_error('create_card_connect')
  rescue Stripe::StripeError => e
    log_error('create_card_stripe')
  rescue => e
    log_error('create_card_generic')
  end

  def success?
    @err.nil? && @customer.stripe_customer_id.present?
  end

  private

  def log_error(error)
    @err = stripe_error(e, error, 0)
    event('card_preauth_failed', 'customer_id', @customer.id)
  end

end


Absolute-difference function for std::size_t

This function computes absolute difference, not absolute value, so it shouldn't be called abs. absolute_difference? size_diff?

What will you use this function for? Are you using size_t for something other than sizes, so an absolute difference is meaningful?

std::max(a, b) - std::min(a, b) is harder to read than a simple conditional:

return a > b ? a - b : b - a;

This function isn't specific to size_t; it can be defined for any type that supports comparison and subtraction:

template<typename T>
T abs_diff(T a, T b) {
  return a > b ? a - b : b - a;
}

If you do want to define it only for size_t, using std::size_t would save some repetitions of std::.


Removing duplicate file references from history

The group_by_size function has multiple responsibilities:

Group files by size
Verify file
Modify attributes of the class (self.files, self.spreadsheet_reader.main_row_dict)

It would be better to reorganize your code so that each function has a single responsibility.

There is some code duplication here that could be improved:

if grouped_by_size.get(size):
    grouped_by_size[size].append(fileid)
else:
    grouped_by_size[size]=[]
    grouped_by_size[size].append(fileid)

Like this:

files = grouped_by_size.get(size)
if files is None:
    files = []
    grouped_by_size[size] = files
files.append(fileid)


Displaying all substrings of some given string

The variable names offset, current, and ending could be better.  offset seems to be distance from the end, and current acts as a starting index, so the names should reflect that.

The loop logic is cryptic.  There is a current = 0; offset++; that "resets" the loop, so it would be more clearly written with nested for loops instead.

If you do it right, you shouldn't need to check !result.equals("").  If you did need to check, then it would be better written as !result.isEmpty().

private static void displayAllCombinations(String text) {
    for (int end = text.length(); end > 0; end--) {
        for (int start = 0; start < end; start++) {
            System.out.println(text.substring(start, end));
        }
    }
}


Show/hide function with multiple div ids

You could have the hide/show divs inside a container, and then on .ready hide all its immediate children;
You could then target all a.close inside this container, and on click hide the clicked anchor's grand-grandparent;
And finally target all anchors inside the items list, and on click show the div corresponding to the anchor's rel;
I would also make the anchor's href the same as its rel, so that if any user has JavaScript disabled the anchor still works.

So, HTML:

BLAH BLAH BLAH

Close

BLAH BLAH BLAH

Close

Meet GrowLab - Canada’s Y-Combinator Arrives in Vancouver (June 24, 2011)

Building the Web's Best Entertainment-Based Community Site: Andy Liu, CEO and Founder of BuddyTV (April 1, 2011)

and a more compact and DRY JQuery:

$(document).ready(function(){
  $('#eventDescriptions>div').hide();
  $('#eventTitles a').click(function(){
    var target = $(this).attr("rel");
    $(target).show('slow');
  });

  $('#eventDescriptions .close').click(function(){
    $(this).parent().parent().hide('slow');
  })
});

Here, a JSFiddle: http://jsfiddle.net/QYjLY/

Other things I quickly noticed:

Good job on using rel;
Instead of <img border=0 ... you could use CSS - a img { border: 0;};
#social is a list, so it could be a ul instead of a div.


Functional Conway's Game of Life in JavaScript

const STEP = 50;
const WIDTH = 200, HEIGHT = 100;

var w = WIDTH, h = HEIGHT,
    xmin = (x <= 0) ? 0 : x-1, ymin = (y <= 0) ? 0 : y-1,//handle borders
    xmax = (x+2 > w) ? w : x+2, ymax = (y+2 > h) ? h : y+2;

Be consistent. I usually recommend a const/let/var per variable and a line each to to make it easy to add and remove variables as needed. No surgical removal of variables in between commas and it's easy to spot the variables.

var Game = init("screen");

setInterval(function (){//repeat the steps every 50ms
    Game.gMap = step(Game.gMap);
    draw(Game);
}, STEP);

The problem with above is that it's not kosher in terms of functional programming. Each step is mutating Game, specifically Game.gmap. If I remember correctly, the functional way to create a game loop is to use recursion and construct a new game state on each step.

function gameLoop(gameState){
  draw(gameState);
  const newState = update(gameState);
  return gameLoop(newState);
}

return gameLoop(createInitialState());

The big difference is that you don't have Game or Game.gmap that mutates on each step. Each step takes in an entirely different state object than the previous. This is inefficient given existing JS data structures, but can be optimized using persistent data structures.

But JS has no TCO yet and you'll blow away the stack if you do it in existing engines (Node.js has it under a flag). The closest you can get to maintaining a similar code structure is by scheduling the next step asynchronously using setTimeout.

function gameLoop(gameState){
  draw(gameState);
  const newState = update(gameState);
  setTimeout(() => gameLoop(newState), STEP);
}

gameLoop(createInitialState());

function init(scr) {
    var cwObj = {
        canvas: document.getElementById(scr),//set up the graphics department
        gMap: new Array(HEIGHT).fill(new Array(WIDTH).fill(0))
    };
    draw(cwObj, ptr, 30, 60);
    step(cwObj.gMap);
    return cwObj;
}

I would suggest this init function only construct state. Drawing should just be a part of the game loop.

function createInitialState(){
  return { /* initial game state */ }
}

pattern.map(function (cur, i){
    cwObj.gMap[x + i] = insert(cwObj.gMap[x + i], cur, y);
    //insert() is a helper, just inserts at an index
});

var out = '';
cwObj.gMap.map(function (cur) {     //create a string of active and
    cur.map(function (cell) {       //inactive cells
        if(cell) {out += "&#9632;";} else {out += "&#9632;";}
    });
    out += "
";
});

You are misusing array.map. array.map is meant to be a 1:1 transform of each item in an array into another. What you're doing here is a job for array.forEach. And since array.forEach does nothing but loop and return undefined, it has to be mutating something outside the callback, making it not functional.

Your first operation could be done with an array.map as it's essentially updating each value with a new value. You will have to replace the array, not mutate the existing one.

cwObj.gMap = pattern.map((current, i) => updatedValueForValueAt(i));

The second one appears to be a job for array.reduce as it is reducing the array into a single string.

const out = cwObj.gMap.reduce((prev, cur) => prev + cur.map(c => c? '&#9632;' : '&#9632;').join(''), '');

JS isn't entirely functional and you will often break rules where necessary. At best, you keep mutation to a minimal.


Varying a second drop-down's options based on a first selection

Same advice as @jfriend00, with an addition: if the user selects the "Choose Plan" placeholder, disable the billing period selector.

function populateBilling(planName) {
    //RESET BILLING PERIOD OPTIONS
    select.options.length = 1;
    document.getElementById('payment-total').innerText = 0 + additional;
    document.getElementById('payment-rebill').innerText = 0 + additional;
    //FILL BILLING PERIOD WITH PLAN OPTIONS AND VALUES
    var selectedPlan = plans[planName];
    if (selectedPlan) {
        for (var i = 0; i < selectedPlan.Option.length; i++) {
            var temp = document.createElement('option');
            temp.value = selectedPlan.Value[i];
            temp.text = selectedPlan.Option[i];
            select.appendChild(temp);
        }
    } else {
        document.getElementById('billing-price').disabled = true; // ← This
    }
}

Parsing the selection text to get a JavaScript identifier is sketchy.  I'd make the value of each option explicit.

<option value="basic">Basic</option>

etc.

function enableBilling(e) {
        document.getElementById('billing-price').disabled=false;
        var planName = plan.options[plan.selectedIndex].value; // ← This
        populateBilling(planName);

}


Using parser_combinators to parse a string

Some small style nits to fix before we dive into the meat. When specifying a variable and a type, there should be space after the :, but not before:

// label : i8,
label: i8,

I break where clauses onto the next line, with each type restriction on its own line as well:

// fn parse_passport<I>(input: State<I>) -> ParseResult<Passport, I> where I: Stream<Item=char> {
fn parse_passport<I>(input: State<I>) -> ParseResult<Passport, I>
    where I: Stream<Item=char>
{

Let the compiler use type inference as much as possible. You don't always need to specify the type of a closure variable, for instance:

// let mut label = digit().map(|i : char| (i as i8) - ('0' as i8));
let mut label = digit().map(|i| (i as i8) - ('0' as i8));

Using try! is going to be your biggest win for clarity:

// let (i,input) = match label.parse_state(input) {
//     Ok((x,n)) => (x,n.into_inner()),
//     Err(e) => return Err(e)
// };
let (i, input) = try!(label.parse_state(input));
let input = input.into_inner();

That's as far as I got with generic Rust knowledge. After reading the docs a bit, I came up with this though (note: this is my first time using this library, so I make no claims to use it well!):

fn parse_passport<I>(input: State<I>) -> ParseResult<Passport, I>
    where I: Stream<Item=char>
{
    let label = digit().map(|i| (i as i8) - ('0' as i8));
    fn to_number(string: String) -> i32 { string.parse().unwrap() }
    let fst = many1(digit());
    let comma = satisfy(|c| c == ',');

    let mut parser = label.and(fst.clone().map(to_number)).and(comma).and(fst.map(to_number));

    let ((((i, f), _), s), input) = try!(parser.parse_state(input));

    let p = Passport { label: i, body: f * 1000000 + s };

    Ok((p, input))
}

I'm certain there's a better way though. The nested tuples are a bit off-putting. Also, I feel like there should be a nice way to map over the result of the parsing so we didn't have to unpack and repack the Result, including the input. There's the straight forward but awkward:

parser.parse_state(input).map(|((((i, f), _), s), input)| {
    (Passport { label: i, body: f * 1000000 + s }, input)
})

This is the final thing I ended up at:

extern crate parser_combinators as pc;
use pc::*;
use pc::primitives::{State, Stream};

fn main() {
    match parser(parse_passport).parse("0123,456789") {
        Ok((r, l)) => println!("{} {} {}", r.label, r.body, l),
        Err(e)     => println!("{}", e)
    }
}

struct Passport {
    label: i8,
    body: i32,
}

fn parse_passport<I>(input: State<I>) -> ParseResult<Passport, I>
    where I: Stream<Item=char>
{
    let label = digit().map(|i| (i as i8) - ('0' as i8));
    fn to_number(string: String) -> i32 { string.parse().unwrap() }
    let fst = many1(digit());
    let comma = satisfy(|c| c == ',');

    let mut parser = label.and(fst.clone().map(to_number)).and(comma).and(fst.map(to_number));

    parser.parse_state(input).map(|((((i, f), _), s), input)| {
        (Passport { label: i, body: f * 1000000 + s }, input)
    })
}


Is this Android click handler using threads correctly?

@ratchetfreak's comment is correct, expanding on it here a bit:

AsyncTask is the class to use (or rather, extend and use your subclass-implementation, as AsyncTask itself is an abstract class).

You should use AsyncTask for performing operations that otherwise would block the UI-thread and thus would make your application not respond.

However, let's take a look at what your code actually does:

Creates a runnable
Gives the runnable a View, from which it takes a Context, two TextViews (and their Strings), and a Bitmap from an ImageView.
Then it creates and shows a toast - this should be done on the UI-thread and not in a background thread
Posts a runnable to your myHandler, therefore making the following code run on your UI-thread:

Create an intent
Compress a bitmap into JPEG
Puts some data into the intent
Starts a new activity

After the runnable has been created and a new thread started, you call a method that seems to want to stop your current thread!? Why on earth would you want to do that?? Let Android take care of the thread handling! That thread is not yours to stop!

Why do you create these threads?

The longest running operation that you perform in these threads is the Compress a bitmap into JPEG, which you run on the UI-thread anyway. The few things that you do in background is so fast that you really don't need to create a new thread for it.

If your Compress a bitmap into JPEG operation takes much time, then I would suggest you create an AsyncTask<Bitmap, Void, byte[]> to handle that. (Bitmap is the input, it does not have any progress update and therefore it says Void, and it returns a byte[] which you will send to the next activity). I don't think you need any AsyncTask at all here though.

Your new code:

With the above comments taken into consideration, here's the code you need. No extra threads. If this code causes your app to stop respond for a longer while than what is comfortable, then you can consider an AsyncTask.

myList.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, final View view,
            int position, long id) {
        Context context = view.getContext();
        String titleItem = (String) ((TextView) view.findViewById(R.id.titleItem)).getText();
        String descItem = (String) ((TextView) view.findViewById(R.id.descItem)).getText();
        Bitmap bitmap = (Bitmap) ((BitmapDrawable) ((ImageView) view.findViewById(R.id.imgItem)).getDrawable()).getBitmap();
        Toast.makeText(context, "Item Title: " + titleItem + ", Item Desc: " + descItem, Toast.LENGTH_SHORT).show();

        Intent intent = new Intent(getApplicationContext(), ItemDetails.class);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] bytes = stream.toByteArray();

        intent.putExtra("title", titleItem);
        intent.putExtra("BMP",bytes);
        intent.putExtra("desc", descItem);
        Log.i("ON ITEM CLICK", "OK");
        startActivity(intent);
    }
});

Normal usage of AsyncTask

Whenever you have a longer running computational-intensive operation, then you can consider an AsyncTask. Also whenever you do network operations (download a file from internet, create a long-running socket-connection, etc.), then you need an AsyncTask. As said already, I don't think your current code needs/benefits from an AsyncTask.

Consider, however...

Your ImageView known as view.findViewById(R.id.imgItem) must have gotten its drawable from somewhere. Is it loaded from a file on the external storage? Is it loaded from a resource? Rather than compressing the drawable's bitmap data and sending the byte array, consider informing your new activity about where it can find the original data. If it's a file on the external storage, pass along a String for the path it is found in. If it's a resource in your application, pass along the resource int identifier.

If the drawable is loaded from the internet or dynamically created, then I agree about compressing it as JPEG and sending the byte array to the new activity.


Educated guesses are: in this case, loop unrolling will probably feature in a big way, and may account for most of the 20X improvement. Additionally, with the loop unroll it may make other things like instruction-level-parallelism more effective, and even cache-line management.
There are essentially only two comments to make on your situation:

non-optimized code is going to be slower.... you pay money for the compiler for a reason, lots of smart people make it 'go fast'.
you need to inspect the instruction-level code (asm) generated by the compiler in order to understand the main differences between the two versions ... anything else is just educated guessing.

Edit
FWIW, Purely for interest sake.... , you may want to try to manually unroll your inner-most loop, and see if this makes a significant difference:
        for (auto it = units.begin() + n; it != (units.begin() + (n + j + 1)); it++)
        {
            sizesMap[1] += (*it).sizes[1];
            sizesMap[2] += (*it).sizes[2];
            sizesMap[3] += (*it).sizes[3];
            sizesMap[4] += (*it).sizes[4];
            sizesMap[5] += (*it).sizes[5];
            sizesMap[6] += (*it).sizes[6];
            sizesMap[7] += (*it).sizes[7];
            sizesMap[8] += (*it).sizes[8];
            sizesMap[9] += (*it).sizes[9];
            sizesMap[10] += (*it).sizes[10];
            sizesMap[11] += (*it).sizes[11];
        }


You can use Array.prototype.filter.
You can read like this: return an array that only has the elements which satisfies the return function expression.
This way, you can avoid instantiating an array and only after this iteration to make the push.

var numList = [];
while(numList.length < 5){
  numList.push(window.prompt());
}

var evenNumbers = numList.filter(function (element) {
  return element % 2 === 0
});
// that's the same that
// var evenNumbers = numList.filter(element => element % 2 === 0);

document.write(evenNumbers);

Although, you can use arrow functions, that has a cleaner syntax.


I am not the expert but you are creating too many threads. If possible create 5-10 threads. Whats happening here its creating too many threads and each thready try to access the resources, probably application spending too much time in sync. Try to do this. If parent directory have 5-10 sub folder(s) create one thread for each subfolder then scan subfolder using that thread only.
If you have 100 subfolders under main folder, then create 10 threads and pick subfolders in 10 blocks each. I'll try to give you sample code.


A bit of honesty

When starting to review your code, I found it unintelligible and I was unable to follow the logic. I was able to understand what you are trying to do but not your implementation so I will post a few improvements here.

Structure

There is no need for the for loop in the body. You can see this as you do not use the value you gain from the interand. Because of this, we can cut the loop out.

.lower()

We can strip checking for a lowercase or uppercase answer by using .lower(). This takes a string and returns the all lowercase equivalent. This means we can strip the user input check to: if start.lower() == "y":

Walrus operator

New in Python 3.8 is the walrus operator! It looks like this :=. We can use this in the while loop as it can handle prompting the user to quit. We can combine this with the .lower() to simplify the while loop.

Unused import

Despite importing random.seed you never use it, we can remove it from the imports.

Final code

from random import randint
dice = [
[[1],[2],[3]],
[[4],[5],[6]],
[[7],[8],[9]]
]

def diceroll():
    """Loop over dice and print the value"""
    start = input("do you want to play dice Y/N ")
    if start.lower() == "y":
        print(dice[0])
        print(dice[1])
        print(dice[2])

        while (x := input("Do you want to roll the dice?  [y/n]: ").lower()) == "y":
            roll=randint(1,9)
            print(roll)
    else:
        print("GoodBye: ")

Further improvements

The function uses a global variable which is a bad practice, it is much better to give the function the global variable as an argument. I did not know if you wanted the dice array for something else, so I left it as it is. Also I question the need for a dice array in the first place, but again, this is your code with your own spec.


Two things you can improve:

Retry in all error cases by doing the recursive call in the catch function.
And limit the number of retries

_getUser (url, triesRemaining) {
    console.log('fetching url', url)
    return fetch(`$(url)/api`, {
      method: 'POST',
      headers: {},
      body: '{"key" : "body"}'
    })
    .then((response) => response.json())
    .then((responseData) => {
      console.log('Getting responseData', responseData)
      if (responseData[0].error) {
        alert(responseData[0].error.description)
        throw new Error();
      } else alert('User Created')
    })
    .catch((error) => {
      console.log(error)
      if(triesRemaining>0) {
        return _getUser(url,triesRemaining-1)
      } else {
        throw new Error('Could not create user. Max amount of tries reached');
      }
    })
  }


Check if two types are the same without template instantiations

If you're using clang or GCC ≥10, you can use the __is_same(type1, type2) intrinsic.
For portability:
#if !defined(__is_same) && (!defined(__clang__) || !defined(__GNUC__) || __GNUC__ < 10)
#define IS_SAME(T1, T2) std::is_same_v<T1, T2>
#else
#define IS_SAME(T1, T2) __is_same(T1, T2)
#endif


Function that assigns names to a struct using strtok

I see some things that may help you improve your code.

Use whitespace to improve readability

Lines like this:

for( i=0; i<sizeof(names); i++ )

become easier to read with a bit more whitespace:

for (i = 0; i < sizeof(names); i++)

Prefer ++i to i++ in loops

There is not a big difference for most uses, but if you don't need to save the pre-incremented value, make it simple for both the reader and the compiler and say ++i.  This also will help when you start using C++ iterators which often only implement the prefix ++ operator.

Declare the loop exit condition at the top

The code currently contains these lines:

for (i = 0; i < sizeof(names); i++) {
    if (names[i] == NULL)
        break;

So the for loop claims that the loop exits when i >= sizeof(names) but the following line says we exit when names[i] == NULL.  In this program, only latter is actually used, so the loop should be written to reflect that:

for (i = 0; names[i] != NULL; i++) {

Similarly, the printing loop can be simplified:

for (i = 0; p1[i].prenom[0]; ++i) {
    printf("%s\t\t%s\n", p1[i].prenom, p1[i].nom);
}

Eliminate unused variables

Unused variables are a sign of poor code quality, so eliminating them should be a priority.  In this code, j is defined but not used. Your compiler is probably also smart enough to tell you that, if you ask it to do so.  Also, the code includes a number of unused #defines, one unused typedef and one unused struct member, all of which just add to clutter in the code.

Use only required #includes

The code has #include <time.h> but nothing from that header is used.  This clutters the code and makes it more difficult to read and understand.  Only include files that are actually needed.

Use const where practical

The current code does not  modify the names array, and so it should be declared const:

const char const *names[] = {

Use stdbool

Instead of defining your own values for true and false, you might consider instead using #include <stdbool.h> which defines true and false.  However, in this program, neither is used.

Free memory that you allocate

This program leaks memory because you have allocated space using malloc but never released with free.  That's bad practice.

Eliminate useless code

The code currently contains this loop:

while (pch != NULL) {
    strcpy(p1[i].nom, pch);
    pch = strtok(NULL, " ");
}

This has the effect of copying each word in the name and only saving the last one which is not very efficient.  See the next suggestion for a more efficient means.

Use the appropriate library function

Instead of copying the string and using strtok, I'd recommend that the code should use strchr.

for (i = 0; names[i] != NULL; i++) {
    char *pch = strchr(names[i], ' ');
    if (pch == NULL || pch-names[i] > MAX) {
        strncpy(p1[i].prenom, names[i], MAX);
    } else {
        strncpy(p1[i].prenom, names[i], pch-names[i]);
        strncpy(p1[i].nom, pch, MAX);
    }
    p1[i].nom[MAX-1] = '\0';
    p1[i].prenom[MAX-1] = '\0';
}

Note too, that this code uses the safer strncpy and also assures that each string is properly terminated with '\0'.

Make sure your data structures are big enough

With only 10 characters allocated for both nom and prenom, many names simply won't fit. "Ludwig van Beethoven" is one such example.

Eliminate return 0 at the end of main

Since C99, the compiler automatically generates the code corresponding to return 0 at the end of main so there is no need to explicitly write it.


Displaying random elements for a quiz app

I assume your sets won't actually look like that, and that was just for the sake of this example.  Right now you're doing the same operation on a bunch of virtually identical things - this is exactly the use case for a for-loop.

First we need to put all of our questions into an array of arrays, and then we can loop over them and do whatever we want.  I made a few other changes as well - by using the nth-child() selector I don't have to have the ids - you can switch between the two methods by changing which lines are commented out.  You can run this code snippet and see how it works down below.

function populateQuestions() {
  var questionSets = [
    ["Set 1 Question 1", "Set 1 Question 2", "Set 1 Question 3", "Set 1 Question 4", "Set 1 Question 5"],
    ["Set 2 Question 1", "Set 2 Question 2", "Set 2 Question 3", "Set 2 Question 4", "Set 2 Question 5"],
    ["Set 3 Question 1", "Set 3 Question 2", "Set 3 Question 3", "Set 3 Question 4", "Set 3 Question 5"],
    ["Set 4 Question 1", "Set 4 Question 2", "Set 4 Question 4", "Set 4 Question 4", "Set 4 Question 5"],
    ["Set 5 Question 1", "Set 5 Question 2", "Set 5 Question 5", "Set 5 Question 4", "Set 5 Question 5"]
  ];

  for (var setIndex = 0; setIndex < questionSets.length; ++setIndex) {
    var questionSet = questionSets[setIndex];
    var questionIndex = Math.floor(Math.random() * questionSet.length);
    var question = questionSet[questionIndex];
    var selector = '#questions li:nth-child(' + (setIndex + 1).toString() + ')';
    //var setId = 'set_' + (setIndex + 1).toString();
    document.querySelector(selector).innerHTML = question;
    //document.getElementById(setId).innerHTML = question;
  }
}

First question

Second question

Third question

Fourth question

Fifth question

<button type=button onclick="populateQuestions()">Populate the questions!</button>

I do have one potential concern - right now you're still presenting the sets in the same order, but you might want to randomize what order the sets appear in. I'll leave that as an exercise to the reader, but it isn't much more complicated than this. You might also want to not present questions that have already been seen before, which is a little tricky. You either want to remove them from the sets once they've been used, or have an object to keep track of ones that have already been used.

Lastly, it might be worthwhile to write a function like getQuestions that looks like this

function getQuestions(callback) {
    // do something to get the questions
    var questions = ...;
    // once the questions are ready, use the callback
    callback(questions);
}

function populateQuestions(questionSets) {
    // same code, minus the creation of questionSets
}

getQuestions(populateQuestions);

We use the callback so this can become an asynchronous method - if you ever wanted to get this data via AJAX, or a web-service, or database, or wherever, it becomes much easier to integrate that into your workflow.


Calculate total, minimum, maximum and mean from a set of distances

I guess std_lib_facilities is a header from the book? It's best to get used to including the standard library headers directly as soon as possible.

If std_lib_facilities contains using namespace std; note that this is bad practice.

In this case, we only need:

#include <vector>
#include <iostream>

"Hungarian" notation (adding type information to the names of variables), is not generally recommended. As such, the variable names should not be ddistance, cgoagain etc., just distance and goagain.

Using camel case or underscores may make them easier to read, and it's generally better to use whole words instead of abbreviations, e.g. totalDistance.

While C once had a requirement for all variables to be declared at the start of a block, C++ does not. Variables should be declared as close to their point of use as practical. As such, ddistance and cgoagain can be moved to just above where they are populated from std::cin.

Since you're storing the greatest and shortest distances, there's no need to iterate the whole vector of distances when a new value is entered. We can simply compare against the existing value. However, this won't work when initializing the greatest and shortest values to zero!

We can use another part of the standard library to initialize the greatest value to something that will always be smaller than a valid double input, and the shortest value to something that will always be larger. That way the first input will override both values successfully:

#include <limits>
...
double greatest = std::numeric_limits<double>::lowest();
double shortest = std::numeric_limits<double>::max();

...
        if (distance > greatest)
            greatest = distance;

        if (distance < shortest)
            shortest = distance;

Note that with this change, there's actually no need to keep a vector containing all the distances. We can just keep a count of the number of values entered and use that to calculate the mean.

Altered code:

#include <vector>
#include <iostream>
#include <limits>

int main()
{
    double totalDistance = 0;
    double greatest = std::numeric_limits<double>::lowest();
    double shortest = std::numeric_limits<double>::max();
    unsigned int distancesEntered = 0;

    while (true) {

        std::cout << "Enter a valid 'double' ";

        double distance = 0;
        std::cin >> distance;

        if (std::cin) {

            ++distancesEntered;

            totalDistance += distance;

            if (distance > greatest)
                greatest = distance;

            if (distance < shortest)
                shortest = distance;

            std::cout << "distancesEntered is\t" << distancesEntered << "\n";
            std::cout << "totalDistance is\t" << totalDistance << "\n";
            std::cout << "The mean distance is\t" << totalDistance / distancesEntered << "\n";
            std::cout << "The greatest distance is\t" << greatest << "\n";
            std::cout << "The shortest distance is\t" << shortest << "\n";
        }

        else {
            std::cout << "That is not a valid value. Would you like to try again? 'y' / 'n' \n";
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

            char goAgain = 0;
            std::cin >> goAgain;

            if (!(goAgain == 'y' || goAgain == 'Y')) {
                break;
            }
        }
    }
}


How to refactor code to abstract data from a complex object into a single object without using foreach statements

First of all, there is a bug in your example. In this loop:

foreach (var geo in con.Geometries)
{
    data.DateTime = geo.Date;
    Event.Add(data);
}

You are just overwriting date in the same object. You should create a new object instead. Your final list will have the same object twice with the same date.

As for better solution for this, you can use linq and create something like this:

IEnumerable<EventDTO> events =
    from e in content.Events
    from c in e.Categories
    from g in e.Geometries
    select new EventDTO { Id = e.Id, Title = e.Title, CategoryTitle = c.Title, DateTime = g.Date };


Replace anchor tags and force create new tag with custom attributes

I must recommend that you favor accuracy over performance.  After all, what good is a fast loading site if it doesn't provide the correct/intended content.

When parsing valid html, please always leverage a good dom parser.  Regex is "dom-unaware" and therefore is more vulnerable to breakage.

Here is a demonstration of how to use DOMDocument and XPath to articulately replace hyperlinks in your document in a stable manner:

Code: (Demo)

$html = <<<HTML

hello FYI later
no quoted attributes
<A href="https://external.com"
title="some title"
data-key="{\'key\':\'adf0a8dfq<>*1$4%\'">a link with data attribute
and
this is not a hyperlink but simply an anchor tag
Jumper

HTML;

$internal = 'https://example.com';

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//a[@href]") as $node) {
    $replacementNode = $dom->createElement("a", $node->nodeValue);
    $href = $node->getAttribute('href');
    $replacementNode->setAttribute('href', $href);
    if($href[0] != "#" && stripos($href, $internal) === false) {
        $replacementNode->setAttribute('rel', 'nofollow noopener');
        $replacementNode->setAttribute('target', '_blank');
    }
    $node->parentNode->replaceChild($replacementNode, $node);
}
echo $dom->saveHTML();

Output:

hello FYI later
no quoted attributes
a link with data attribute
and
this is not a hyperlink but simply an anchor tag
Jumper

Will this be slow?  Well, I presume it will be slower than regex but then that is the cost of implementing a superior processing tool.  If you need to gain performance, investigate other avenues which will not spoil your content.  This is not a task where a shortcut is a good idea.


For one, I'd use the << operator rather than push just out of convention.

Second, you still have other Array/Enumerable methods at your disposal. So there's no need to create a new array and add unique items to it. Try filtering the array instead.

Update: Whoo boy, I was still asleep when I wrote that first answer. In my defense it was early

You can actually just do

def uniq(&block)
  group_by(&block).values.map(&:first)
end

As for my previous answer... well, I did say it could be done better. Just pretend it didn't happen.


Implementing a hash table

This hash table implementation is a bit limited: it supports only String keys and int values. It would be good to generalize it.

When getting a value of a key not in the table, the common expected behavior is null. Since you're using int as the type of values, this is not possible, but -1 just doesn't seem special enough to be commonly understood as "missing value".

The toAscii method is very bad:

It's only used internally, so it shouldn't be public
The name doesn't describe very well what it does: converting a string to ascii sounds more like an encoding transformation than a hash code calculation. It would have been better to call it calculateHashCode, and make it return a BigInteger
Even better would have been to use String's very own hashCode, rather than reimplementing your own

Naming

    HashMap entry = new HashMap();

"entry" is an inappropriate name for a map. "map" would seem the obvious choice.

General coding issues

The HashEntry class is an implementation detail of your hash table.
As such, it would be best to hide this class,
by making it a private static class inside the hash table.

Instead of this:

new BigInteger(((Integer)TABLE_SIZE).toString());

A much better and simpler way:

BigInteger.valueOf(TABLE_SIZE);

Limit variables to the smallest scope possible,
to prevent accidental changes outside their intended purpose.
For example in this code:

      long asciiInt;
      // loop through all values in the string, including blanks
      for (int i = 0; i < s.length(); i++){
          //getting Ascii value of character and adding it to the string.
          char c = s.charAt(i);
          asciiInt = (int)c;
          sb.append(asciiInt);
      }

asciiInt should have been declared inside the loop.

This code looks very confused:
you get a char, cast it to an int to store in a long variable.
This could have been simply:

    for (int i = 0; i < s.length(); i++){
        sb.append((int) s.charAt(i));
    }

And even simpler with a for-each loop:

    for (char c : s.toCharArray()) {
        sb.append((int) c);
    }

        table = new HashEntry[TABLE_SIZE];
        for (int i = 0; i < TABLE_SIZE; i++)
              table[i] = null;

When iterating over all elements of an array,
I recommend using the array's length as the limit.
It's safer. Like this:

        table = new HashEntry[TABLE_SIZE];
        for (int i = 0; i < table.length; i++) { ... }

But since you're only using this loop to assign the values to null,
the entire loop is pointless, you can safely delete it.

It's highly suspicious when you compare objects using != like you do for the keys in this code:

    while (table[hash] != null && table[hash].getKey() != key)
        hash = (hash + 1) % TABLE_SIZE;

For example, what do you think this code will print:

    String key1 = new String("Jack");
    String key2 = new String("Jack");
    entry.put(key1, 11);
    entry.put(key2, 21);
    System.out.println(entry.get(key1));
    System.out.println(entry.get(key2));

It will print 11 and 21. I suggest to replace != on objects everywhere with .equals(...). Then these two keys will be considered equal, as usually expected from a hash map, and the print statements will return 21 and 21.

Other coding style issues

I suggest using braces { ... } even for single-statement blocks
Instead of comments like /* function to retrieve value from the table according to key */, use proper JavaDoc, for example:

/**
 * Retrieve value from the table according to key
 *
 * @param key the key to look for
 * @return the value of the key, or null if doesn't exist
 */

Since the fields of HashEntry never change, you can make them final
This code block appears twice:

while (table[hash] != null && !table[hash].getKey().equals(key))
    hash = (hash + 1) % TABLE_SIZE;

Avoid code duplication. Extract to a private helper method,
or refactor your implementation in a way that you don't have to duplicate code.

Same note for this code:

int hash = new BigInteger(toAscii(key)).mod(new BigInteger(((Integer)TABLE_SIZE).toString())).intValue();

Improved implementation

Taking some of the suggestions above,
the implementation can be simplified and improved:

private int calculateHashCode(String key) {
    int mod = key.hashCode() % TABLE_SIZE;
    return mod < 0 ? mod + TABLE_SIZE : mod;
}

private int findIndex(String key) {
    int index = calculateHashCode(key);
    while (table[index] != null && !table[index].getKey().equals(key)) {
        index = (index + 1) % TABLE_SIZE;
    }
    return index;
}

public int get(String key) {
    int index = findIndex(key);
    return table[index] == null ? -1 : table[index].getValue();
}

public void put(String key, int value) {
    table[findIndex(key)] = new HashEntry(key, value);
}


Completely static builder implementation

I'm afraid and sorry to say that your code does not make a lot of sense.

A Builder is supposed to build an object. As such it replaces the constructor. That builders allow for chained method calls using return this is some syntactic sugar that's frequently used for builders. However, return this doesn't turn an arbitrary class into a Builder.

A Builder is used when it adds value over a regular constructor call. There are various reasons why one would introduce a Builder, to name a few:

The constructor call would be too complex or confusing.
A set of similar objects shall be created which differ in only a few elements.
To allow multiple method calls until the object is created while still retaining immutability for the final object.

The general expectation is that neither Builders nor classes created by them are Singletons, and that Builders and the constructed objects are independent of each other, that is, that they do not have side effects on each other.
In other words, one can create two Builders, and those two Builders would have nothing in common but being Builders for the same class. And then call build() on each of them, and end up with two different objects of possibly the same class but otherwise unrelated with each other.

The source of this is the massive over-use of static on non-final fields. Using static for fields without making them final is almost always a mistake.

More confusing things are

static Setters
Setters which have side effects on something else, something seemingly unrelated

Also, have you ever thought of the testability of the code in question?


Finding the closest point to a list of points

It will certainly be faster if you vectorize the distance calculations:

def closest_node(node, nodes):
    nodes = np.asarray(nodes)
    dist_2 = np.sum((nodes - node)**2, axis=1)
    return np.argmin(dist_2)

There may be some speed to gain, and a lot of clarity to lose, by using one of the dot product functions:

def closest_node(node, nodes):
    nodes = np.asarray(nodes)
    deltas = nodes - node
    dist_2 = np.einsum('ij,ij->i', deltas, deltas)
    return np.argmin(dist_2)

Ideally, you would already have your list of point in an array, not a list, which will speed things up a lot.


Your random_rearrange_num function has a bias.  If you want an equal chance of getting every permutation, implement something like the Fisher-Yates shuffle.  Your implementation is actually a common implementation error.  You can read about it here.

I would implement it as follows: (my C is mighty rusty and I don't have a compiler on hand to verify syntax or correctness)

void random_rearrange_num(int p[][numCols])
{
  int r, k, l, temp;
  for (int i = numRows * numCols - 1; i > 1; i--)
  {
    r = rand() % i; //select from only the remaining numbers
    k = r / numRows;
    l = r % numRows;
    temp = p[i][j];
    p[i][j] = p[k][l];
    p[k][l] = temp;
  }
}


I'll put some comments inline to the code, and in the end add a complete implementation of the program, with various changes to improve the execution.

program BA
 implicit none
 integer, parameter :: N = 20

For real numbers it is advisable to introduce a real kind with selected_real_kind:

 integer, parameter :: rk = selected_real_kind(15)
 integer :: A(n,n)

Use the real kind introduced above, to declare the reals:

 real(kind=rk) :: r, p, r2(2), pj
 real(kind=rk) :: sumA_q
 integer :: sumA
 integer :: m0, i, j, L0, N1, t, jnod, k, di

Often it is better to use more than single characters for variables (for example something like iNode or iEdge, this makes it visible what the iterator is actually used for.

 integer :: edge_number, ii, ie, je, degree

 A = 0
 m0 = 5 ! initial nodes
 L0 = 4 ! initial edges
 ii = 0
 ! adding m0 nodes with random connections
 rand_cnx: do ! while is actually deprecated, you anyway use 'if exit' in the
              ! loop, so I'd stick to that one. Using a block label to allow
              ! the identification of the loop in the exit statement.
   do ie = 1, m0
     call random_number(r)

You could create a bunch of m0 random numbers all at once here, and use them then subsequently. That might be a little faster, but probably has no really big impact.

     je = r * (m0 - 1) + 1
     if (A(ie,je) == 0 ) then
       A(ie,je) = 1
       A(je,ie) = 1
       ii = ii + 1
       if (ii>=L0) EXIT rand_cnx

No need to compute another random number here, if the limit was reached, leave the loop. Use a block label to directly leave the outer loop.

     end if
   end do
 end do rand_cnx

 edge_number = L0
 N1 = m0
 degree = m0

 ! Precompute sum of submatrix up to m0-1
 sumA = sum(A(1:m0-1, 1:m0-1))

 ! adding remaining nodes with pereferential attachment
 do t = 1,N-m0
   di = 0
   N1 = m0 + t

The summation over the subarray does not depend on the random numbers (only entries outside the subarray at N1 are modified, if I am not mistaken) and can be pre-computed. As N1 is linearly increasing, we can update the sum of the submatrix up to N1, by just adding the newly filled column and row from the previous iteration.

   ! Update sum of submatrix with the previously computed column and row.
   sumA = sumA + sum(A(1:N1-1,N1-1)) + sum(A(N1-1,1:N1-2))
   sumA_q = 1.0_rk / real(sumA, kind=rk)

   do
     call random_number(r)
     jnod = r * (N1-2)+1
     pj = sum(A(jnod,1:N1-1))*sumA_q
     call random_number(r)
     if ( r<pj .and. A(N1,jnod)==0 ) then
        A(N1,jnod) = 1
        A(jnod,N1) = 1
        edge_number = edge_number + 1
        di = sum(A(N1,1:N1))
        if (di >= degree) EXIT
     end if
   end do
 end do

 do i = 1,N
    write(12,"(*(I5))") (A(i,j),j=1,N)
 end do
end program BA

With a little more memory effort, you could also precompute all sum(A(jnod,1:N1-1)), use them for the summation of the complete submatrix and in the computation of pj, instead of recalculating the sum everytime the random number picks a specific jnod. This would result in turning the di into an array of length N. Implementing this led me to find that the first additional node has to be connected to all previous nodes, as you set degree=m0. In this case no randomness seems to be involved? I catch this special case in the implementation below:

program BA
  implicit none
  integer, parameter :: N = 20

  integer, parameter :: rk = selected_real_kind(15)
  integer :: A(n,n)

  real(kind=rk) :: r, pj
  real(kind=rk) :: sumA_q
  integer :: sumA
  integer :: m0, i, j, L0, N1, t, jnod
  integer :: di(N)

  integer :: edge_number, ii, ie, je, degree

  A = 0
  di = 0

  m0 = 5 ! initial nodes
  L0 = 4 ! initial edges

  ! adding m0 nodes with random connections
  ii = 0
  rand_cnx: do

    do ie = 1, m0
      call random_number(r)
      je = nint(r * (m0 - 1)) + 1
      if (A(ie,je) == 0 ) then
        A(ie,je) = 1
        A(je,ie) = 1
        di(ie) = di(ie) + 1
        di(je) = di(je) + 1
        ii = ii + 1
        if (ii>=L0) EXIT rand_cnx
      end if
    end do

  end do rand_cnx

  edge_number = L0
  N1 = m0
  degree = m0

  ! Precompute sum of submatrix up to m0-1
  sumA = sum(di(:m0-1)) - sum(A(:m0-1,m0))

  ! adding remaining nodes with pereferential attachment
  do t = 1,N-m0
    N1 = m0 + t

    ! Update sum of submatrix with the previously computed column and row.
    sumA = sumA + sum(A(:N1-2,N1-1)) + di(N1-1)
    sumA_q = 1.0_rk / real(sumA, kind=rk)

    need_all: if (N1-1 == degree) then

      ! Need all nodes to fulfill degree, no randomness required?
      A(N1,:N1-1) = 1
      A(:N1-1,N1) = 1
      edge_number = edge_number + N1-1
      di(:N1-1) = di(:N1-1) + 1
      di(N1) = di(N1) + N1-1

    else need_all

      do
        call random_number(r)
        jnod = nint(r * (N1-2))+1
        ! Only consider not yet connected nodes.
        if (A(jnod,N1) == 0) then
          pj = di(jnod)*sumA_q
          call random_number(r)
          if ( r<pj ) then
             A(N1,jnod) = 1
             A(jnod,N1) = 1
             edge_number = edge_number + 1
             di(N1) = di(N1)+1
             di(jnod) = di(jnod) + 1
             if (di(N1) >= degree) EXIT
          end if
        end if
      end do

    end if need_all

  end do

  do i = 1,N
     write(12,"(*(I5))") (A(i,j),j=1,N)
  end do

end program BA

No guarantees, that this is in any way correct. I guess, this could be further increased by just picking the random nodes out of the not yet connected ones. This would imply that you need to keep an index list of all 0 values for the current node, and then use jnod to pick out of those. This would be more involved book-keeping but would reduce the number of guesses, you need to do.


Add three integers and report the sign of the sum

Use shorthand for addition, multiplication, division etc.

E.G instead of this.total = this.total + number;

do: this.total += number;

You have a lot of code repetition with these two methods. Anytime you copy & paste, you should be asking yourself if you can make the code shorter.

With your overloaded method, it's easy. Just change your no-arg constructor to call the other:

public void status(){
    status(this.total);
}

You may also want to change the name to printStatus. You can further reduce the code, since all of the if statements print a lot of the same characters

E.G:

public void status(total){
    String status = "The sum is ";

    if(total<0) {
            status += "negative.";
    } else if (total>0) {
            status += "positive";
    } else {
           status += "equal to zero.";
    }

    System.out.println(status);
}


Okay, I'll throw in a review. The part more directly addressing your question is at the end

Naming

Usually in C# you will see PascalCase used for public members. For private members, it's a bit more varied, but _camelCase (note the prefixed underscore) is quite popular. What I've never seen before is ALLCAPS for public members. You can of course choose your own casing conventions for your project, but in general it's a positive to be consistent with the conventions of the language. It's helpful when working in a group or contributing to open-source, and it's also helpful to keep code you write consistent in appearance with code you call from other libraries (including the core .NET libraries)
Casing aside, not all of your variables are well-named:

args is not a good name for the variable you pass in to the Point constructor. You already have a name for these, values, so why not keep consistent?
Having said that, Values isn't actually a great name either. A point doesn't have "values", it has "coordinates", so that might be a better name.
temp inside your ToString method isn't ideal either. It's declared on the first line of the method, and returned at the end, that's about as not-temporary as a local variable can get! I generally use result here, though I know some people hate it.
Likewise, temp inside your Distance and Midpoint methods can be renamed along the same principle of giving it a meaningful name which describes what the variable actually is.

Cleaning up code

A few bits and pieces that can be expressed more concisely and readably

You don't need to declare a separate backing field for VALUES, C# has some nice syntactic sugar to do this for you:

public List<double> VALUES { get; set; }

This works exactly the same way as what you have, except that since the values field no longer exists, you will have to update the first line of your constructor to use VALUES instead.
The SameDimension method can be much more concisely expressed as

public static bool SameDimension(Point point1, Point point2)
{
    return point1.DIMENSION == point2.DIMENSION;
}

You can also get rid of the loop (and the hard-to-name variable along with it) in ToString()

public override string ToString()
{
    return "( " + String.Join(", ", VALUES) + " )";
}

Don't Repeat Yourself

Generally this adheres pretty well to the Don't Repeat Yourself (DRY) principle. One place where I see repeated logic is in the check for the exception you're describing in the question. This can be moved out to its own method:

private static void ValidateSameDimension(Point point1, Point point2)
{
    if(!SameDimension(point1, point2))
        throw new MismatchingDimensionsException(); // Or whatever you decide to call it
}

Then you can just call ValidateSameDimension at the top of methods which need that validation.

Using Exceptions

Your approach, using an exception in the case of trying to perform an action between points of different dimensions, is good. But what you've written about it is actually a little contradictory. So trying not to move too far outside the realm of a code review, here's some advice about how should use exceptions.

As a basic review of exceptions, when an exception is thrown from a method, that method immediately terminates and it is passed up to the next method in the call chain (the one that called it), and continues being passed up until it is caught.

So let's say I write a method which calls DoFoo(), and I know that DoFoo() can throw a particular exception. My options are more or less as follows:

Surround DoFoo() with try...catch because I know how to fix (or attempt to fix) the problem that the exception represents, or because I know I can safely ignore the exception. An example of this is if DoFoo() involves a remote webservice call, and I want to retry the first time I get an exception from it, in case it was a temporary connectivity problem
Surround DoFoo() with try...catch but re-throw it from within the catch. This is because I can't actually handle or ignore it, but there's something else I need to do before kicking it on up the call chain. Maybe I want to log it, or maybe there's some important clean-up I need to do inside a finally block.
Surround DoFoo() with try...catch not because I can properly handle it, but because it's vital that my program doesn't actually terminate. This could be the case, for example, on a server-side process with an exception caused by a request sent by a client. It can't do anything more useful than log and display an error message to the client, but it needs to catch the exception so that it doesn't crash and stop processing requests altogether.
Don't surround DoFoo() with try...catch. This is when I can't do anything more useful than pass it on up through the call chain, either to be handled higher up, or bubble up all the way to terminate the program with an error.

So, looking through those options, you'll probably see that in your case, generally the best one will be the last. This will actually have the opposite effect to what you were worried about. Not trying means that your Vector (for example) won't silently fail and return null, instead it will cease operating and the exception will keep bubbling on up. On the other hand, if you do surround it in a try block and leave the catch empty, that would silently gobble up the exception, and that's where you're at risk of getting weird, hard to debug behaviour.


Calling a function once a threshold is met

Pass small trivial types by value.
void f(unsigned ui);  // GOOD
void f(const unsigned& ui);  // WORSE

C and C++ don't do parameters of function type; they do parameters of function pointer type.
void f(void callback());     // BAD
void f(void (*callback)());  // GOOD

See Linus Torvalds' take on "parameters of array type", and then apply the same attitude to "parameters of function type." Don't write them. Write what you mean, instead.

Prefer signed int over unsigned int, unless you're doing bit-twiddling. Especially in your case, where the user might legitimately pass in a secondThreshold of zero or negative. See "The unsigned for value range antipattern" (2018-03-13).

Default function arguments are the devil. Prefer overloading:
void setTriggerOnEnvelope(int threshold, void (*cb)(), int cooldown);

void setTriggerOnEnvelope(int threshold, void (*cb)()) {
    return setTriggerOnEnvelope(threshold, cb, threshold - threshold/10);
}

Notice how I just shortened your original code by about 7 lines, because now you don't need all those helper variables (secondFactor, THRESHOLD_SCALE_FACTOR) and you don't need any mutation.

In fact, you should consider giving those two functions different names. Right now, it is much too easy for a careless programmer or refactorer to write
board.setTriggerOnEnvelope(700, [](){ Serial.println("Reached!"); });

when they actually meant
board.setTriggerOnEnvelope(700, [](){ Serial.println("Reached!"); }, 350);

If the two-argument version were named setTriggerOnEnvelopeWithDefaultCooldown, it'd be a lot harder for the programmer to run into a bug by forgetting the right number of arguments. See "Inheritance is for sharing an interface (and so is overloading)" (2020-10-09).

// TODO: Call callback when passed threshold is met by envelope value.

This TODO comment seems "done", doesn't it? Anyway, you should certainly not have any TODO comments left in code that you're posting to the CodeReview Stack Exchange, because we explicitly don't review non-working code.


This is an extremely overcomplicated solution to a relatively straightforward problem.

The waitForExpectationsWithTimeout method should effectively only be used assure that a particular asynchronous expectation was fulfilled.

So, in the case where we are testing whether or not the user was successfully logged in, it'd be tempting to write something along the lines of:

func testLogin() {
    let loginExpectation = expectationWithDescription("User successfully logged in")

    LoginManager.doLogin { success in
        if success {
            loginExpectation.fulfill()
        }
    }

    waitForExpectationsWithTimeout(10, handler: nil)
}

But problematically, this test can fail for two reasons:

The user wasn't successfully logged in.
The expectation wasn't fulfilled in the time limit.

If the test fails, we can't be sure whether it would have passed given a longer time limit or if it returned very quickly but wasn't successful.

So, we need to modify our test to look more like this:

func testLogin() {
    let networkExpectation = expectationWithDescription("Network request completed")

    LoginManager.doLogin { success in
        XCTAssertTrue(success)
        networkExpectation.fulfill()
    }

    waitForExpectationsWithTimeout(10, handler: nil)
}

Now, the test determines whether or not the asynchronous code executed, and if so, we verified whether or not the login was a success (or whatever the success variable represents here).

Now, you're looking for the opposite case.  You want to know not whether or not the user logged in, but whether or not the user was prevented from logging in.  And that's as simple as inverting an XCTAssertTrue to an XCTAssertFalse.

func testLogin() {
    let networkExpectation = expectationWithDescription("Network request completed")

    LoginManager.doLogin { success in
        XCTAssertFalse(success)
        networkExpectation.fulfill()
    }

    waitForExpectationsWithTimeout(10, handler: nil)
}

Importantly, this pattern doesn't require any complicated code (that we would have to of course write tests around ourselves).  Our tests are using stuff purely out of the Xcode test suite box--exactly what any one looking at our code base would expect to see.  It's very straight forward what is going on here.

And we are able to distinguish between whether the asynchronous call back ever happened or if it did happen but we got a bad result.  There's a huge difference here between a test failing because the asynchronous code didn't run before our time out and it did run but it gave an incorrect result.  We need to clearly distinguish between these results, and doing so doesn't require writing any complicated code whatsoever.

An important note here, make sure that fulfilling the expectation is the very last thing you do in the asynchronous callbacks, or you may set up a race condition.

And finally, your tests should certainly be far more robust than this.  Ultimately, we should be testing with mocked network responses and we should know, for each test, exactly what network response we will get.  We should test that whatever code is doing the login returns back the correct information to us.  There's a difference between the server allowing the user to log in successfully and denying the user with invalid credentials.  There's also a difference between invalid credentials and getting any number of various server errors (most commonly, errors in the 5xx range).  Getting a 503 and getting an invalid credential response are far from the same thing, and your tests should validate you're getting what you expect to get.

So, I've basically just told you to completely scrap all the code you've written.  And I'll stand by that.  There's no reason for the code you've written to exist.  But, we can still talk about some of the issues your existing code does have.

This function name has a weird name: waitFalseExpectationsUntilTimeout.  It's hard for me to tell by name alone what to expect this method to do.  It looks similar to the existing waitForExpectationsWithTimeout(timeout: NSTimeInterval, handler: XCWaitCompletionHandler?) method, but it has this weird array of expectations I'm supposed to pass in.  The name needs to be better.  Something like assertUnfulfilledExpectationsWithTimeout.

Even with the better name, we're in extraordinary trouble here.  As far as I can see, there's no public means of checking whether or not an expectation has been previously fulfilled.  Your code doesn't really do anything beyond fulfilling all of the expectations in the last moment before the test completes.  It doesn't assure that they weren't fulfilled earlier.

let smaller = timeout < 0 ? 0 : timeout.advancedBy(-0.5)

This variable deserves a better name, and this logic either deserves a comment or it should be eliminated altogether.  I'd opt for eliminating it altogether and throwing an exception if the user has passed a value less than 0.5.  And finally, this logic is ultimately problematic, because you can end up with negative time (if timeout is less than 0.5).

You should probably opt for some logic that looks more like this:

if timeout < 0.5 {
    // fulfill expectation immediately
}
else {
    // set up timer with timeout - 0.5 to fulfill expectations
}

Finally, there are several issues with the nested class:

class CompleteSelector {
    @objc func fullFillExpectations(timer: NSTimer) {
        let expectations = timer.userInfo as! [XCTestExpectation]
        for expc in expectations {
            expc.fulfill()
        }
    }
}

First, we don't need to mark this as an @objc function.  We can instead mark it as dynamic.

Second, we're force-casting, but we're not Jedi.  This would not pass my personal set of swiftlint rules where force-casting is considered an error and refuses to compile.

Third, expc is a meaningless variable name, and there's no real value in abbreviating here.

Fourth, you've misspelled fulfill even though it's spelled correctly several other times in this context by virtue of autocompleting method names.

Fifth, why don't we just add a method to the extension to handle this instead of over complicating with a nested class with a weird name?

enum ExpectationArgumentError: ErrorType {
    case InvalidTimeInterval, NoExpectations
}

extension XCTestCase {
    func assertUnfulfilledExpectations(timeout: NSTimeInterval, expectations: [XCTestExpectation], handler: XCWaitCompletionHandler?) throws {
        if expectations.empty {
            throw ExpectationArgumentError.NoExpectations
        }

        let fulfillTime = timeout - 0.5
        if fulfillTime < 0 {
            throw ExpectationArgumentError.InvalidTimeInterval
        }

        NSTimer.scheduledTimerWithTimeInterval(fulfillTime, target: self, selector: "fulfillExpectations:", userInfo: expectations, repeats: false)

        waitForExpectationsWithTimeout(timeout, handler: handler)
    }

    private dynamic func fulfillExpectations(timer: NSTimer) {
        if let expectations = timer.userInfo as? [XCTestExpectation] {
            for expectation in expectations {
                expectation.fulfill
            }
        }
    }
}

So, that's a significantly cleaned up and safer version of your code... but again, it doesn't actually assert that these expectations were not fulfilled before you fulfilled them (as far as I know that's impossible).  And ultimately, it's a quite a lot of code to implement, test, maintain, and verify that it works... and that is especially so when we compare that to the simply expectation+assertion combo I outlined at the top of this answer.

I wanted to add an addendum in case the issue was that there is a particular block of code that is only executed in the case of a successful login.  If this is the scenario, there are only two possibilities.

The first is that there are separate success and failure blocks.  Something along these lines:

LoginManager.doLogin("username", password: "password",
    success: {
        // login was successful
    },
    failure: {
        // login failed
    }
)

In this case, the gist is roughly the same as what I've outlined at the top.  We do want to fulfill the expectation in both blocks, but in the success block, we'll just add an XCTFail("User was allowed to log in") so that we still wait around for this block (or the failure block) to execute, but if it takes this path, we fail for the specific reason that the wrong branch was entered (as opposed to simply taking the right path but not taking it quickly enough).

The other case is that there is only a callback for the success path:

LoginManager.doLogin {
    // if logged in, this is called... otherwise, nothing
}

If THIS is the design, I don't have a clue how your app manages to give any feedback to the user at all that something went wrong during the login process... I know you can't modify the code, but you need to be telling the people who can that they need to fix this problem.


Singletons with eager and lazy instantiation

The singleton pattern guarantees that only one instance of a class will be created into the application context.

So, in your code I see that:

You are create a static final class.
You declare the selfclass propertie as final: private static final LoggerEagerSingleton logger

Both of these last points are not necessary because the singleton pattern guarantees that just one will be create and nobody could be modify the unique instance of the singleton class.

The singleton patterns suggest the following rules:

A private construct.
A Static private property of the self class.
A Static method to get the unique instance, where it create the instance if it has not been created.

    public class SimpleSingleton {

        private SimpleSingleton logger;

        private SimpleSingleton() {

        }

        public static SimpleSingleton getInstance() {

            if(logger == null)
                logger = new LoggerEagerSingleton();

            return logger;
        }
    }

As you can see the property logger is create in the static method getInstance() and no other methods give access or alter this property, and the method give you a way to get the unique instance of the class.

So if you apply these rules, your classes could be rewritten like:

public class LoggerEagerSingleton {

    private static LoggerEagerSingleton logger = null;

    private LoggerEagerSingleton() {
    }

    public static LoggerEagerSingleton getInstance() {
        if(logger == null)
            logger = new LoggerEagerSingleton();
        return logger;
    }

    //TODO: All the remain methods
    public void method A()
    {

    }

}

And it could be used as:

LoggerEagerSingleton ref = LoggerEagerSingleton.getInstance();
ref.void methodA();

But remember, a patter is a generic design that has been used to solve some issues that are common in several projects. So you can implement the pattern as it is presented or make some modifications without altering the essence of the pattern.


How would you handle 300 parallel lines?

    Line ParallelLine1 = CameraObject.GetComponent<DrawLines>()
                                     .CreateParallelLine(referenceLine, 50);
    Line ParallelLine2 = CameraObject.GetComponent<DrawLines>()
                                     .CreateParallelLine(referenceLine, -50);
    Line ParallelLine3 = CameraObject.GetComponent<DrawLines>()
                                     .CreateParallelLine(referenceLine, 100);
    Line ParallelLine4 = CameraObject.GetComponent<DrawLines>()
                                     .CreateParallelLine(referenceLine, -100);
    ...
    Line ParallelLine297 = CameraObject.GetComponent<DrawLines>()
                                     .CreateParallelLine(referenceLine, 950);
    Line ParallelLine298 = CameraObject.GetComponent<DrawLines>()
                                     .CreateParallelLine(referenceLine, -950);
    Line ParallelLine299 = CameraObject.GetComponent<DrawLines>()
                                     .CreateParallelLine(referenceLine, 1000);
    Line ParallelLine300 = CameraObject.GetComponent<DrawLines>()
                                     .CreateParallelLine(referenceLine, -1000);

Something's not right isn't it?

I think you need to put words on the concepts involved here:

You have a bunch of lines.
Lines are drawn in pairs.
Lines are offset from the referenceLine by a fixed interval - one line with a positive offset, the other with a negative offset.

You need to write a method that can create n lines and return an IEnumerable<Line> given:

A referenceLine.
An offsetIncrement for the offset.
The n number of pairs of lines you want to create.
A LineParams instance.

And then you can just iterate the result and write the AddNewLine() call only once.


I also followed [Torvalds'] coding style

I'm all for coding style standards, though I decline to listen to all of his suggestions simply because he's the loudest (seriously, very very loud) voice in the room. His blind obedience to 1988's K&R with no other rationale I find short-sighted as well. Anyway, enough editorializing:
Your non-parenthesized sizeof *new falls on a matter in his guide that is a little ambiguous -

The notable exceptions are sizeof, typeof, alignof, and __attribute__, which look somewhat like functions (and are usually used with parentheses in Linux, although they are not required in the language)

Whereas parens are not required after sizeof, I see them in the majority of code I encounter so I'd recommend sticking with them.
I warn against writing keywords from C++ as symbol names in C, in this case new. If ever you want this to be readily C++-compatible, this will cause you grief.


Run a timer while waiting for user input

Several things:

When doing multi-processing and sharing a resource (in this case, the console window), you should use locks to prevent two threads using the same resource at once. This is the source of your problems. When updating the counter you probably need to hold the lock while moving the cursor to the timer, change the timer string, and hold it until you set the cursor back to the bottom of the console. On the other thread you'd have to maintain the lock while reading user input.
You don't need to roll-your-own timers. You can use .NET's Timer class. Notice that Thread.Sleep() is not accurate and you're not really counting seconds (even if you roll-your-own than you should probably do it with time deltas and not with thread sleeps).
Don't use the Thread class, use the Task Parallel Library class. It'll be much easier. You will need to use Task.Delay instead of Thread.Sleep
Notice that you're line-breaking outside of the loop and not inside. Also WriteLine will add a line-break at the end automatically

If you're merely learning the language (I noticed the "beginner" tag) than I suggest you learn the points I've mentioned. They're more important than learning a specific (and somewhat advanced) use case of C# console applications where you change text while accepting user input. I believe it would be easier for you if it would be a simple WPF application instead of a console application.


Creating a Generic Template Interface/Class and injecting into another object

The template related class and interface are looking good to me. But the generator related class and interface are flawed.

Assume one would call the Generate() method with an ITemplate<string> which would be totally legal. Sure it would work, but xmlDocumentBody would be null.

You could if the passed in template isn't a ITemplate<XmlDocument> throw some exception, but a user of this class wouldn't expect for a generic class which is called correctly to get an exception.

So you should better make the IDocumentGenerator generic and not the Generate() method.

public interface IDocumentGenerator<T>
{
    void Generate(ITemplate<T> template, string outputDocumentFilepath);
}

and now your WordDocumentGenerator class should implement IDocumentGenerator<XmlDocument> like

public class WordDocumentGenerator : IDocumentGenerator<XmlDocument>
{
    public void Generate<T>(ITemplate<XmlDocument> template, string outputDocumentFilepath)
    {
        XmlDocument xmlDocumentBody = template.GetContent();

        // generate doc
    }
}

For sure if you have different types of templates you should add a DocumentGeneratorFactory which returns the desired DocumentGenerator for the task at hand.


Splitting an array of numbers into all possible combinations

import itertools
import numpy

number = [53, 64, 68, 71, 77, 82, 85]

results = itertools.combinations(number,4)
# convert the combination iterator into a numpy array
col_one = numpy.array(list(results))

# calculate average of col_one
col_one_average = numpy.mean(col_one, axis = 1).astype(int)

# I don't actually create col_two, as I never figured out a good way to do it
# But since I only need the sum, I figure that out by subtraction
col_two_average = (numpy.sum(number) - numpy.sum(col_one, axis = 1)) / 3

dif = col_one_average - col_two_average

print dif


Non-testable class wrapping Java Properties with basic logic

Your class is non-testable mainly because :

it reads datas from disk/network
it doesn't use any injection

Firstly, please note that Spring has some utility to read property file and fills java beans automaticly. You should check this if you don't want to reinvent the wheel. ;)
Also, Properties is a fairly old school class in Java and isn't used that much recently.

If you do want to have your own implementation, the let's see what we can do line-by-line, shall we ?

private final String secretToken = "SECRET";

Either you plan on making this variable (and then it should be injected in the constructor) or this is a constant (so it should be private static final).

public final class Keys
{
    public final static String KEY1 = "KEY1";
    public final static String KEY2 = "KEY2";
}

I don't really get what you were trying to accomplish here. Why didn't you put those constants in the main classes ? I'd remove this code altogether IMHO.

private Properties properties;

This is set in the constructor so this is a good candidate for final ;)

public PropertiesManager() throws IOException
{
    properties = new Properties();
    InputStream in = new FileInputStream(CONF_FILE_NAME);
    properties.load(in);
}

Maybe some people will disagree but I'm no big fan of constructor that do I/O.
Also this is non-configurable : what if you want to change the file name ? what if you want to read not from a file but from a string or from the console ?
You should read about dependency injection if you've never heard of it before.
For a quick introduction, it's a principle that some codes delegates the configuration of the object to the calling code allowing for more and easier code reuse.

The InputStream is not closed which may lead to ressource-leak. See https://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html#close() ;)

IMO I'd have a constructor that takes a Properties object. However, this may pose others problems (such as the Properties object still being accessed by another object and be modified directly).
So, I'd consider using a static factory method that takes a Reader and returns the PropertiesManager. The calling code will be the one responsible to close the stream.
This allows you to inject any time of Reader making your code more reusable.

public String getProperty(String name)
{
    //...

This is fine. As a side-note : you shouldn't use System.out.println for log in production code.

public HashMap<String, String> getAllPublicProperties()

Your return type shouldn't be HashMap ; when possible you should code against the interface that most suits your need, in this case : Map.

HashMap<String, String> map = new HashMap<>();

properties.keySet().stream().map(f -> (String)f).filter(f -> !f.contains(secretToken)).forEach(f -> map.put(f, properties.getProperty(f)));

This code may be dangerous as it is not thread-safe due to the forEach that modify a non thread-safe object. From a FP pov, you should try to delegate to the collect method (check https://docs.oracle.com/javase/9/docs/api/java/util/stream/Collectors.html).

This leads us to the following code :

package pl.propertiesdemo;

import static java.util.stream.Collectors.toMap;

import java.io.IOException;
import java.io.Reader;
import java.util.Map;
import java.util.Properties;
import java.util.function.Function;

public class PropertiesManager {
    public static final String DEFAULT_CONF_FILE_NAME = "conf_file.conf";

    private static final String SECRET_TOKEN = "SECRET";

    private final Properties properties;

    public static PropertiesManager createFrom(final Reader r) throws IOException {
        var properties = new Properties();
        properties.load(r);
        return new PropertiesManager(properties);
    }

    protected PropertiesManager(final Properties properties) {
        this.properties = properties;
    }

    public String getProperty(final String name) {
        String property = properties.getProperty(name);
        if (property == null) {
            System.out.println("Property " + name + " not found in properties file");
        }
        return property;
    }

    public Map<String, String> getAllPublicProperties() {
        return properties.keySet()
                .stream()
                .map(f -> (String) f)
                .filter(f -> !f.contains(SECRET_TOKEN))
                .collect(toMap(Function.identity(), f -> properties.getProperty(f)));
    }
}

Now that your object don't read from disk and can be easily injected, the object instantiation in the test class may look like this :

PropertiesManager prop = null;
try {
    prop = PropertiesManager.createFrom(new StringReader("someKey=someValue"));
} catch (IOException ioe) {
    fail();
}


Your solution is far too complicated.  It's also inefficient, because it uses functions .lastIndexOf() and .includes(), both of which analyze the entire str looking for target, whereas an optimal solution should look only starting at a known position at the end of str.

Here are two simple solutions:

function confirmEnding(str, target) {
  return str.startsWith(target, str.length - target.length);
}

function confirmEnding(str, target) {
  return target == str.substring(str.length - target.length);
}

console.log(
  false == confirmEnding("s", "try long target strings") &&
  false == confirmEnding("", "try an empty str") &&
  true  == confirmEnding("Bastian", "n") &&
  true  == confirmEnding("Congratulation", "on") &&
  false == confirmEnding("Connor", "n") &&
  false == confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") &&
  true  == confirmEnding("He has to give me a new name", "name") &&
  true  == confirmEnding("Open sesame", "same") &&
  false == confirmEnding("Open sesame", "pen") &&
  false == confirmEnding("Open sesame", "game") &&
  false == confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain") &&
  true  == confirmEnding("Abstraction", "action")
)

The first solution, using .startsWith(), should be efficient, but it might be considered "cheating" to use .startsWith() even though only .endsWith() is prohibited.

The second solution is slightly simpler, but it involves creating a substring, so it would be less efficient.


Keeping just the rare characters in a long string

x is not a good variable name.  I suggest page_source.

Your approach is inefficient because you re-count all of the occurrences of each character, which is O(n2), where n is the length of the string.

It would be better to use a Counter.  It's more efficient because counts all characters using just one pass through the string.  (We call that O(n).)

from collections import Counter

count = Counter(text)
s = ''.join(char for char in text if count[char] < 10)
print(s)

If you wanted to make your own counter with similar performance characteristics, you could do something similar to this:

count = {}
for char in text:
    count[char] = 1 + count.get(char, 0)


Find every possible pair of numbers that sum up to n number

Removing numbers greater than the target affects the correctness of this program - they could be added to negative numbers to reach the target.

You could get a performance improvement by finding the difference between each element and the target, then looking to see if that difference is in the list.  This doesn't in itself reduce the computational complexity (it's still O(n²)), but we can build on that: if the list is first sorted, and we then use a binary search to test membership we get to O(n log n); if we convert to a structure with fast lookup (such as a collections.Counter, which has amortized O(1) insertion and lookup), then we come down to O(n).

If we have a Counter, then we can account for all combinations of that pair by multiplying one count by the other (but we'll need to consider the special case that the number is exactly half the target).

We could do with some auto tests.  Consider importing the doctest module and using it.  Some good test cases to include:

1, [] → 0
1, [1] → 0
1, [0, 1] → 1
0, [-1, 1] → 1
0, [0, 1] → 0
4, [1, 4, 3, 0] → 2
4, [1, 1, 3, 3] → 4
4, [2, 2, 2, 2] → 6


Disclaimer: this should be a comment, my reputation at the moment does not allow me to comment your question

What about exploiting const_missing?
https://apidock.com/ruby/Module/const_missing

I used it in an app to declare ActiveRecord models at runtime. If you are interested in this approach I suggest you to namespace all Dynamic controllers i.e.

module Dyn
  def self.const_missing(sym)
    # Declare class Dyn::MyDynamicController
    # without overriding or patching Rails classes
  end
end


Efficiency and correctness of my randomized selection algorithm

You should learn about how to benchmark your code, from my benchmark, shuffling makes the algorithm slower:

from random import shuffle,randint
import time

def _partition(arr, lo, hi, pivot):
    p = arr[pivot]
    arr[hi - 1], arr[pivot] = arr[pivot], arr[hi - 1]
    i = lo - 1
    for j in xrange(lo, hi):
        if arr[j] <= p:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
    return i

def select(arr, lo, hi, spos,shuffling=None):
    assert lo <= spos < hi
    if shuffling: shuffle(arr)  # here's your randomization.
    while True:
        pos = _partition(arr, lo, hi, lo)
        if pos == spos:
            return arr[pos]
        elif pos < spos:
            lo = pos + 1
        else:
            hi = pos

def random_list(length):
    return [randint(1,100) for _ in range(length)]

start = time.time()
results = []
for _ in range(10000):
    results.append(select(random_list(10),1,5,1,shuffling=True))
print("With shuffling: ",time.time()-start)

start = time.time()
results = []
for _ in range(10000):
    results.append(select(random_list(10),1,5,1,shuffling=False))
print("WithOUT shuffling: ",time.time()-start)