There is lots that can be improved here. I won't repeat the great points that others have already made. Some thoughts:

Why are all these methods public?  Do you intend that CheckListLength is going to be called by code external to this class?  Only make things public that are part of the public surface of the class.
Why are any of these methods instance methods?  There is no instance data. They could all be static.
The contract of the primary method is bizarre. Summing up: you require that the user pass in two lists. If the first is empty, it becomes a copy of the second. The second list is then never touched again. Random items are chosen from the first list, and removed.  Think about how many ways there are for that to go horribly wrong. What if the user passes in two completely different lists? What if they pass in two references to the same list?  This is a disaster waiting to happen.
Consider the cost.  Suppose the method is used as it is supposed to be: we pass in an empty list and a list with N items. We wish to get out the N items in a random order. Now, I will tell you this crucial fact: the cost of removing an item from a list at random is on average proportional to the number of items in the list.  That's because lists are packed. If you have a million items in a list and you remove item number 123, then item 124 has to be moved into slot 123, item 125 has to be moved into slot 124, and so on up to item 1000000 being moved into slot 999999.  You are performing that operation N times, and the cost each time is proportional to N. If you work out the math you'll find that on average, if you use this method to fully randomize a list, then you are performing about N2/2 operations.  That's nothing if N is 4, but it is a trillion if N is a million; you will wait a long time to get your list randomized.
Your goal of producing a random sequence without modifying the original list is a really good one.  There are two far easier ways to do that, and I encourage you to try both of them.  They are:

First: make a method with this signature:

public static List<T> ProduceShuffle<T>(this IList<T> original)

You can have the method take a Random if you like as well.

the action of the method is:

Make a copy of the original list.
Loop from the end of the list to the beginning of the list
Each time through the loop, choose a random number less than or equal to the current index. This is key; you must not choose a random number covering the entire size of the list, otherwise the shuffle is biased.
Swap the element at the current index with the element at the randomly chosen index.

This is the Knuth Shuffle, also called the Fischer-Yates shuffle, and it is very efficient. Can you implement the code from my description? Can you produce an argument that this shuffle is both efficient and unbiased?

The second way to do it is much shorter but slightly less efficient.

public static List<T> ProduceShuffle<T>(this IEnumerable<T> original, Random random)
{
    return original.OrderBy(x => random.NextDouble()).ToList();
}

That is: generate a random fraction associated with each element. Produce a sorted sequence -- without modifying the original sequence -- that is sorted by that random element. Then turn that thing into a list and return it.

I note that some people on StackOverflow will tell you to sort by a new guid rather than by a random number because guids are random. This is a bad idea. Guids are unique; that guids happen to gain their uniqueness through randomness is an implementation detail subject to change. Use guids as a source of uniqueness, not as a source of randomness.


Test class

In the scope of code you provided, the div is useless and may be omitted:

render() {
  return this.state.comments.map((comment, index) => (
    <Comment key={index} comment={comment}/>
  ))
}

However, as React warns you in the console, don't forget to pass a key prop to your array items (added in the snippet above).

Comment class

The method name renderSidebar suggest to me that it will return something that React can render, but it returns an object of CSS styles instead. For that reason, I'd rename it to getSidebarStyle.
Since the method renderSidebar doesn't depend on anything except its parameters and doesn't alter any instance variables (it's a pure function), you can move it outside the class.
The array of colors has nothing to do with the logic of selecting a color depending on the intendation level. Depending on your coding style preferences, you could move it to outside the method and capitalize it.
When rendering the subcomments, set a key prop on your array items as above.
JSX is camel-cased and that's why React warns you in the console to change your CSS property names (e.g. border-left to borderLeft), also allowing you to omit the quotes.

Generally, your code is in good shape & all of the comments above are more or less only improvements. To help you move faster, I suggest always checking the console for helpful warnings and using tools such as Prettier and a linter for your JS dialect to help you while programming.


It looks good!  I only have some minor suggestions.  You might want to not have the LINQ expression all on one line.  Right now I have to scroll to see it all.

An alternative is to use Enumerable.Range() to create a range of indexes:

public static int GetGTINCheckDigitUsingRange(string code)
{
    var reversed = code.Reverse().ToArray();
    var sum = Enumerable
        .Range(0, reversed.Count())
        .Sum(i => (int)char.GetNumericValue(reversed[i]) * (i % 2 == 0 ? 3 : 1));
    return (10 - sum % 10) % 10;
}

Another alternative is to use query syntax:

public static int GetGTINCheckDigitUsingQuery(string code)
{
    var reversed = code.Reverse().ToArray();
    var sum =
       (from i in Enumerable.Range(0, reversed.Count())
        let digit = (int)char.GetNumericValue(reversed[i])
        select digit * (i % 2 == 0 ? 3 : 1)).Sum();
    return (10 - sum % 10) % 10;
}

I think your version three is still better than my alternatives, but you might prefer one of them.  Enumerable.Range() is nice for replacing for loops, and query syntax is nice for declaring intermediate values (like digit) and replacing nested loops.  But the Select() method that takes a lambda that includes the index as a parameter is very nice for this situation.  With enough practice you can get to the point where your code looks like version three right away.  I rarely write loops anymore.  I actually find them tougher to write because they make you focus more on "how" than "what".


Split a string based on a delimiter in C

Check allocated pointers before using them
It's good that we have a if (!temp) check, but unfortunately we used temp as argument to memset() before we did the check, so it's too late!
We could (and should) use calloc() if we need to zero out the memory we allocated.  In this case, it's not necessary (we'll be overwriting it anyway), so we should just omit the memset() call.
Use const where appropriate
The pointers str, p and q can all point to const char; that allows us to safely pass a string literal as argument, for example, and it helps users understand what guarantees they are given.
Document the arguments
The meaning of the argument len isn't obvious from its name or from the function's comment.  It seems that it's the largest substring we expect to handle.
Even better would be to make the code adapt (using realloc(), perhaps) to the string it's given, rather than requiring the user to specify that.  I'll leave that as an interesting exercise for you.
Try not to mix indexing and pointer arithmetic
It's a little confusing to index into str using i, but to also have pointers p and q pointing into the string, too.
The break at the end of the loop
Since p initially points to the beginning of the string, we can move the test at the end of the loop to be part of the loop condition.  This makes the loop structure easier to follow:
for (size_t i = 0;  i <= len && *p;  ++i)

(I changed the test of i slightly, for simplicity and also as an almost-automatic aversion to integer overflow).
We don't need a loop to find the next instance of token
We could use strchr() to find the next token in str.  On GNU platforms, there's also strchrnul() which returns a pointer to the terminating NUL (instead of a null pointer) when the character isn't present.
Consider discarding empty words
Many users will expect the same result from "foo bar" and "foo  bar" - it's a surprise to find that this code considers there to be a zero-length word between the two spaces in the latter string.  Even more surprising is " foo" which splits to "" and " foo".

Reworked code
I started again from scratch, taking into account these observations.  The interface is a bit different, as in real life we want to be able to re-use the function to perform different actions on the tokens found, so we accept a function and a state pointer for the function.
This is standard portable C - you're of course able to add your annotation header to this if you want.
#include <stdlib.h>
#include <string.h>

/**
 * @brief Call a function for each token found in the input string.
 * @param s input string
 * @param sep nul-terminated set of delimiter characters, or NULL for default
 * @param f callback function
 * @param data callback data
 * @return true if successful, false on any failure
 */
int process_tokens(const char *s, const char *sep,
                   void (*f)(const char*,void*), void *data)
{
    if (!sep) {
        /* use default word separators */
        sep = " \t\n.!?()";
    }

    char *buf = NULL;
    size_t buf_len = 0;

    while (*(s+= strspn(s, sep))) {
        /* s is now pointing at next word character */
        size_t word_len = strcspn(s, sep);

        /* ensure we have sufficient storage */
        if (buf_len <= word_len) {
            buf_len = 2 * word_len + 1;
            char *t = realloc(buf, buf_len);
            if (!t) {
                free(buf);
                return 0;
            }
            buf = t;
        }

        /* copy word into storage, and call user function */
        memcpy(buf, s, word_len);
        buf[word_len] = 0;
        f(buf, data);

        /* advance to next separator */
        s += word_len;
    }

    free(buf);
    return 1;
}

/* A simple test program */

#include <stdio.h>

static void print_token(const char *s, void *data)
{
    size_t *count = data;
    ++*count;
    printf("Processed: \"%s\"\n", s);
}

int main()
{
    size_t count = 0;
    const char *input = "  Pack my box  with five-dozen liquor jugs.  ";
    if (!process_tokens(input, NULL, print_token, &count)) {
        fprintf(stderr, "Error splitting input string\n");
        return 1;
    }

    printf("Processed %zu tokens\n", count);
}


Python for HPC: Parse file, generate statistics, record output

I have a program which is designed to be highly parallelizable.

I can't see this, all I can see is a broken module level program.

As for improvements in your code.
There are quite a few ways you can improve your for-loop to make vals:

Put it in a function,
Use a defaultdict, this should result in something like:

if split_line[1] != nam:
    continue
vals[split_line[1]].append(float(split_line[0]))

This should make you realise that you'll only ever add to vals[nam].
And so change it to just a list.
slice dchunk.values.

for line in dchunk.values[:49] + dchunk.values[numlines - 50:]:
    split_line = ''.join(str(s) for s in line).split()

Alternately if this doesn't work use a comprehension with enumerate.

for line in (l for i, l in enumerate(dchunk.values) if i < 49 or i > numlines - 50):
    split_line = ''.join(str(s) for s in line).split()

Merge all the if statements into one.

if (len(split_line) != 2 or
    split_line[0] in ('nan', '-nan') or
    split_line[1] != nam):
    continue

You should change some of your variables to 'constants' using the UPPER_SNAKE_CASE convention.

And you can change count_vals into a single line with len and itertools.takewhile.

count_vals = float(len(takewhile(lambda i: i > coe_threshold, coe_vals)))

You can change the way you get numlines to len(list(f)).


Tic-Tac-Toe code using Python with Tkinter

Let us begin with some layout. This is a typical grid use case so that you won't have to manually manage grid. At the lowest level, a grid structure essentially places buttons by calculating coordinates. But this gets tedious over time, that's why a grid layout is provided. Also, it was a clever way of cheking win by being symbol agnostic. A normal tic tac toe game would have used checkwin(symbol) to determine win.

On strings

To escape ' within ' ' you can use " instead. From

'\'S TURN.'

to

"'S TURN."

and you can also use string formatting to clear up some clutter.

"PLAYER {}'S TURN.".format(turn)

On layout

Modifying your create_button function to this allows a grid structure

def create_button(x, y):
    button = tk.Button(width=10, height=2, command=lambda: callback(button))
    button.grid(row=x, column=y)
    return button

Then we modify others since different layouts can't be mixed

label_button = ttk.Button(
                        game,
                        text="PLAYER {}'S TURN.".format(turn),
                        style='Fun.TButton', width=20,
                        state='disabled')
label_button.grid(row=0, column=1)
invalid = tk.Label(text='')
invalid.grid(row=4, column=1)

adding the buttons can be then done as

buttons = []

buttons.append(create_button(1, 0))
buttons.append(create_button(1, 1))
buttons.append(create_button(1, 2))
buttons.append(create_button(2, 0))
buttons.append(create_button(2, 1))
buttons.append(create_button(2, 2))
buttons.append(create_button(3, 0))
buttons.append(create_button(3, 1))
buttons.append(create_button(3, 2))

You can use a loop for the row and itertools.cycle for the 0, 1, 2 if you want to simplify it.

The check_win function

Simplifying if

Adding a () to if statements allows you to write or without \

if ... :
    ...

to

if (...):
    ...

thus the win_function can be simplified from

if (buttons[0]['text'] == buttons[1]['text'] == buttons[2]['text'] != '') or \
(buttons[3]['text'] == buttons[4]['text'] == buttons[5]['text'] != '') or \

to

def check_win():
    if (
        (buttons[0]['text'] == buttons[1]['text'] == buttons[2]['text'] != '') or
        (buttons[3]['text'] == buttons[4]['text'] == buttons[5]['text'] != '') or
        ...
        ):
        return True
    else:
        return False

Simplifying values write-up

This can also be further simplified by defining a function to replace buttons[0]['text']

def btext(i):
    return buttons[i]['text']

and using it

def check_win():
    if (
        (btext(0) == btext(1) == btext(2) != '') or
        (btext(3) == btext(4) == btext(5) != '') or
        (btext(6) == btext(7) == btext(8) != '') or
        (btext(0) == btext(3) == btext(6) != '') or
        (btext(1) == btext(4) == btext(7) != '') or
        (btext(2) == btext(5) == btext(8) != '') or
        (btext(2) == btext(4) == btext(6) != '') or
        (btext(0) == btext(6) == btext(8) != '')
        ):
        return True
    else:
        return False

On architecture

A common pattern is the MVC (Model, View, Controller). While checking and updating gui directly works here, you might consider adding states in a structure like this:

board = [
    ['', '', ''],
    ['', '', ''],
    ['', '', '']
]

Operations are done on this and the gui is updated according to this.


So you need to separate the construction of that class from the class itself? This is the Factory Pattern.

Data class

Boil down to your DTO to ... well the data.

public class MassiveDTO {
    private final List<String> company;
    private final List<String> partners;
    private final List<String> biodata;

  /**
   * @see MassiveDTOBuilder
   */
  MassiveDTO(List<String> company, List<String> partners, List<String> biodata) {
    this.company = company;
    this.partners = partners;
    this.biodata = biodata;
  }
   ... getters only
}

Factory Pattern

Then have a second class, MassiveDTOFactory, that calls that constructor with suitable fixed values.

public class MassiveDTOFactory {
  public static MassiveDTO create() {
    return new MassiveDTO(
      List.of("X0788", "X0192"), // Here we use Java 9 immutable collections
      List.of("X0081"),
      List.of("X0913")
    );
  }
}

Fluent Builder Pattern

If you wish more flexibility on the values then a Fluent Builder is for you. Something like this:

public class MassiveDTOBuilder {
  private List<String> companies = new ArrayList<>();
  private List<String> partners = new ArrayList<>();
  private List<String> biodata = new ArrayList<>();

  public static MassiveDTOBuilder massiveDto() {
    return new MassiveDTOBuilder();
  }

  private MassiveDTOBuilder() {
  }

  public MassiveDTOBuilder withCompany(String... items) {
    for (String i : items) {
      companies.add(i);
    }
    return this;
  }

  public MassiveDTOBuilder withPartner(String... items) {
    for (String i : items) {
      partners.add(i);
    }
    return this;
  }

  public MassiveDTOBuilder withBiodata(String... items) {
    for (String i : items) {
      biodata.add(i);
    }
    return this;
  }

  public MassiveDTO build() {
    return new MassiveDTO(
      Collections.unmodifiableList(companies),
      Collections.unmodifiableList(partners),
      Collections.unmodifiableList(biodata)
    );
  }
}

Which can used like:

MassiveDTO m = massiveDto()
  .withCompany("X0788", "X0192")
  .withPartner("X0081")
  .withBiodata("X0913")
  .build();


Minimum number of steps to move from one city to another

Okay, found problem online and solved it. The trick to the problem (as with most problems) lies in the constraints:

There are a lot of queries, but a small amount of cities. It would seem more important to optimize answering a query time, which is usually done with some precalculation or caching.

In this case, we can think that as there are at most 3000 cities, there is at most 3000 distinct city types. So all queries that don´t ask for an invalid city type (no city has that city type) will have one of those 3000 types.

We can precalculate for all cities, the query of going to right or left for each of these types, ending with a O(cities * distinct types * 2) complexity, which would be 3000 * 3000 * 2 at most, much better than the original 500000 * 3000.

Then for each query, if the type of city is a valid type (at least one of the cities has it), we have already preprocessed the answer and can answer in O(1). If it isn´t, we just answer with -1.

Another hint is the topic of the problem, which is for practicing multi dimentional arrays. We use this to store the calculation of all valid queries to then answer in O(1).

I advice you to try coding the problem again with these hints.

If you get stuck:

   Even though city types can go up to 200000, we can map them to values between 1 and 3000, because we only have 3000 cities.

And if you still can´t solve it, here is my solution:

        Scanner kb=new Scanner(System.in);
        int cities = kb.nextInt();
        int queries = kb.nextInt();

        int types[] = new int[cities];
        HashSet uniqueTypes = new HashSet();

        for (int i = 0; i < cities; i++) {
            types[i] = kb.nextInt();
            uniqueTypes.add(types[i]);
        }

        HashMap mapping = new HashMap();

        Integer idx = 0;
        for (Integer type: uniqueTypes) {
            mapping.put(type, idx++);
        }

        for (int i = 0; i < cities; i++) {
            types[i] = mapping.get(types[i]);
        }

        int closestRight[][] = new int[cities][cities];
        int closestLeft[][] = new int[cities][cities];

        for(int i = 0; i < cities; i++) {
            for (int j = 0; j < cities; j ++) {
                closestRight[i][j] = closestLeft[i][j] = cities + 1;
            }
        }

        for(int i = 0; i < cities; i++) {
            for (int j = 0; j < cities; j ++) {
                int leftIndex = ((i - j) + cities) % cities;
                int rightIndex = (i + j) % cities;
                int rightCityType = types[rightIndex];
                int leftCityType = types[leftIndex];

                closestRight[i][rightCityType] = Math.min(closestRight[i][rightCityType], j);
                closestLeft[i][leftCityType] = Math.min(closestLeft[i][leftCityType], j);

            }
        }

        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new
        FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512);

        for (int i = 0; i < queries; i++) {
            int city = kb.nextInt();

            int destinationType = kb.nextInt();

            if (mapping.get(destinationType) == null) {
                out.write("-1" + "\n");
                continue;
            }

            destinationType = mapping.get(destinationType);

            if (kb.next().charAt(0) == 'L') {
                out.write(closestLeft[city][destinationType] + "\n");
            } else {
                out.write(closestRight[city][destinationType] + "\n");
            }

        }

        out.flush();


Changing color via JRadioButtons and JButtons

For my first code review, I hope you find this useful!

Firstly, I like the fact you've used arrays for your buttons, this is good. The name of the array is also nice and descriptive.

colorbuttons = new JButton[]{new JButton(),

Looking at some of your other variable names, I'm not quite as happy.

bar = new JMenuBar();
menu1 = new JMenu("Edit circle");
sub1 = new JMenu("Colour");
colors = new JRadioButtonMenuItem[]{new JRadioButtonMenuItem("White"),
color

Firstly colors I'd expect a list/array of colours - but no, it's an array of radio button menu items. I think color is your worst offender here. By reading the variable name, we don't know what object it's the color of.

Now, you have buttons related to a subset of colours. So I would start with an enum that will keep a track of the Color and the name

private enum EColorSet {
    eWhite(Color.WHITE, "White"),
    eGreen(Color.GREEN, "Green"),
    eRed(Color.RED, "Red"),
    eYellow(Color.YELLOW, "Yellow"),
    eBlue(Color.BLUE, "Blue"),
    eBlack(Color.BLACK, "Black");

    Color c;
    String label;

    private EColorSet(Color c, String label)
    {
        this.c = c;
        this.label = label;
    }
}

Now that you have a set of colours to iterate against, you can set up your arrays as follows

colorbuttons = new JButton[EColorSet.values().length]
colors = new JRadioButtonMenuItem[EColorSet.values().length]

and initialise them whilst looping through the colours

for (EColorSet currentColor : EColorSet.values()) {
    colourbuttons[currentColor.ordinal()] = new JButton();
    colourbuttons[currentColor.ordinal()].setBackground(currentColor.c);
    //do the same for the colors menu items -note you use the label...
}

see the fact in colourbuttons[currentColor.ordinal()] .setBackground(currentColor.c); i'm using the colour stored in my enum

We need to map the button (or menu item click) to an index in the array, which also represents a EColorSet instance. Unfortunately, we still need the index of the button in the array, but

public void actionPerformed(ActionEvent e) {
    JButton temp = (JButton)e.getSource();

    int index = 0;
    for(JButton b : colourbuttons) {
        if(temp.equals(b)) {
            break;
        }
        index ++;
    }
    EColorSet currentColor = EColorSet.values()[index];
    setColor(currentColor);
    setMenuFromColor(currentColor);
}

Now to finish this off, when a button is clicked, we need to find the index, but we can do this as we know the color now.

private void setMenuFromColor(EColorSet colourClicked){
    colors[colorClicked.ordinal].setSelected(true);
    //set the menu to selected
}

private void setColor(EColorSet colourClicked){
    //set the colour of the circle
}


Splitting an NSArray into an NSDictionary of array more elegantly

As far as name of the method is concerned I have two points:

There is no need of the work Array here, as it is NSArray instance method.
The work With gives wrong impression here. (the phrase "group a with b" will generally mean to group them together).

So in my opinion groupUsingBlock or dictionaryGroupedUsingBlock, might be better.

Regarding KVC, if grouping is required to be done on a single property and that property is in complaint with the standard, you can have the function as following:

 -(NSDictionary *)groupByKey:(NSString *) key {
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

    for (id obj in self) {
        id keyValue = [obj valueForKey:key];
        NSMutableArray *arr = dictionary[keyValue];
        if (! arr) {
            arr = [NSMutableArray array];
            dictionary[keyValue] = arr;
        }
        [arr addObject:obj];
    }
    return [dictionary copy];
}

This will make the method slightly easy to use, but will also seriously limit the flexibility. So I would suggest that you keep the method which uses Block and implement the KVC version of the method by using it, like following:

 -(NSDictionary *)groupByKey:(NSString *) key {
    return [self groupUsingBlock:^(id obj) {
            return [obj valueForKey:key];
        }];
}


zip_longest without fillvalue in typescript

How about this? You iterate through each array only once.

function zipLongest(...arrays: Array<any>) {
    const result:any[] = [];
    arrays.forEach((arr) => {
      arr.forEach((val: any, i: number) => {
        if (i === result.length) result.push([]);
            result[i].push(val);
      })
    });
    return result;
}

"use strict";
const aFixture = [
    { name: 'name_a', value: 'value_a' },
    { name: 'name_b', value: 'value_b' },
    { name: 'name_c', value: 'value_c' },
    { name: 'name_d', value: 'value_d' },
];
const bFixture = [
    { name: 'name_1', value: 'value_1' },
    { name: 'name_2', value: 'value_2' },
];
const cFixture = [
    { name: 'name_x', value: 'value_x' },
    { name: 'name_y', value: 'value_y' },
    { name: 'name_z', value: 'value_z' },
];
function zipLongest(...arrays) {
    const result = [];
    arrays.forEach((arr) => {
        for (var i = 0; i < arr.length; i++) {
            if (i >= result.length) {
                result.push([arr[i]]);
            }
            else {
                result[i] = result[i].concat(arr[i]);
            }
        }
    });
    return result;
}
const myarray = zipLongest(aFixture, bFixture, cFixture);
console.log(myarray);


Strategy design pattern for writing to a file or to the console

According to the GoF, Strategy pattern:

  Define a family of algorithms, encapsulate each one, and make them
  interchangeable. Strategy lets the algorithm vary independently from
  the clients that use it.

See that the objective is disacouplished client (context object) of your possibles behaviours. So there is two basics elements in this pattern: context object and strategies.

The contexts objects have domain problems that must be separated from each other, so different algorithms. See in image(source in: https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm):

All this allow that you can work to an interface without worrying implementation strategy.

In your code there is no context object, so this is wrong. If there is no context object, the problem does not exist either.

Refactoring your code, we will have the following strategies:

// ----------------------------------------------
// in strategies.go files
// ----------------------------------------------

type PrintStrategy interface {
    Print() error
}

type ConsoleStrategy struct{}
func (c ConsoleStrategy) Print() error {
  fmt.Println("Hello, playground by console strategy")
  return nil
}

type FileStrategy struct {DestinationFilePath string}
func (c FileStrategy) Print() error {
  //print in file c.DestinationFilePath
  fmt.Println("Hello, playground by file strategy")
  return nil
}

type DefaultStrategy struct{}
func (c DefaultStrategy) Print() error {
  //print in printer device
  fmt.Println("Hello, playground by default strategy")
  return nil
}

And the following context object:

// ----------------------------------------------
// in context.go files
// ----------------------------------------------
type MyContextObject struct {
  ps PrintStrategy
}

func (m MyContextObject) Print(){
  //check if PrintingStrategy is not nil
  err := m.ps.Print()
  if err != nil {
    panic("Fail on PrintMyDatas")
  }
}

func NewMyContextObject(p PrintStrategy) MyContextObject{
  if (p != nil){
    return MyContextObject{p}
  } else {
    return MyContextObject{DefaultStrategy{}}
  }
}

See that on instancing of MyContextObject an behaviour is passed. In your case the behaviour for this context is provided by argument passing on executing. In another case you might like change the behaviour in according with the content size. These are different context using same strategy.

func main() {
    //read args
    strategy := flag.String("strategy", "console", "selected strategy")
    flag.Parse()

    //context object that needs to print your datas in according with
    //an user arg.
    var m MyContextObject

    //this statments can be replaced by factory method
    switch *strategy {
    case "console":
        m = NewMyContextObject(ConsoleStrategy{})
    case "file":
        m = NewMyContextObject(FileStrategy{"bigciao"})
    default:
        m = NewMyContextObject(nil)
    }
    //
    m.Print()
}

Now you can does more strategies or share this behaviour in other contexts.
This is a good practical of reuse!!

This code is in https://play.golang.org/p/P-kGGOwDDRt.

I hope I helped you!


Improving my code of Margrabe Formula in Python

First of all, when you compare to None, you are better off using if stock1 is None: - an object can define equality, so potentially using == could return True even when stock1 is not None. Using is checks identity, so it will only return True in the case it really is None.

As to simplifying your code, you can simply place the default values directly into the function definition:

def margrabe(stock1=s1, stock2=s2, sig1=t, sig2=sigma1, time=sigma2, corr=rho):
    dd1 = d1(stock1, stock2, time, sig1, sig2, corr)
    dd2 = d2(stock1, stock2, time, sig1, sig2, corr)
    return stock1*norm.cdf(dd1) - stock2*norm.cdf(dd2)

This makes your code significantly more readable, and much shorter.

It is also worth a note that CapWords is reserved for classes in Python - for functions, use lowercase_with_underscores - this is defined in PEP-8 (which is a great read for making your Python more readable), and helps code highlighters work better, and your code more readable.


Code review of code to strip 0 from decimal series

Well... Sorry to say this, but it's crappy!

The function name doesn't explain what the function does (and using your explanation above for Javadoc would only make things worse, judging from the confusion in the comments)
Even knowing the implementation doesn't help, it's hard to tell if the steps performed inside the function correspond to a real-world concept or represent some algorithm
it's not clear if this function makes sense for negative values, I'm pretty sure it would return unexpected values (i.e. output for x and -x would be drastically different). If the function is not defined for negative values, throw an IllegalArgumentException when num < 0
You use confusing names for variables; I think even a, b, c etc. would be better than num, newNum, numberToReturn (nb. this last one is additionally misleading as you still process it before returning)
The function seems to solve some general problem but it uses arbitrary depth: repeats the same operation twice (in lines 1&2 and 3&4) instead of using a loop or recursion (which would also communicate your intentions better)

I know this is the part where you give your recommendations but I believe this function is broken beyond repair until you make it clear what its purpose and contract are. Remember that most real-world mathematical problems are already solved and have well-described algorithms, using well-tested solutions is always a better idea than trying to reinvent the wheel.


Generating words based on a list of letters

import itertools
from multiprocessing import Process, Manager

dictionary_file = '/usr/share/dict/words'
letter_list = ['t','b','a','n','e','a','c','r','o']
control_letter = 'e'

By convention, global constant should be named in ALL_CAPS

manager = Manager()
word_list = manager.list()

def new_combination(i, dictionary):
    comb_list = itertools.permutations(letter_list,i)
    for item in comb_list:
        item = ''.join(item)
        if(item in dictionary):

You don't need the parens. Also, dictionary in your code is a list. Checking whether an item is in a list is rather slow, use a set for fast checking.

            word_list.append(item)

Having a bunch of different processes constantly adding onto a single list, performance will be decreased. You are probably better off adding onto a seperate list and then using extend to combine them at the end.

    return

There is no point in an empty return at the end of  a function

def make_dictionary():

I'd call this read_dictionary, since you aren't really making the dictionary

    my_list = []

Name variables for what they are for, not their types

    dicts = open(dictionary_file).readlines()
    for word in dicts:

Actually, you could just do for word in open(dictionary_file) for the same effect

        if control_letter in word:
            if(len(word) >3 and len(word)<10):
                word = word.strip('\n')

I recommend stripping before checking lengths, just to make it easier to follow what's going on

                my_list.append(word)
    return my_list

def main():
    dictionary = make_dictionary()
    all_processes = []
    for j in range(9,10):
        new_combo = Process(target = new_combination, args = (j,dictionary,))

You don't need that last comma

        new_combo.start()
        all_processes.append(new_combo)
    while(all_processes):

Parens unneeded

        for proc in all_processes:
            if not proc.is_alive():
                proc.join()
        all_processes = [proc for proc in all_processes if proc.is_alive()]

What happens if a process finishes between the last two lines? You'll never call proc.join() on it.

        if(len(all_processes) == 0):
            all_processes = None

an empty list is already considered false, so there is no point in this.

Actually, there is no reason for most of this loop. All you need is

for process in all_processes:
    process.join()

It'll take care of waiting for all the processes to finish. It'll also be faster since it won't busy loop.

    print list(set(word_list))

if __name__ == '__main__':
    main()

I've given a few suggestions for speed along the way. But what you should really do is invert the problem. Don't look at every combination of letters to see if its a word. Look at each word in the dictionary and see if you can form it out of your letters. That should be faster because there are many fewer words in the dictionary then possible combination of letters.


Building tree structure based on flat objects - second follow up

As long as the underlying object is a ICollection or ICollection<T> the Count() method returns the Count property of the underlying object.

That's correct, but since your parameter has type IEnumerable<T>, and the method is public, you have no guarantee that the underlying collection is an ICollection<T>. Even in non-public methods, if you assume the underlying collection is an ICollection<T>, your method signature should reflect that; if you decide to accept the more generic IEnumerable<T>, then you should use Any(). Otherwise you have hidden assumptions throughout your code that the type system cannot help with.

Use of the var keyword would clean things up considerably.

In this code

private static IEnumerable<ArchiveTreeEntry> CreateRootEntries(
    IEnumerable<ArchiveDefinition> archiveDefinitions)
{
    List<ArchiveTreeEntry> rootArchiveTreeEntries = new List<ArchiveTreeEntry>();

    rootArchiveTreeEntries.AddRange(
        archiveDefinitions.Where(e => e.TypeOfArchive == ArchiveType.Archive)
            .Select(d => new ArchiveTreeEntry(d)));

    return rootArchiveTreeEntries;
}

there's no point creating a List<T>, you can just write

private static IEnumerable<ArchiveTreeEntry> CreateRootEntries(
    IEnumerable<ArchiveDefinition> archiveDefinitions)
{
    return archiveDefinitions.Where(e => e.TypeOfArchive == ArchiveType.Archive)
        .Select(d => new ArchiveTreeEntry(d));
}

Similarly, you can write

private static IEnumerable<ArchiveDefinition> GetNonRootArchiveDefinitions(
    IEnumerable<ArchiveDefinition> archiveDefinitions)
{
    IEnumerable<ArchiveDefinition> remainingEntries =
            archiveDefinitions.Except(
            archiveDefinitions.Where(e => e.TypeOfArchive == ArchiveType.Archive));

    return remainingEntries;
}

as

private static IEnumerable<ArchiveDefinition> GetNonRootArchiveDefinitions(
    IEnumerable<ArchiveDefinition> archiveDefinitions)
{
    return archiveDefinitions.Where(e => e.TypeOfArchive != ArchiveType.Archive);
}


Scraper for parsing email-ID using email sending button

Here are the few improvements I would apply:

match the "Email" links directly via //div[@class='businessCapsule--callToAction']//a[. = 'Email']/@href XPath expression - note how I'm matching the link by Email text
use urlparse to get the "id" number and extract that logic into a separate function
make a "scraper" class to share the same web-scraping session and persist things like headers to avoid repeating them every time you make a request
a better name for process_page would probably be send_email

Improved Code:

from urllib.parse import urlparse

import requests
from lxml import html

def extract_id(link):
    """Extracts the search result id number from a search result link."""
    return urlparse(link).path.split("/")[-1]

class YellScraper:
    MAIN_URL = "https://www.yell.com/ucs/UcsSearchAction.do?keywords=pizza&location=London&scrambleSeed=2082758402"
    EMAIL_SEND_URL = "https://www.yell.com/customerneeds/sendenquiry/sendtoone/"

    def __init__(self):
        self.session = requests.Session()
        self.session.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36'}

    def scrape(self):
        response = self.session.get(self.MAIN_URL).text
        tree = html.fromstring(response)
        for email_link in tree.xpath("//div[@class='businessCapsule--callToAction']//a[. = 'Email']/@href"):
            self.send_email(extract_id(email_link))

    def send_email(self, search_result_id):
        payload = {'message': 'Testing whether this email really works.', 'senderPostcode': 'GL51 0EX',
                   'enquiryTimeframe': 'withinOneMonth', 'senderFirstName': 'mth', 'senderLastName': 'iqbal',
                   'senderEmail': 'habibrahman@gmail.com', 'senderEmailConfirm': 'habibrahman@gmail.com',
                   'uniqueAdId': search_result_id, 'channel': 'desktop', 'ccSender': 'true', 'marketing': 'on'}

        response = self.session.post(self.EMAIL_SEND_URL, data=payload)
        items = response.json()
        item = items['emailToCustomerUUID']
        print(item)

if __name__ == '__main__':
    scraper = YellScraper()
    scraper.scrape()


You could move the duplicated lines into a function, something like this should work:

#include <stdio.h>

float get_input(void)
{
    float input;

    printf("Enter a distance in inches (0 to quit): ");
    scanf("%f", &input);

    return input;
}

int main()
{
    float inches, floatFeet, input;
    int feet;

    while (input = get_input())
    {
        feet = input/12;
        inches = (input-feet*12);
        floatFeet = input/12;
        printf("%d feet and %f inches or %f feet \n\n",feet,inches,floatFeet);
    }

    printf("Goodbye!\n");
}


File(s) encrypter implementation in python

Ways of improving:

Splitting filename

Both methods encrypt and decrypt try to split a filename into "root" part and extension. encrypt method makes that even worse and verbose with 2 statements:

    file_name = "".join(file_.split(".")[:-1])
    file_extention = "." + file_.split(".")[-1]

Instead, that's easily achievable with os.path.splittext(path) function (split the pathname path into a pair (root, ext)):

file_name, file_ext = os.path.splitext(file_)

Generating Fernet instance

Both methods encrypt and decrypt have the same 2 statements for generating Fernet instance (with only difference in salt value):

key = base64.urlsafe_b64encode(hashlib.pbkdf2_hmac("sha256", bytes(self.__password, encoding="utf-8"), salt, 100000, dklen=32))
f = Fernet(key)

It's good to extract that common behavior into a separate internal function:

def _get_fernet_instance(self, salt):
    key = base64.urlsafe_b64encode(hashlib.pbkdf2_hmac("sha256", bytes(self.__password, encoding="utf-8"),
                                                       salt, 100000, dklen=32))
    return Fernet(key)

decrypt function.
The variables save1, save2, save3 and save reassignment are confusing things rather than clarify.The variables save1, save2, save3 can be renamed to line1, line2 and salt.
Aliasing save = decrypted gives no benefit - just refer decrypted directly.Including the above mentioned optimizations the decrypt method would look as:

def decrypt(self, file_):
    file_name, _ = os.path.splitext(file_)

    with open(file_, "rb") as f:
        line1 = f.readline()
        line2 = f.readline()
        salt = f.readline()

        fernet_ = self._get_fernet_instance(salt)
        decrypted = fernet_.decrypt(line1)
        file_ext = fernet_.decrypt(line2)

    with open(file_name + file_ext.decode(encoding="utf-8"), "wb") as f:
        f.write(decrypted)

    os.remove(file_)

encrypt function.
The variable file__ in file__ = file_.read() does not give an explicit meaning for the content being read. Let the content be content or data.The same issues around variables save1, save2, save3 and redundant aliases.

In case if there would be a need to refer the input argument file_ (in both methods) as its original value in different places in methods body - you should not reassign it in context managers with open(file_, "rb") as file_:.

os.remove(file_name + file_extention) is essentially the same as os.remove(file_)

The final optimized encrypt method would look as:

def encrypt(self, file_):
    salt = os.urandom(64)
    fernet_ = self._get_fernet_instance(salt)
    file_name, file_ext = os.path.splitext(file_)

    with open(file_, "rb") as f:
        content = f.read()
        encrypted_content = fernet_.encrypt(bytes(content))
        encrypted_ext = fernet_.encrypt(bytes(file_ext, encoding="utf-8"))

    with open(f'{file_name}.enc', 'wb') as f:
        f.write(encrypted_content)
        f.write(b"\n")
        f.write(encrypted_ext)
        f.write(b"\n")
        f.write(salt)

    os.remove(file_)


Fastest / most efficient random bit indexing in Python

What exactly do you want to do with your array of booleans? If you used numpy, you could instantiate your boolean array as an array of uint8 one eighth the size of the boolean array, e.g.

In [38]: a = np.random.randint(256, size=(1000000//8,)).astype(np.uint8)

To extract items, you could do something like:

In [39]: def get_bools(a, i):
   ....:     b = i // 8
   ....:     o = i % 8
   ....:     mask = 1 << o
   ....:     return (a[b] & mask) != 0
   ....:

If you run this to extract a single item, the speed is appalling:

In [40]: idx = 500000

In [41]: %timeit get_bools(a, idx)
100000 loops, best of 3: 4.53 us per loop

But if you do it for 1000 items at once, things look (much) better:

In [42]: idx = np.random.randint(1000000, size=(1000,))

In [43]: %timeit get_bools(a, idx)
10000 loops, best of 3: 31.1 us per loop

Note that the last timing means ~30 ns per item retrieved, right where you wanted to be.

If you need to extract the boolean values one at a time, you are going to have to deal with the painful Python overhead. Notice that simply getting a single item from an array is terribly slow:

In [44]: %timeit a[62500]
10000000 loops, best of 3: 135 ns per loop

But if you can vectorize your code with numpy, or use a C array directly from cython, then you should have no problem in achieving your speed goal.


NCAA Pool - Generate random teams for a list of players

Randomly shuffling a list seven times is not any better than doing it once. So random.shuffle(playerlist) is enough.

In Python you almost never want to iterate over the indices of a list, rather iterate over the list itself. Here you could do:

import random
import itertools

regions = "East", "West", "Midwest", "South"
players = ["Player {}".format(i) for i in range(64)]
teams = range(1, len(players) / len(regions) + 1)
random.shuffle(players)

teamlist = ["{}: {} {}".format(player, *team) for player, team in
            zip(players, itertools.product(regions, teams))]

print(teamlist)

Here I used str.format to make formatting the different strings easier and itertools.product to construct a list (actually an iterable) of region, team:

>>> list(itertools.product(regions, teams))
[('East', 1), ('East', 2), ('East', 3), ('East', 4), ('East', 5), ('East', 6), ('East', 7), ('East', 8), ('East', 9), ('East', 10), ('East', 11), ('East', 12), ('East', 13), ('East', 14), ('East', 15), ('East', 16), ('West', 1), ('West', 2), ('West', 3), ('West', 4), ('West', 5), ('West', 6), ('West', 7), ('West', 8), ('West', 9), ('West', 10), ('West', 11), ('West', 12), ('West', 13), ('West', 14), ('West', 15), ('West', 16), ('Midwest', 1), ('Midwest', 2), ('Midwest', 3), ('Midwest', 4), ('Midwest', 5), ('Midwest', 6), ('Midwest', 7), ('Midwest', 8), ('Midwest', 9), ('Midwest', 10), ('Midwest', 11), ('Midwest', 12), ('Midwest', 13), ('Midwest', 14), ('Midwest', 15), ('Midwest', 16), ('South', 1), ('South', 2), ('South', 3), ('South', 4), ('South', 5), ('South', 6), ('South', 7), ('South', 8), ('South', 9), ('South', 10), ('South', 11), ('South', 12), ('South', 13), ('South', 14), ('South', 15), ('South', 16)]

Note that 0 is the default start argument for a range.

If your script becomes longer, you should probably add a if __name__ == "__main__": guard to allow importing your code from other scripts.


There is no problem modelling the request with classes representing each part of the request and a class that aggregates them.

One thing to note here, those classes adhere to builder pattern - builder of JSON.
Maybe you dont know that there is an interface \JsonSerializable which would comminucate the intent of the classes much better then a toArray() method. Although many arrays can be deemd json serializable, its not always true. Where as json serializable object is always serializable to json and it makes it clear that the json serializability is its purpose...

Then i quite dont understand this piece:

        $product
        ->setSkus($price);
        ->setSkus($stock);

You set skus to a Price object, then overwrite with Stock object?
Given this piece of data:

"skus": [
        {
          "price": {
            "offer": "offer",
            "default": "default"
          },
          "stock": {
            "available": "available",
            "amount": "amount"
          },
          "gtin": "gtin",
          "images": [
            "image",
            "image"
          ],
          "idSku": "idSku",
        }
      ]

I would expect that there is one more object between Product and Stock/Price object. Maybe a Sku object:

$product->addSku((new Sku())->setPrice($price)->setStock($stock));

And I wouldnt also see problem adding methods for more convenient work (that would instantiate the parts classes):

$sku = new Sku();
$sku->setPrice('offer', 'default');
$sku->setStock('available', 'amount')

instead of:

$sku = new Sku();
$sku->setPrice(new Price('offer', 'default'));
$sku->setStock(new Stock('available', 'amount'));

After all, those classes are not meant to represent the request, they represent a builder of a json request. And builder should make it as easy to build the target as possible....

EDIT: you were worried about coupling. I dont think this brings in any more coupling then necesary. The API uses specific keys in the request and these will never change, unless the API introduces BC break. But then maybe it was not a very good API structure... Anyway it wouldnt hurt to have those keys defined as constants of the bulder classes, so you dont have to repeat string literals all over the place... if nothing it makes it easier to find all occurences of a key.

Chances are that there are multiple ways the api could have been designed, yet retaining the same capabilities. And this means that there are also multiple ways to model the request with php objects. But you should prefer to have this 1:1. The api designer was probably aware of the multiple ways and chosen the one he chosen for a reason. And you should follow that reasoning...

Well this statement might have seem quite abstract, so let me complete it with an example. Lets say we have api structure:

{
  "scopeA": {
    "configA1": "valueA1"
  },
  "scopeB": {
    "configB1": "valueB1"
  }
}

but we can also model it as this structure:

{
  "scopeAconfigA1": "valueA1",
  "scopeBconfigB1": "valueB1"
}

but the first structure is the API structure, and so the PHP model should also have the first structure. Simply following the same reasoning why the api designers chose the first structure. Whatever reasoning it may have been...


Binary tree (S-Expression) pretty printer

Disclaimer: I am a C++ coder, but I researched to make sure none of that made it into this advise.

It looks alright, there are a couple little things.

First, explicitly state that main() takes no arguments.  This is applicable to all functions in C:

int main(void)

leaf should take an argument of Leaf rather than unsigned long, this means that you will only have one line to change if you ever want your tree to hold something else.

Tree leaf(Leaf x)

Either use <stdbool.h> if on a C99 compiler, or explicitly define true and false rather than just using 1 and 0. This will make your code more self documenting.

#include <stdbool.h>

#define true 1
#define false 0

Again, if using <stdbool.h>, use the bool type or roll your own:

typedef int bool

If you are using C11 then you can use anonymous unions to simplify your TreeStruct.  It will also mean you can remove the now superfluous .value throughout your code.

struct TreeStruct
{
    bool isNode;
    union
    {
        Node node;
        Leaf leaf;
    };
};

You don't actually use the isRoot value passed to print, but it can be used to print a newline at the end.

void print(Tree * tree, bool isRoot)
{
    if (!tree->isNode)
    {
        printf("%lu", tree->leaf);
        return;
    };

    printf("(");
    print(tree->node.left, false);
    printf(" ");
    print(tree->node.right, false);
    printf(")");

    if (isRoot)
    {
        printf("\n");
    }
};

As a matter of personal preference, I like to space things out a bit more, as you can see above.


Optimized MySQL query with complex calculation

Think one problem is that you have no key that it is using on the provider table, hence it is checking every row.

Not tested the following but this might be faster. Uses the provider_categories table as the first one (on which you are limiting the number of rows with a keyed check) and from that joining to the provider table.

SELECT b.id,
    {$algorithhm} AS score
FROM provider_categories a
INNER JOIN provider b ON a.provider_id = b.id
LEFT OUTER JOIN users_provider c ON a.provider_id = c.provider_id AND user_id = {$current_user->id}
WHERE c.provider_id IS NULL AND a.category_id IN ( {$categories} )
ORDER BY score DESC
LIMIT 3


Generating a 64 bit unique integer in Java

My specification is only to generate the 64 bit unique integer, that's it.

In this case, there's no need for anything more complicated than atomically incrementing a counter:

public class Counter {

    private static final AtomicLong counter = new AtomicLong(0);

    public static long getNextNumber(){
        return counter.incrementAndGet();
    }
}

To offer a more specific critique of your code, it's unnecessarily complicated and inefficient.  I don't see anything incorrect about it (i.e. it seems like it meets your criteria), but there's the old saying about obviously no bugs vs no obvious bugs (paraphrased).


On tkinter: scrolling multiple widgets simultaneously in different frames

Remove unnecessary imports

You're importing parts of tkinter twice, Remove this line:

from tkinter import Frame, Canvas, Scrollbar, Button

Then, whenever you need to use Frame, Canvas, etc, use tk.Frame, tk.Canvas, etc.

Don't create your own event loop

You have code that looks like this:

while True:
    <some code>
    root.update()

Instead, call mainloop once, move <some code> into a function, and call it with after if you need it to run in a loop.

def redraw():
    <some code>
    root.after(50, redraw)
root.mainloop()

Don't continually delete and recreate items on a canvas

You're continually deleting and recreating identical items on a canvas. This is inefficient and will eventually call tkinter to crash. The canvas widget does not re-use canvas ids, so each time you create a new object you get a new id. There is a limited number of ids that tkinter can manage.

Instead, create the items once, and then if you need to change them, change the existing items

def draw():
    global block1, block2
    block1 = canvas1.create_rectangle(100, 100, size_x, size_y,
                                      fill='orange')
    block2 = canvas2.create_rectangle(100, 100, size_x, size_y,
                                      fill='blue')

def redraw():
    global block1, block2
    canvas1.itemconfigure(block1, ...)
    canvas2.itemconfigure(block2, ...)

Group your layout code together

Intermixing widget creation and widget layout makes the code hard to read.

Consider this:

frame1 = Frame(root, bg='grey')
frame1.grid(row=0, column=0)
frame2 = Frame(root, bg='grey')
frame2.grid(row=0, column=1)
frame3 = Frame(root, bg='grey')
frame3.grid(row=0, column=2)

I recommend splitting this into two blocks:

frame1 = Frame(root, bg='grey')
frame2 = Frame(root, bg='grey')
frame3 = Frame(root, bg='grey')

frame1.grid(row=0, column=0)
frame2.grid(row=0, column=1)
frame3.grid(row=0, column=2)

I think this makes the code much easier to read because I can see at a glance that you're creating three frames, and that each frame is going into a separate column. In the original code it's not nearly as easy to see this without closely reading the code.

Use separate functions for scrolling in x and y direction

Your use of an argument to specify x-axis or y-axis makes the code a little bit harder to understand. Instead, I recommend using two separate functions.

For example:

def scroll_x(*args):
    global canvas1, canvas2
    canvas1.xview(*args)
    canvas2.xview(*args)

def scroll_y(*args):
    global canvas1, canvas2
    canvas1.yview(*args)
    canvas2.yview(*args)
...
yscrollbar = Scrollbar(frame3, orient='vertical', command=scroll_y)
xscrollbar = Scrollbar(frame3, orient='horizontal', command=scroll_x)

Notice how it makes the code much easier to read, since we can replace the complicated lambda with a much simpler command.


Please be careful with the indentation because it looks like there are different number of spaces for different indentation depths and it looks very weird.

Minor improvements:

Repetition

 md5 = hashlib.md5()
 path = same_size[size][i]
 md5 = hashlib.md5()

I am almost sure there is no reason to repeat md5 = hashlib.md5() twice.

"Native" iteration

while i < len (same_size[size]):
 # Hash file content with read buffer
 md5 = hashlib.md5()
 path = same_size[size][i]
 ...
 i=i+1

You are iterating over all the files with the given size:

for path in same_size[size]:
   ...

In general in Python you can use for x in list_ to iterate over all items in any collection.

Zero length automatically skipped

if len (same_size[size]) > 1:

If you ask python to iterate over a zero length collection nothing happens, so you can remove this line as it does nothing but increases indentation and line count.

edit: No @miracle173 correctly noted that this is an efficiency gain to skip files of which there is only one of a certain size so it cannot be skipped.

Default dict to simplify logic

    if file_size not in same_size:
     same_size[file_size] = list([path])
    else:
     same_size[file_size].append(path)

Not tested, but using a defaultdict you can avoid the branch and only use append.

Same size?

Are you sure you need to calculate also the size in order to check if two files are equal? Isn't the hash enough?


LINQ to Entities query with lots of grouping

This can't be called "simple". And it's not possible to tell where bottleneck is because of so many joins and subqueries.

Subqueries are certainly suspect, you can optimize them by using Dictionary<> (as you would add indexes in real DB).

I would also try to split this huge query into small ones, put ToArray() at the end of each one, and run a profiler to get some hints on what is slow.


I need help optimizing a function that returns all divisors

Welcome to Code Review!
When factorising a number, you have the property that; if a number \$ a \$ is factor of \$ n \$, then \$ \frac{n}{a} \$ is also a factor of \$ n \$.
This immediately reduces your loop from \$ 1..n \$ by half to \$ 1..\frac{n}{2} \$.
Now, another optimisation to be done could be memoisation taking into account the property above. If the number \$ \frac{n}{a} \$ is a factor, then all factors of this number would also be factors for your original number \$ n \$.
Next step you can think about is checking only for prime factors, and then using the memoisation of factors from above.
There are several other factorisation algorithms to efficiently calculate. Take a look at some of such algorithms discussed in this article. (https://cp-algorithms.com/algebra/factorization.html)


Rename and move images to a destination directory based on a text file followup

You have lots of unneeded empty lines, they also hinder readability.
fn(arg=value) is abnormal. It's common to use fn(value). It's common only to use the former when the argument is a keyword or default argument.
You don't need to make a path another path.

desination_root = Path("R:\\Pictures")
destination = Path(desination_root).joinpath(folder.stem)

Path.mkdir isn't a static method, and so it's abnormal to use it as Path.mkdir(my_path) rather than my_path.mkdir().
check_if_folder_exists isn't needed as repository.iterdir and destination.mkdir will error if they don't exist.

It should also be noted that you can pass parents=True to Path.mkdir to automatically create the folder if it doesn't exist, rather than force the user to do that.
It's better if you make another function that moves the files, and one, main, that passes it the values. Preferably main would be changed to not use static values and get the values from a config file.
finally isn't needed.
You should raise a SystemExit(1) or use sys.exit(1) if there is an error. They both do the same thing which notifies the system that the program failed. It didn't run without problems.
Given that generating a name that doesn't conflict with existing files is not a simple one-liner I'd recommend you move it out into a function.

I should note that it may overwrite files, if you have a folder with file_1.png and file_3.png your code's going to overwrite file_3.png, but not have a file_2.png.

You changed away from some of the above, and so I'd recommend you think about the differences, which is easier to re-use, which is easier to read, which performs the correct action in the situation. If you don't know what the difference is even with my explanation, such as with SystemExit(1), then you should look up what it does.

import os
from pathlib import Path
import shutil

def gen_name(path, number):
    orig_name = path.parent.name.lower().replace(" ", "_")
    return f"{orig_name}_{number}{path.suffix}"

def move_files(src, dest):
    for folder in Path(src).iterdir():
        destination = Path(dest) / folder.stem
        destination.mkdir(exist_ok=True, parents=True)
        start = len(os.listdir(destination)) + 1
        for number, image in enumerate(folder.iterdir(), start=start):
            image_name = gen_name(image, number)
            destination_image = destination / image_name
            print(f"{image} will be named {destination_image}")
            shutil.move(image, destination_image)

def main():
    try:
        move_files(
            "{0}\\{1}".format(os.getenv("USERPROFILE"), "Repository"),
            "R:\\Pictures",
        )
    except(ValueError, FileNotFoundError, OSError) as error:
        print(error)
        raise SystemExit(1) from None

if __name__ == '__main__':
    main()

I think it could make more sense for gen_name to be a closure, as then it can correctly handle existing files. I won't change how the code functions, but will show how it could be implemented.

def gen_name_builder(folder):
    orig_name = folder.name.lower().replace(" ", "_")
    number = len(os.listdir(destination))
    def gen_name(file):
        nonlocal number
        number += 1
        return f"{orig_name}_{number}{path.suffix}"
    return name

def move_files(src, dest):
    for folder in Path(src).iterdir():
        destination = Path(dest) / folder.stem
        destination.mkdir(exist_ok=True, parents=True)
        gen_name = gen_name_builder(destination)
        for image in folder.iterdir():
            image_name = gen_name(image)
            destination_image = destination / image_name
            print(f"{image} will be named {destination_image}")
            shutil.move(image, destination_image)


This is a fascinating solution. I kept looking at it and thinking "There must be an easier way!" but every possible solution I came up with had a fatal flaw.

All I really have, then, is nitpicking:

public static IEnumerable<Assembly> Assemblies => AssemblyNames
        .Select(an => Load(an))

Can be simplified to:

public static IEnumerable<Assembly> Assemblies => AssemblyNames
    .Select(Load)

SolutionAssemblyNames is looking fairly dense. I'd add 1 line of whitespace between each property to make it a bit more readable.


You don't actually care about indexes during the iteration; you just want the contents. The loop would be better written as

sentence = input(…)
for word in sentence.split():
    if word[0] in "aeiou":
        …

How would you reassemble the results?  Noting that each word can be translated independently, I would define a function for that, then use a generator expression.

def pig_latin(word):
    if word[0] in "aeiou":
        return word + 'yay'
    else:
        return word[1:] + word[0] + 'ay'

sentence = input("Enter a sentence you want to convert to pig latin: ")
print(' '.join(pig_latin(word) for word in sentence.split()))


Offload more functionality into depth_first_search()
One improvement your solution has over LeetCode's is that you move the grid boundary check into depth_first_search(). However, you can do more, by having it return whether you are starting on an island or in the ocean:
bool depth_first_search(...) {
    // Checks for grid boundaries and '0' cells
    if (...)
        return false;

    // We are on an island, recurse
    ...

    return true;
}

Then, the loop inside numIslands() can be simplified:
for (std::size_t row = 0; row < row_length; row++)
    for (std::size_t col = 0; col < col_length; col++)
        islands += depth_first_search(grid, row, col, row_length, col_length);

Naming things
While depth_first_search() does iterate in a depth-first fashion, it is not search for anything. Rather, it is implementing a flood fill algorithm. But here we use it to remove an island. If it also performs a check to see if there is an island at the given position, I would name it check_and_remove_island(). As Emily L. mentions, a function name that reads like foo_and_bar() is usually a hint that it should be split into a foo() and bar(). If you want to go that way, I suggest you make it so you can write the following code:
if (is_island(grid, row, col)) {
    islands++;
    remove_island(grid, row, col);
}

Get rid of the size variables
I don't think it's that useful to store the sizes into separate variables, and to pass them explicitly to depth_first_search(). This information can always easily be gotten from the variable grid. This also gets rid of the check for an empty grid:
std::size_t numIslands(std::vector<std::vector<char>>& grid) {
    size_t islands{};

    for(std::size_t row = 0; row < grid.size(); row++)
        for (std::size_t col = 0; col < grid[row].size(); col++)
            islands += check_and_remove_island(grid, row, col);

    return islands;
}

You have to modify depth_first_search() to match of course.


typedef size_t hkey_t; doesn't seem right. Since hash has to be implemented by the client, the client must know exactly what hkey_t is. It would however make certain sense to use hkey_t throughout your code.
It is very suspicious that data argument to remove has an extra level of indirection, compared to insert and lookup. Is it a typo?
I'd recommend to allocate buckets with calloc instead of malloc. Then a cleanup loop of chtb_init can be replaced with a call to chtb_destroy, that is stating your intention explicitly.
Since the linked_list.h code is not posted, it is impossible to reason about the rest of the functions (specifically, return codes). In general, it make sense to return more than just failure code (a pointer to an inserted node, maybe? - cf STL inserts).


Regular Expression replace specific characters

You could use a regular expression and Dictionary<string, string> to do the search replace:

// This regex matches either one of the special characters, or a sequence of
// more than one whitespace characters.
Regex regex = new Regex("['\"&,\\\\]|\\s{2,}");

var map = new Dictionary<string, string> {
    { "'", "`"},
    { "\"", "`"},
    { "&", "and" },
    { ",", ":" },
    { "\\", "/" }
};

// If the length of the match is greater that 1, then it's a sequence
// of spaces, and we can replace it by a single space. Otherwise, we
// use the dictionary to map the character.
string output = regex.Replace(input.ToUpper(),
    m => m.Value.Length > 1 ? " " : map[m.Value]);


Calculating IRR (Internal Rate of Return) in Ruby using recursion

Sanity checking
You should probably add some sanity checks. It's entirely possible to provide a range that'll never produce a result.
Separate output from calculation
Your test code ends up printing an extra blank line because #irr doesn't actually return anything. It'd be nicer to let #irr actually return the rate it found; you can do whatever you want with it afterward. Right now it just prints.
Too many splats
Variadic arguments are neat, but aren't really that necessary here. It'd be simpler and more straightforward to pass an actual array for the amounts.
Repetition
No need to do call present_value_of_series two-three times in a row, like you do here:

if present_value_of_series(rate, *amounts) < 0
  if present_value_of_series(rate, *amounts) >= -precision_level
    #debug puts "present value = #{present_value_of_series(rate, amounts)}"

Just stick it in a variable.
#present_value_of_series
This can be simplified by not treating the initial value as a separate argument, and using #reduce to do the sum:

def present_value_of_series(rate, amounts)
  amounts.each_with_index.reduce(0) do |sum, (amount, index)|
    sum + amount / (rate + 1)**index
  end
end

Note that this also matches your other code where you do treat the amounts as an array. No need for * splats.

As a general note, you rarely need while or for loops when iterating arrays in Ruby. There's almost always a neater way.
#irr
Since you're dealing with a range, it'd be nice to use, well, a Range. A range also gives you a #step iterator, which is useful here.

Here's what I came up with. It works the same as yours (recursion), but I can't say I'm super happy with it - returning from inside the #detect block feel wrong, but it avoids recalculating the present value afterward to check it against -1.

def irr(range, step, amounts)
  rate = range.step(step).detect do |rate|
    present_value = present_value_of_series(rate, amounts)
    if present_value < 0
      return rate if present_value >= -1
      true
    end
  end

  if rate.nil?
    raise "No solution"
  else
    irr((rate-step..rate), step / 10, amounts)
  end
end

Still needs extra sanity checks, though.

A possible optimization (trading some memory for computation) would be to use Array#bsearch instead of #detect. It does however mean that the range has to be made into an array first (e.g. range.step(step).to_a.bsearch ...).

Speaking of binary searching, you could also do:

def irr(min_rate, max_rate, amounts)
  range = max_rate - min_rate
  raise "No solution" if range <= Float::EPSILON * 2

  rate = range.fdiv(2) + min_rate
  present_value = present_value_of_series(rate, amounts)

  if present_value > 0
    irr(rate, max_rate, amounts)
  elsif present_value < -1
    irr(min_rate, rate, amounts)
  else
    rate
  end
end

Basic idea is that it keeps guessing in the direction of the answer by testing a rate midway between min_rate and max_rate. It gives up if the difference between min_rate and max_rate would introduce floating point precision loss.

It's the fastest solution of the bunch, though it could perhaps be smarter about checking the initial min/max before starting the iteration (it could do that up front by calculating present values for max and min, and only then, if the range makes sense, handle the iteration in separate method). It should probably have a precision argument as well, but that's trivial.


Be careful of IDs, especially those with common names, since they (unfortunately) automatically create properties on the global object when the ID is a valid identifier, which is not an uncommon source of bugs 2. Here, you have #messages, which is probably a pretty common word related to your script. It's not likely to be a problem in most cases, but I'd feel more comfortable using a class instead.
CSS tweak Due to positioning, the send button appears to have an unusually thick border on the right. Consider using width: 9.5%; instead of width: 9%;. You could also consider using flex for the <form> instead, and only set an explicit width of a few % for the button, letting the <input> horizontally expand to take up the rest of the space automatically, without hard-coding.
jQuery? You have a few uses of $ that look like uses of jQuery, but it doesn't appear to exist as a


Initial stages of MVP, is the bootstrap file efficient coding

You can add another folder named libraries inside of app.
Follow a particular case convention. Like don't have config (all small) and other folders with first letter capitalized. Either all small or all first letter capitalized.
Add a language folder within app. That will store your language strings within each language folder. For example, you can have a language/english folder & similarly for other languages.

I like that you have separated the public folder.


Game combo press model (substring search)

Bug

Since you never mark your suffix tree nodes as end nodes, your search will find combos that don't exist.  For example, if ABXY is a registered combo, and you search for AB, it will return both A and AB as combos.  You should have a boolean per node telling you whether the node is the end of a combo or not.

Efficiency

You appear to search for all sublists that end with the end of the original list.  For example, if the original search list were ABXY,you would search for these sublists: ABXY BXY XY Y.

Given this behavior, you could greatly improve your suffix tree by storing the combos in reverse order.  Then, when you want to search for a given list and all of its sublists, you search the suffix tree once in reverse order.  For example, given ABXY, you search the suffix tree for YXBA and return up to four combos that match (Y YX YXB YXBA).  This would reduce your search from \$O(n^2)\$ to \$O(n)\$.

How to mark end nodes

This is in response to the comment.  Given a tree with combos A B X Y ABXY, the tree would look like this:

                          Root
                      /  |   |  \
                     A*  B*  X*  Y*
                    B
                   X
                  Y*

In the tree above, the end nodes are marked with a *.  So if you searched for combo AB, it would go down the left branch from the root but it would not find a combo because the node B on the left branch does not have a *.

Why searching in reverse order is more efficient

Suppose you are given combos A B X Y ABXY.  If you reversed each combo and added to a tree, your tree would look like:

                          Root
                      /  |   |  \
                     A*  B*  X*  Y*
                                  X
                                   B
                                    A*

Now suppose you were given ABXY as your search list, meaning you actually want to search for the four sublists ABXY BXY XY Y.  You could do this in one search by searching for YXBA and returning a positive match every time you find an end node.  So in the tree above, you would follow the rightmost path four levels, passing by the lists Y YX YXB YXBA.  Since Y and A are marked as end nodes, you would return Y and YXBA as matches.  After reversing, these would correspond to Y and ABXY as matches.  Notice that you only have to traverse the tree once instead of 4 times.


Getting the miliseconds from now to the next midday

if (r > 0) // It's before noon
   ;
else // It's after noon
   r = TimeSpan.FromTicks(TimeSpan.TicksPerDay).TotalMilliseconds + r;

Change to:

if (r <= 0) // It's after noon
   r = TimeSpan.FromTicks(TimeSpan.TicksPerDay).TotalMilliseconds + r;

No need to have an if that does nothing.


f=open('C-large.in')

Don't sue single letter variable names, its really hard to read

    noi=int(f.readline().rstrip('\r\n'))

Since the default is already to remove whitespace, why both with the \r\n parameter?

    i=1
    ou=open('jam.out','w')
    while i<=noi:

Use for loops, not while loops to count

      re=f.readline().rstrip('\r\n')

re is a really bad name because its the same as the regular expression module

      rs=re.split()
      a=int(rs[0])
      b=int(rs[1])

I'd use a,b = map(int, re.split())

      ans=0
      c=[x for x in range(a,b+1)]

Use c = list(range(a,b+1))

      for ind,x in enumerate(c):
          for y in c[ind+1:]:

That's gonna be inefficient. Firstly, you can easily express it using simple ranges

for x in range(a, b+ 1):
    for y in range(x + 1, b + 1):

and therefore avoid the slices.

But you can do much better. You are only interested in values of y which are recyclings of x. Instead of generating the rather large number of possible second numbers, try just generating the fairly small number of possible ways to recycle x.

              n=str(x)
              m=str(y)

Converting all your numbers to strings will be expensive. See if you can keep them as integers and just do math operations on them

              if len(n)==len(m) and len(n)>1 and len(m)>1:
                 ki=1
                 while ki <len(n):

Again, use for loops to count

                     temp=n[-1:-(ki)-1:-1][::-1]+n[:-(ki)]

temp should be banned variable name. All variables are temporary, use a more helpful name.

                     if temp[0]!='0':
                      if temp==m:
                         ans+=1
                         break
                     ki+=1
              else :
                  break

      print("Case #%s:"%(i),ans,file=ou)

Normally, we use %d for numbers

      i+=1
    ou.close()
    f.close()


Eliminating columns from a matrix where the entries in two rows are equal

In general, you speed up Matlab programs by computing whole vectors or matrices at once, rather than writing loops. In this case, you can generate a "logical" vector that contains 1 in each column where the corresponding column in A has different values in rows 4 and 5, and 0 in the other columns:

selected_columns = A(4, :) ~= A(5, :);

Then you want to collect all the rows of A, in the columns where the two rows are different:

B = A(:, selected_columns);

I tested the idea in Octave, since I don't actually have Matlab:

octave-3.4.0:7> A = [1, 1, 2, 2, 3, 4, 5;1, 2, 3, 2, 1, 4, 5]
A =

   1   1   2   2   3   4   5
   1   2   3   2   1   4   5

octave-3.4.0:8> selected_columns = A(1, :) ~= A(2, :)
selected_columns =

   0   1   1   0   1   0   0

octave-3.4.0:9> B = A(:, selected_columns)
B =

   1   2   3
   2   3   1

This isn't exactly equivalent to your original code, but it's probably closer to what you meant anyway. Specifically, if A has more than 4000 columns, my code will include the extra ones, while yours will drop them. My code also doesn't care about the initial value of B, while yours can include extra columns from B that weren't in A. Similarly, your code can fail if A is narrower than 4000 columns, or if B is too narrow to hold all the unequal columns from A.


The code is pretty clear in what it does, good work.

# We define a function here.
def ...
...
... = {} # Empty dictionary
...
... = False # Set the flag to 'False'

Many of these comments are not all that useful. I can see by looking at the code that the flag is set to false, or that a function has been defined. Usually you would comment with the reason why a piece of code exists. If you removed a comment from beside some code, could you still work out what the code does? If so the comment is probably not useful.

def display_comments():
    """Displays User Input (comments)"""
    if user_comments:  # If the dictionary 'user_comments' has at least one key value pair then execute this block of code.
        print("\nTop Comments:")
        for username, comment in user_comments.items(): # Define a for loop for each key value pair in the dictionary 'user_comments'.
            print(f"\n\t{username}: {comment}.")  # Print each key value pair.

This looks pretty good. It does what it says it does. Remove the inline comments and it is golden.

banned_users = ['pete', 'jack', ...
...
if username.lower() in banned_users:

Extracting banned users to a list is good. An issue might arise here if a with an uppercase letter is is added to the banned list. He won't be prevented from commenting! In general there are two ways to avoid this problem

Do a case-insenstive compare. In a Java this would be done with username.equalsIgnoreCase(banned_user)
Normalize both strings and then compare. This is the recommended method in Python.

So I would suggest making sure every banned user has been lowercased

banned_users = ['pete', 'jack', ...
banned_users = [banned_user.lower() for banned_user in banned_users]

If you believe you'll ever need to deal with international usernames casefold may be of interest. It will normalize strings more aggressively than lower will.

One result of lowercasing the names is that it cuts down on the number of available usernames. If Ben Dor and B. Endor both try to sign up as BenDor and BEndor respectively, only one can get the name. Is that OK? Will this ever be a problem?

repeat = input(continue_prompt)
if repeat == 'no':

This is one place I would lowercase as an answer of "NO" or "No" clearly indicate the user is done.

user_comments = {}
...
user_comments[username] = comment

As the comments are stored in a dictionary, every username will only have one comment, the latest one they've made. For instance if the chat was meant to be

A: where is the coal?
B: walk west for 2 mins then
B: north for 1 min

The comments appear as

A: where is the coal?
B: north for 1 min

Is that intended? If not you can change to use a list containing the username and comment instead

comments = []
...
comments.append((username, comment))

and display_comments looks nearly identical

for username, comment in comments:
    ...


HackerRank - Filter huge list for elements that occur more than a given number of times

It seems that the suggestion I got in the comment is enough to pass the HR test:
import Data.Maybe (fromJust)
import Data.List (foldl', nub)
import qualified Data.Map as M

main :: IO()
main = do
  nCasesStr <- getLine
  let nCase = read nCasesStr :: Int
  sequence_ $ replicate nCase $ do
    k    <- (str2int. last . words) <$> getLine
    list <-    map str2int . words  <$> getLine
    let outList = processList k list
    if null outList
      then putStr $ show (-1)
      else mapM_ (putStr . (++" ") . show) outList
    putStrLn ""
    where
      str2int = read :: String -> Int

processList :: Int -> [Int] -> [Int]
processList k = nub . (filter <$> (flip (\x -> (k <=) . fromJust . M.lookup x . list2map)) <*> id)
  where
    list2map = foldl' step M.empty
    step map num = M.insertWith (+) num 1 map


Acquiring a hash containing a key and a value

This is just about your current code; existing answers have good suggestions for ways to do the entire thing differently.

As sschmeck notes, you can make good use of each_with_object here, even without radically changing your code. For instance, your helpers could be:

def build_counter_cache(definitions = [])
  counter_cache = Hash.new { 0 }
  definitions.each_with_object(counter_cache) do |d, cache|
    cache[d[:name]] += 1
  end
end

def build_fields_cache(fields = [])
  fields.each_with_object({}) do |f, cache|
    cache[f[:id]] = f[:value]
  end
end

The Hash.new { 0 } trick creates a hash that will return 0 for unknown/unset keys. So you don't need the if else in your block. (Note that the hash-with-fallback-value can bite you; it always returns the same object reference. In this case, it works, since we're using an immutable integer, but if you were to say Hash.new { [] }, you'd be getting the same array each time.)

You also have a pretty redundant method in the form of all_mocks. Really the same thing can be achieved with:

definitions, fields = mock_definitions, mock_fields

or, more readably, simply say:

definitions = mock_definitions
fields = mock_fields

All the all_mocks method does is add a layer of obfuscation to what's going on. You still need to know that it returns definitions and fields, in that order, if you want to use it. So if you have to know that, why bother calling the method in the first place?

As for alternative code, I'd do things much like sschmeck already suggested, though I'd still split the task into multiple methods rather than one big one.


The code is pretty good as it is. Here is how I would improve it:

Constant handling

In C++, you should prefer const over #define. So

#define INITIAL_CAPACITY 5

becomes

const int INITIAL_CAPACITY = 5;

Also don't use all uppercase names for non constant variables. It is
confusing and breaks the 50 year old tradition.

Clearer names

I renamed a few of your variables:

MIN_CAPACITY => capacity Because the instance variable holds the
current capacity of the dynamic array, not the minimum capacity.
length() => size The words length and size are synonymous but
using them both can cause confusion. A reader might think is the
length the number of elements in the array and size the allocacted
size, or vice versa?

Offby one errors

You have an offby one error in deleteAt. If you have a dynamic array
with 5 elements, then their positions are 0 to 4 so deleteAt(5)
shouldn't work, but it does. I've fixed that for you.

Pretty printing

Adding pretty printing functions is almost always a good idea because
they make debugging much easier. I've added one for you.

Error handling

Your error handling consists of printing to stdout and letting the
program continue to run. That is incorrect because errors might not be
discovered if stdout is redirected or the user is not paying attention
to what is printed.

There are many ways to handle errors. I've implemented basic assert
based error handling for you. But you can certainly be fancier and use
exceptions or status codes.

Functions implemented in terms of each other

For all dynamic arrays dynarr.append(x) is equivalent to
dynarr.insertAt(x, dynarr.size()). So append can just call
insertAt.

Destructor

Your dynamic array allocates memory in the constructor, but there is
no corresponding destructor that frees the memory. I've added one
looking like this:

~dynamic_array() {
    delete[] array;
}

Copying memory

There's a function called std::copy which you can use for copying
memory. That way, you don't have to write your own copy function.

Pointless comments

Writing good comments is hard. As a reviewer I much prefer no comments
over pointless comments. An example of a pointless comment is //
constructor init. I can see that the lines below is the constructor
so the comment doesn't tell me anything I didn't already know. Same
for the comment // returns size of array.

Source code

Here is the improved version of the dynamic array:

#include <assert.h>
#include <cstring>
#include <iostream>

using namespace std;

const int INITIAL_CAPACITY = 2;
const int GROWTH_FACTOR = 2;

template <class T>
class dynamic_array {
    T *array;
    int capacity = INITIAL_CAPACITY;
    int _size;

public:
    dynamic_array() {
        array = new T[capacity];
        _size = 0;
    }

    ~dynamic_array() {
        delete[] array;
    }

    void deleteAt(int pos) {
        assert(0 <= pos && pos < _size);
        _size--;
        for (int i = pos; i < _size; i++) {
            array[i] = array[i + 1];
        }
    }

    void insertAt(int element, int pos) {
        assert(0 <= pos && pos <= _size);
        if(_size == capacity) {
            resize();
        }
        for(int i = _size; i > pos; i--) {
            array[i] = array[i-1];
        }
        _size++;
        array[pos] = element;
    }

    void append(T element) {
        insertAt(element, _size);
    }

    int size() {
        return _size;
    }

    // doubles capacity if it has to and deletes reference to current array.
    void resize() {
        capacity *= GROWTH_FACTOR;
        T *temp = new T[capacity];
        copy(array, array + _size, temp);
        delete [] array;
        array = temp;
    }

    T get(int pos) {
        return array[pos];
    }

    void pretty_print() {
        cout << "[";
        for (int i = 0; i < _size - 1; i++) {
            cout << array[i] << " ";
        }
        if (_size) {
            cout << array[_size - 1];
        }
        cout << "]\n";
    }
};


Implementing Luhn's algorithm to validate a credit card number in Java

Ordering

The ordering is a bit mixed. Try to an ordering such as: variables, constructor, public methods, private methods. There's no real convention for that, but try to tell the reader the story about your class. As for instance the member vars are the protagonists, the Constructor is the entry of a book, and the methods are the chapters.

Probable bugs

Even and odd sum are never assigned

simplify

In validateCompany, you can assign the char once and use a switch-statement.
In validateLength: String has a length() method.
In isDivisibleBy10: You call getEvenSum and getOddSum, add both values up, even though you have a getSum method.

concerns

The validateCompany method assigns the company. On one hand, the developer who uses your api would never figure that out. Also, you have to call validate, otherwise you wouldn't get the company
The constructor gets a credit card number passed. At the same time it reads from the console. And then ignores the input and assignes "0;" to the local variable. Only pass the number, that should be enough, the type shouldn't care about how the number is loaded.
getCcNumber: This method too should not read from the console. It should return the value which was passed to the constructor.

public methods

The only method you call in your tester class (which should start with a capitalized T), only calls the isValid() method. Reduce the visibility of all other methods. Depending on how the type is used, the user of the API will see too many methods, he only needs one. And beside that: It's a common principle to hide as much implementation as you can, also known as 'information hiding'

Hope this helps,
slowy


I prefer to make a distinction on semantic level: there are no functions or methods, but instead there are properties and actions. Every property is an object (in real-world sense) and an action is something done on an object. A good mnemonic is probably to read () as do it!.

Consider a variable:

$document

You know by the name it's an object, since it's a noun.

$document->author

Even though author is probably a function/method, an author is an object and a noun, so it's a property and thus no parens here.

$document->send()
$document->author->write_book()

Again, send and write_book are functions/methods, but since those are actions (as designated by verbs), we write parens behind them.

$document->author_count
$document->has_reviews

Again, a function/method, but a property of a document object, not an action, so no parens. A boolean value or an integer is strictly speaking not a real-world object, but it's more like an object than an action.


Don't leak Context

It's not good to leak Context out of an Activity/Service. Your class needs just the output of context.getFilesDir(), so store just that:

private final File parentDir;

public PageDownloader(Context context) {
    parentDir = context.getFilesDir();
}

Hardcoded strings

It would be better if the filename was a parameter, not a hardcoded string. If you must hardcode, then at least make it a constant:

private static final String FILENAME = "tmpPage.html";

Hide internal methods

It's good to make everything private by default, and change to less strict access only when there is a good reason to do so. For example the _download method will only be called from your inner class, so there's no need to make it public, so change it to private.

Reading from a stream

The way you read from the input stream has many problems:

It's inefficient to build long strings by appending to a String with +=. Use a StringBuilder instead.
Since you initialized String result = null, as you append the input to it your end result will start with the literal string "null". You probably meant to initialize with String result = "".
The available method of InputStream is not very useful in practice, and it can be misleading. I would recommend using a constant instead.
You are not closing the input stream after reading from it, which can lead to a resource leak.
You should not use e.printStackTrace(), but log instead
The comments //DOWNLOAD and //SAVE are completely pointless

Variable and method naming violations

You're not following common naming practices: variable and method names should be camelCase and not start with _. Class names should be CamelCase (starting with capital letter). For example:

download instead of _download
TestClass instead of testClass

Of course, an even bigger issue with your names is that they are not descriptive. For example the variable r, the class TestClass, and many others. You should review ALL your variables/methods/classes and give them more descriptive names so your code reads like a story.

Suggested implementation

private static final String TAG = "PageDownloader";
private static final int BUFSIZE = 1024;

private void download(String urlString) {
    StringBuilder builder = new StringBuilder();
    InputStream in = null;
    try {
        URL url = new URL(urlString);
        URLConnection con = url.openConnection();
        con.connect();
        in = con.getInputStream();
        byte[] data = new byte[BUFSIZE];
        while (in.read(data) != -1) {
            builder.append(new String(data));
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage(), e);
        return;
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }
    saveFile(builder.toString());
}


Find the oldest person by Lithuanian National Identification Number

Headers

Prefer <cmath> to <math.h> when writing new C++ code.  It seems it's not required in this program, so prefer to omit it instead!

<fstream> is only required for the test program - I'll move it to after the function.  (In fact, I'll use a string stream instead, to make the test program self-contained).

Avoid using namespace std;, especially in headers - there's many answers here on Code Review that explain why it's harmful.

Types

Enumeration types are normally named as singular, unless they are intended to be combined as bitmask values.  That's a useful convention to maintain, so let's rename Genders to Gender.  We never want Gender to implicitly convert to and from integer values, so we can make it a strong enumeration, using enum class.

We can improve the cohesion of Person by observing that all its properties are derived from the ID number.  Instead of requiring client code to populate all fields, we can supply a constructor which accepts the ID number and populates the whole structure from it.

We might even choose to store only the number (to reduce the size of Person) and compute the derived properties when needed.  That would be an appropriate strategy if we had a much larger number of input lines.

We can present a public interface that doesn't depend on our implementation choice:

class Person
{
public:
    Person(long kodas);
    Gender gender() const;
    int dobYear() const;
    int dobMonth() const;
    int dobDay() const;
    long code() const;
};

I also suggest making the comparison and formatting functions into members:

class Person
{
public:
    Person(long kodas);
    Gender gender() const;
    bool older_than(const Person& other) const;
    std::ostream& operator<<(std::ostream&) const;
};

(Note that the birth date no longer needs to be public).

Implementation

We don't need to split the code into year, month and day to compare - we can just sort the numbers directly (because 10000*year + 100*month + day will sort the same way).  If we did need to sort based on multiple fields, we could use std::make_tuple() or std::tie() to simplify the code.

When printing month and day, it's usual to zero-fill single-digit numbers.

We should check that we reached end-of-stream - if not, that indicates a read error, and we can't claim to have found the answer.

Modified code

#include <iosfwd>

enum class Gender {
    Man, Woman
};

class Person
{
    long kodas;
public:
    Person(long kodas);
    Gender gender() const;
    bool older_than(const Person& other) const;

    friend std::ostream& operator<<(std::ostream&, const Person&);

private:
    long remove_gender() const;
};

#include <iomanip>
#include <ostream>
#include <stdexcept>
Person::Person(long kodas)
    : kodas{kodas}
{
    if (kodas < 0)
        throw std::domain_error("negative ID");
}

Gender Person::gender() const
{
    auto firstDigit = kodas / 10000000000;
    return firstDigit % 2 ? Gender::Man : Gender::Woman;
}

bool Person::older_than(const Person& other) const
{
    return remove_gender() < other.remove_gender();
}

std::ostream& operator<<(std::ostream& os, const Person& p)
{
    auto n = p.remove_gender() / 10000;
    int century = 18 + n/2000000;
    n %= 1000000;

    int year = n / 10000;
    n %= 10000;

    int month = n / 100;
    int day = n % 100;

    // save stream settings
    auto fill = os.fill();

    return os << std::setfill('0')
              << century
              << std::setw(2) << year
              << '-'
              << std::setw(2) << month
              << '-'
              << std::setw(2) << day
              << std::setfill(fill);
}

long Person::remove_gender() const
{
    return gender() == Gender::Woman ? kodas - 10000000000 : kodas;
}

#include <sstream>
#include <iostream>
int main () {
    std::istringstream kodai(
                        "33309240064\n"
                        "40212220064\n"
                        "50211020064\n"
                        "10001010064\n"
                        "20001010064\n"
                        );

    Person oldestMan(99999999999);
    Person oldestWoman(89999999999);

    long code;
    while (kodai >> code) {
        Person person{code};
        switch (person.gender()) {
        case Gender::Woman:
            if (person.older_than(oldestWoman))
                oldestWoman = person;
            break;
        case Gender::Man:
            if (person.older_than(oldestMan))
                oldestMan = person;
            break;
        }
    }
    if (!kodai.eof())
        throw std::runtime_error("Failed to read whole file");

    std::cout << "Oldest man: " << oldestMan << std::endl;
    std::cout << "Oldest woman: " << oldestWoman << std::endl;
}