Bowling kata solution in java This is my first bowling kata solution in java. I would be very grateful if you say something about that. I want to learn from you to become a better programmer.
I think the score method is quite small, but is it clear enough as well?
How can I improve it more?

public class BowlingGame {

  int[] rolls = new int[21];
  int currentRollIndex = 0;

  public void roll(int roll) {
      if (currentRollIndex < 21) {
          rolls[currentRollIndex++] = roll;
      }
  }

  public int score() {
      int score = 0;
      int index = 0;
      for (int i = 0; i < 10; i++) {
          score += rollIndex(index++);
          if (isStrike(index - 1)) score += rollIndex(index, index + 1);
           else {
              score += rollIndex(index++);
              if (isSpare(index - 2)) score += rollIndex(index);
          }
      }
      return score;
  }

  private boolean isStrike(int index) {
      return rolls[index] == 10;
  }

  private boolean isSpare(int index) {
      return rolls[index] + rolls[index + 1] == 10;
  }

  private int rollIndex(int... indexes) {
      int sum = 0;
      for (int i = 0; i < indexes.length; i++) sum += rolls[indexes[i]];
      return sum;
  }
  }

JUnit test:

public class BowlingKataTest {

    public BowlingKataTest() {
    }
    Bowling bowling;

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
        bowling = new Bowling();
    }

    @After
    public void tearDown() {
    }

    @Test
    public void NullTest() {
        bowling.roll(0);
        assertEquals(0, bowling.score());
    }

    void setRolls(int n, int pin) {
        for (int i = 0; i < n; i++) {
            bowling.roll(pin);
        }
    }

    void set2Rolls(int n, int pin1, int pin2) {
        for (int i = 0; i < n; i++) {
            bowling.roll(pin1);
            bowling.roll(pin2);
        }
    }

    void setArrayRolls(int[] n) {
        for (int i = 0; i < n.length; i++) {
            bowling.roll(n[i]);

        }
    }

    @Test
    public void OnesTest() {
        setRolls(20, 1);
        assertEquals(20, bowling.score());
    }

    @Test
    public void OnesBonusTest() {
        setRolls(10, 1);
        bowling.roll(10);
        setRolls(8, 1);
        assertEquals(30, bowling.score());
    }

    @Test
    public void FullBonusTest() {
        setRolls(12, 10);
        assertEquals(300, bowling.score());
    }

    @Test
    public void FullHalfBonusTest1() {
        set2Rolls(10, 3, 7);
        bowling.roll(10);
        assertEquals(137, bowling.score());
    }
    @Test
    public void FullHalfBonusTest2() {
        setRolls(21, 5);
        assertEquals(150, bowling.score());
    }
    @Test
    public void RealTest() {
        int[] rolls = {0,10,5,5,3,2,10,10,3,7,7,1,4,2,9,1,8,2,5};
        setArrayRolls(rolls);
        assertEquals(140, bowling.score());
    }
}

Overall, looks good design. good breakdown into methods.
Here are my comments:

Avoid magic numbers
Magic numbers are literals (String or Numeric values).  They should be replced with constant variables (public static final ... and UPPER_CASE named).  This has two benefits: 1) give meaning to the literal value (helps readability) and 2) one place to change value and also avoid (runtime!) errors due to incorrect value due to typo.
Example: public static final int MAX_ROLL_COUNT = 21;
Meaningful variable names
This is particularly useful in your case where you have multiple index variables. You have both i and index.  IIUC, i is index on frames (==turns in bowling jargon, and don't forget to replace literal used as loop limit with constant!) and index is index on rolls.
Meaningful method names
rollIndex() is not a good name. perhaps calculateScoreForFrame() or something similar
Use collection streams
Depending on your proficiency in the language, you may want to experiment with replace these for loops with Java 8 collection streams.  It (arguably) makes the code even more clearer.


Conway's Game of Life in C++ This is my attempt at Conway's Game of Life. It works, and it's the most complicated program I've made to date.  I'm sure it's pretty poorly done. Any ideas on how I can improve on it?

#include <iostream>
#include <cstdlib>

const int gridsize = 75; //Making this a global constant to avoid array issues.

void Display(bool grid[gridsize+1][gridsize+1]){
    for(int a = 1; a < gridsize; a++){
        for(int b = 1; b < gridsize; b++){
            if(grid[a][b] == true){
                std::cout << " *";
            }
            else{
                std::cout << "  ";
            }
            if(b == gridsize-1){
                std::cout << std::endl;
            }
        }
    }
}
//This copy's the grid for comparision purposes.
void CopyGrid (bool grid[gridsize+1][gridsize+1],bool grid2[gridsize+1][gridsize+1]){
    for(int a =0; a < gridsize; a++){
        for(int b = 0; b < gridsize; b++){grid2[a][b] = grid[a][b];}
    }
}
//Calculates Life or Death
void liveOrDie(bool grid[gridsize+1][gridsize+1]){
    bool grid2[gridsize+1][gridsize+1] = {};
    CopyGrid(grid, grid2);
    for(int a = 1; a < gridsize; a++){
        for(int b = 1; b < gridsize; b++){
            int life = 0;
        for(int c = -1; c < 2; c++){
            for(int d = -1; d < 2; d++){
                if(!(c == 0 && d == 0)){
                    if(grid2[a+c][b+d]) {++life;}
                }
            }
        }
            if(life < 2) {grid[a][b] = false;}
            else if(life == 3){grid[a][b] = true;}
            else if(life > 3){grid[a][b] = false;}
        }
    }
}

int main(){

    //const int gridsize = 50;
    bool grid[gridsize+1][gridsize+1] = {};

    //Still have to manually enter the starting cells.
    grid[gridsize/2][gridsize/2] = true;
    grid[gridsize/2-1][gridsize/2] = true;
    grid[gridsize/2][gridsize/2+1] = true;
    grid[gridsize/2][gridsize/2-1] = true;
    grid[gridsize/2+1][gridsize/2+1] = true;

    while (true){
        //The following copies our grid.

        Display(grid);     //This is our display.
        liveOrDie(grid); //calculate if it lives or dies.
        system("CLS");
    }
}

Two major suggestions:

First, let's try speeding everything up by taking advantage of the nature of Conway's Game of Life and the way C++ handles pointers. When you evaluate Conway's Game of Life, it's a two part process.  First you copy all of the entries into a new array, then you do your computation referring to that new array, and update the original one. This process takes \$ O \left( n^{2} \right) \$, and involves a major memory copy; for small sizes that shouldn't be a problem, at larger sizes, the cost incurred by the memory copy will become non trivial, so let's reformulate the design a little:

Conway's Game of Life itself is an application of cellular automata, where the state G of the grid at time t is a function of of the state at a time t-1. More specifically, it would be of a form like this: G(t)=R(G(t-1)) where R() is some rule function determining which cells live and which cells die. This direct dependence offers us an interesting solution to the memory copying conundrum--what if we store two grids, one to represent G(t) and one to represent G(t-1)? Then we can get away with reading G(t-1), applying our rule and updating G(t). This however brings us back to the first question--how do we update G(t-1) then? do we just copy G(t)'s memory? C++ offers us a more convenient approach actually, we can swap the pointers instead: as G(t) is fully described by G(t-1) if we simply swap the pointers for the two arrays, so the pointer for G(t-1) refers to G(t)'s memory region, and G(t) refers to G(t-1)'s memory region, then we can apply the update rule, update G(t) to be G(t+1), overwriting the old memory used to store G(t-1), which prevents us from needing to copy the grids ever, which will significantly speed up the simulation in case n>500 in my experience.

The second comment is on code abstraction, cellular automata as a whole is a good place to explore this, because it's such a general field. It's not necessary to make your Conway's Game of Life code work, but it will make it easier if you come up with interesting variations you want to test. Right now you have the update rule, R() represented as a single function, liveOrDie, this can be re-factored into several smaller tasks however, which has the advantage of making the system more modular and easier to tweak. How then can we break down this rule into smaller, more modular components? Let us start by listing the actual procedure performed by the update function:

Iterate over all of the cells and update them
To update a cell, look up it's neighbors (in Conway's Game of Life we use the Moore neighborhood)
Look at a cells neighbors and decide whether it will live or die (apply the rule to a cell)
Update the contents of a cell according to it's rule

This list of tasks lends itself to defining three separate functions

void update(G(t),G(t-1)), which will perform the updating itself
int neighbors(G,x,y), which will return the number of neighbors of a cell indexed at (x,y)
bool rule(neighbors,lod,x,y) which will look at a specific cell and decide whether it lives or dies (lod is the state of the cell, live or dead)

The basic outline could then be something like this:

update(G(t),G(t-1)){
 for(x: 1..size)
  for(y: 1..size){
    G(t-1)[x+y*size] = rule(neighbors(G(t),x,y),G(t)[x+y*size],x,y)
  }
 swap = G(t-1)
 G(t-1) = G(t)
 G(t) = swap
}

The advantage to this model is if you want to change the function of the rule, or the neighborhood, say apply periodic bounding, you can easily change only the definition related to that part of the code. Hope that helps.


Editing Javascript and rendering HTML in one window I've been trying to learn the basics of Javascript, so this afternoon I put together a small JavaFX application that has a raw text area on the left, and an HTML rendering on the right:

public class Fifty extends Application {
    private String filePath = null;
    private TextArea text;
    public void init() throws Exception {
        super.init();
        Parameters parameters = getParameters();
        List<String> unnamedParams = parameters.getUnnamed();
        if (unnamedParams.size() > 0) {
            filePath = unnamedParams.get(0);
        }
    }
    public void start(Stage stage) throws Exception {
        SplitPane splitPane = new SplitPane();
        text = new TextArea();
        final WebView web = new WebView();
        try {
            text.setText(readFile(filePath, Charset.defaultCharset()));
            web.getEngine().loadContent(text.getText());
        } catch (Exception e) {
            alertException(e);
        }
        text.setStyle("-fx-font-family: monospace");
        text.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(final ObservableValue<? extends String> observable,
                    final String oldValue, final String newValue) {
                web.getEngine().loadContent(text.getText());
            }
        });
        splitPane.getItems().addAll(text, web);
        Scene scene = new Scene(splitPane);
        scene.setFill(Color.RED);
        stage.setScene(scene);
        stage.setTitle("eleven-fifty: because i'm bad at naming things");
        stage.show();
    }
    public void stop() {
        try {
            saveFile(filePath, text.getText());
        } catch (Exception ex) {
            ex.printStackTrace();
            System.err.println("file not saved!");
        }
    }
    static String readFile(String path, Charset encoding) throws IOException {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return new String(encoded, encoding);
    }
    static void saveFile(String path, String text) throws Exception {
        PrintWriter out = new PrintWriter(path);
        out.print(text);
        out.close();
    }
    static void alert(String title, String body) {
        Alert alert = new Alert(AlertType.INFORMATION);
    alert.setTitle(title);
    alert.setContentText(body);
    alert.show();
    }
    static void alertException(Exception e) {
        StackTraceElement[] trace = e.getStackTrace();
        int i = 0;
        StringBuilder traceRes = new StringBuilder();
        traceRes.append(String.format("%s\n", e.toString()));
        for (StackTraceElement element: trace) {
            traceRes.append(String.format("%s\n", element.toString()));
            if (++i > 10) break;
        }
        alert("Exception", traceRes.toString());
    }
}

Finally, a script to automatically launch the .jar file:

java -jar eleven-fifty.jar %1
pause

How can this simple application be improved?

Style review

Added newlines between methods – Your code looks mighty cramped, and this makes it harder to read, which in turn makes it harder to understand. This also applies to places within code. When programming in Python the guidelines says to use two new lines between methods, and if needed one new line in code. That is good advice
Keep good indentation and consistent brace style – It looks like you mostly have good indentation, and consistent brace styles. I like that (mostly) you're using braces around even one line blocks. That's good!

There are a little slip up in the alert() method, and similar a hidden break in the alertException()
Add comments – You should have some comments in the code indicating what the different parts do, and when they do it. Not what the code does, but why it does is that way

Code suggestions

To me it is not clear when you execute the new code, of if it is continously being executed. I would not continuosly execute it, and rather have some buttons to start and stop execution.
I would also have a (scrolling) panel for the javascript console output, if possible. Lots of messages will be made to the console, and otherwise be hidden
In due time you'll also need to have the ability to have the possibility to edit the html section, so maybe you need to have a button or panel to allow editing that as well
In other words, I think I would divide the left panel into javascript and raw html, whilst the right panel is divided into the html output and javascript console. And some buttons or menu somewhere. If possible in JavaFX the divider in either panel should be movable to accomodate for whatever part is the longer, and of course they should have scrollbar if text extends the panel


Automate the Boring Stuff with Python 2nd Edition - Sandwich Maker Practice Project I am in learning process, even though its a very easy project, I still want experts to please review it and share the improvement that can be done, if anyone wants to use other modules to shorten the code then you can also use them, I already thank you to the people who wants to spend their precious time for this. other beginners will also find it helpful.
import pyinputplus as pyp

menu = True

# price of all ingredients
prices = {'wheat': 2, 'white': 1, 'sour dough': 3, 'chicken': 2, 'turkey': 3, 'ham': 2, 'tofu': 1,
          'cheddar': 1, 'swiss': 2, 'mozzarella': 3, 'mayo': 1, 'mustard': 1, 'lettuce': 1,
          'ketchup': 1}
while menu:
    # options to select bread, protein, cheese with inputMenu() method
    bread = pyp.inputMenu(['wheat', 'white', 'sour dough'],
                          prompt='Please select the type of bread you want for your sandwich: \n',
                          numbered=True)

    protein = pyp.inputMenu(['chicken', 'Turkey', 'Ham', 'Tofu'],
                            prompt='Which type of protein you would like: \n',
                            numbered=True)

    cheese = pyp.inputYesNo('Do you want Cheese in your sandwich?(Y/N)\n')
    cheese_type = ''
    if cheese == 'yes':
        cheese_type = pyp.inputMenu(['cheddar', 'swiss', 'mozzarella'], numbered=True)

    # using inputYesNo() for single ingredients with no further types
    mayo = pyp.inputYesNo('Do you want mayo?(Y/N) \n')
    mustard = pyp.inputYesNo('Do you want mustard?(Y/N) \n')
    lettuce = pyp.inputYesNo('Do you want lettuce?(Y/N) \n')
    ketchup = pyp.inputYesNo('Do you want tomato ketchup?(Y/N) \n')

    # using inputInt() and blockRegexes that do not allow negative integer, float or 0
    sandwichQT = pyp.inputInt('How much sandwiches you would like to order?\n',
                              blockRegexes=['[0|-|.]'])

    total_amount = 0

    # using for loop to print items, prices and adding their amount to total_amount variable
    for item, price in prices.items():
        if bread == item:
            print(f'Your sandwich ingredients and prices are as follows: \n'
                  f'{item}= {price}')
            total_amount += price

        if protein == item:
            print(f'{item}= {price}')
            total_amount += price

        if cheese_type == item:
            print(f'{item}= {price}')
            total_amount += price

    # for items that have yes and no values stored and also adding their amount to total
    if mayo == 'yes':
        print(f"mayo = {prices['mayo']}")
        total_amount += prices['mayo']

    if mustard == 'yes':
        print(f"mustard = {prices['mustard']}")
        total_amount += prices['mustard']

    if lettuce == 'yes':
        print(f"lettuce = {prices['lettuce']}")
        total_amount += prices['lettuce']

    if ketchup == 'yes':
        print(f"ketchup = {prices['ketchup']}")
        total_amount += prices['ketchup']

    # at the end printing total amount and how much sandwiches have been ordered
    print(f"sandwich cost x sandwich Qt ordered = {total_amount}x{sandwichQT} = "
          f"{total_amount*sandwichQT}")

    # confirming if the user need to reorder or user wants to confirm the order by simple yes/no
    # if user confirm by typing yes or y then menu will become false and while loop will terminate
    order_confirm = pyp.inputYesNo('Please confirm your order: (Y/N)\n')
    if order_confirm == 'yes':
        print('Please take your order number from the machine and you will be notified when '
              'its ready')
        menu = False

while True
First of all, using "flag" variables is not customary in Python. Instead of using a boolean variable to control a while loop, you can just do while True: ... break.
Avoiding many ifs
You might notice the repeating structure of:
print(f'{item}= {price}')
total_amount += price

under every if. This is because your logic is reversed. You are currently iterating over ALL possible ingredients and checking if you need them. But there might be many that are not in use. It makes more sense to create a list of ingredients in use and then just take their price in a loop. This will require changing how you save your sauces. Instead of saving them as 'yes', we will save them with their name - to match with the prices dict keys.
So we will create a list of ingredients, and add the sauces as well:
if pyp.inputYesNo('Do you want mayo?(Y/N) \n') == 'yes':
    ingredients.append('mayo')

And now the printing loop will be if-free:
print(f'Your sandwich ingredients and prices are as follows: \n')
for item in ingredients:
    price = prices[item]
    print(f'{item}= {price}')
    total_amount += price

Full Code
import pyinputplus as pyp

# price of all ingredients
prices = {'wheat': 2, 'white': 1, 'sour dough': 3, 'chicken': 2, 'turkey': 3, 'ham': 2, 'tofu': 1,
          'cheddar': 1, 'swiss': 2, 'mozzarella': 3, 'mayo': 1, 'mustard': 1, 'lettuce': 1,
          'ketchup': 1}

while True:
    ingredients = []
    # options to select bread, protein, cheese with inputMenu() method
    ingredients.append(pyp.inputMenu(['wheat', 'white', 'sour dough'],
                          prompt='Please select the type of bread you want for your sandwich: \n',
                          numbered=True))

    ingredients.append(pyp.inputMenu(['chicken', 'Turkey', 'Ham', 'Tofu'],
                            prompt='Which type of protein you would like: \n',
                            numbered=True))

    if pyp.inputYesNo('Do you want Cheese in your sandwich?(Y/N)\n')== 'yes':
        ingredients.append(pyp.inputMenu(['cheddar', 'swiss', 'mozzarella'], numbered=True))

    # using inputYesNo() for single ingredients with no further types
    if pyp.inputYesNo('Do you want mayo?(Y/N) \n') == 'yes':
        ingredients.append('mayo')
    if pyp.inputYesNo('Do you want mustard?(Y/N) \n') == 'yes':
        ingredients.append('mustard')
    if pyp.inputYesNo('Do you want lettuce?(Y/N) \n') == 'yes':
        ingredients.append('lettuce')
    if pyp.inputYesNo('Do you want tomato ketchup?(Y/N) \n') == 'yes':
        ingredients.append('ketchup')

    # using inputInt() and blockRegexes that do not allow negative integer, float or 0
    sandwichQT = pyp.inputInt('How much sandwiches you would like to order?\n',
                              blockRegexes=['[0|-|.]'])

    total_amount = 0
    # using for loop to print items, prices and adding their amount to total_amount variable
    print(f'Your sandwich ingredients and prices are as follows: \n')
    for item in ingredients:
        price = prices[item]
        print(f'{item}= {price}')
        total_amount += price

    # at the end printing total amount and how much sandwiches have been ordered
    print(f"sandwich cost x sandwich Qt ordered = {total_amount}x{sandwichQT} = "
          f"{total_amount*sandwichQT}")

    # confirming if the user need to reorder or user wants to confirm the order by simple yes/no
    # if user confirm by typing yes or y then menu will become false and while loop will terminate
    if pyp.inputYesNo('Please confirm your order: (Y/N)\n')== 'yes':
        print('Please take your order number from the machine and you will be notified when '
              'its ready')
        break


Pruning unwanted columns from a selected row I've got this little module that returns basic user data required for a web app that's extracted from a large number of columns per row. I was asked to replace the small, column specific select statement I'd prepared with a stored procedure that returns the entire row. This moves column pruning into the server.

I've modified my original function to work as expected with the code below, but it feels like I could be doing better with Array.find((e) => {})

sqlRequest.on('row', function(columns) {
  response = {};
  const keys = ['id', 'fn', 'ln', 'ctr'];

  columns.forEach(function (c) {
    let key = String(c.metadata.colName).toLowerCase();
    if (keys.find((e) => { return key === e})) {
      let value = String(c.value).charAt(0).toUpperCase() + String(c.value).slice(1).toLowerCase();
      response[key] = value;
    }
  });
});

response is an implicit global, which is a no-no. Now, I imagine it is declared in a wider scope already, but it's still disconcerting to see a function have such crass side-effects. It just overwrites the entire response variable (but if other functions have their own references to the previous value, they won't know about the overwriting).
I'd use a callback or a promise to "return" a fresh object, and let some other piece of code deal with whether to redefine response.
Your find call can be reduced to keys.find(e => key === e) - you don't need braces or return for one-line statements, or parentheses around a single parameter. But the more conventional way to do things is using indexOf. I.e.

if(keys.indexOf(e) !== -1)


Auctioneer calling "Going once… going twice… sold!" I feel like the if-else combination isn't the most optimal and I'm also not sure if I need a loop

var Auktionator = function(){
var rennt = false;

this.versteigern = function(objekt){
        if(rennt === false){
        for(var i = 1; i<=4; i++){
            if(i === 1){
                setTimeout(function(){console.log(objekt + " zum ersten")},1000*i);
            }
            else if(i === 2){
                setTimeout(function(){console.log(objekt + " zum zweiten")},1000*i);
            }
            else if(i === 3){
                setTimeout(function(){console.log(objekt + " zum dritten")},1000*i);
            }
            else if(i === 4){
            setTimeout(function(){console.log(objekt + " verkauft!")},1000*i);

        }
         rennt = true;
    }
    }
}
}

Definetely not. The loop is useless (and un-optimizing) here.

As far as I can see, the index i is only used to calculate some constants' values. Realise that your original loop has the same effect than dropping off the loop and the ifs clauses, and hard-code the values computed from i:

setTimeout(function(){console.log(objekt + " zum ersten")},1000);
setTimeout(function(){console.log(objekt + " zum zweiten")},2000);
setTimeout(function(){console.log(objekt + " zum dritten")},3000);
setTimeout(function(){console.log(objekt + " verkauft!")},4000);

Or, another valid alternative could be taking advantage of the resembling of the actions and generalize them by using data:

var messages=[" zum ersten", " zum zweiten", " zum dritten", " verkauft!"];

This would be more comprehensive and flexible, since it allows to add more messages without changing the logic a little.

Update

I recommend RobH's answer, which is based upon arrays, and works fine.


Calculating sum of squares in C I wrote some program in C language. I have to calculate sum of squares. My book suggested me to use loops but I chose more efficient way by using formula:

$$1^2+2^2+\cdots+n^2=\frac{n\left(n+1\right)\left(2n+1\right)}{6}$$

Original code from listing 5.13:

#include <stdio.h>

int main(void) {
    int licznik, suma;

    licznik = 0;
    suma = 0;
    while (licznik++ < 20)
        suma = suma + licznik;
    printf("suma = %d\n", suma);
    return 0;
}

Finally, this is my code:

#include <stdio.h>

int main(void) {
    int zakres;
    printf("Podaj zakres przeprowadzanych obliczen:\n");
    scanf("%i", &zakres);
    printf("suma kwadratow = %d\n", (((zakres * (zakres + 1)) * (2 * zakres + 1)) / 6));
    return 0;
}

What do you think about this solution? Is it more efficient than loops?

Well, I can't say much about your naming, as I cannot read it. For a wider audience than a purely local team - and probably even then - consider switching to english.

What I can tell is that you are very generous with parentheses. Using them everywhere actually reduces readability, you know?

Next, congratulations for working smarter instead of harder, it really pays in speed.
Though there is a down-side to your implementation of the modified algorithm: It encounters Undefined Behavior due to integer-overflow slightly before the brute-force-one does (by about five to six numbers). Why are you using signed arithmetic anyway?

And then you assume the programs input is always well-formed. You know scanf() can fail? So, test the return-value.


Check if element is a member of all sets in Scheme Here is a function that checks whether an alement a is a member of every set in list l-set.

I don't like the fact that it returns #t for an empty list of sets. What would be a clean fix to this problem?

(define memberall
  (lambda (a l-set)
    (cond
      ((null? l-set) #t)
      ((not (member a (car l-set))) #f)
      (else (memberall a (cdr l-set))))))

so this is not a question about code, but about conventions. Usually to say "a condition holds for all elements of a set" is the same as "there's no such element in the set that the condition doesn't hold for it". Which there clearly is no such element, in an empty set. So by convention all such "all-are-true" predicates hold for an empty set.

But if you want your function to return #f in such a case, just add simple entry check for this, and convert what you have right now into an inner (nested) definition:

(define memberall
  (lambda (a l-set)
    (and (not (null? l-set))
      (letrec ((alltrue
                 (lambda (l-set)
                   (cond
                     ((null? l-set) #t)
                     ((not (member a (car l-set))) #f)
                     (else (alltrue (cdr l-set)))))))
        (alltrue l-set)))))

Or with named let:

(define memberall
  (lambda (a l-set)
    (and (not (null? l-set))
      (let alltrue ((l-set l-set))
        (cond
          ((null? l-set) #t)
          ((not (member a (car l-set))) #f)
          (else (alltrue (cdr l-set))))))))


Ajax request URL with the Google Maps API I am making an HTTP request with the Google Maps API and I have to pass in parameters (adresses/coordinates):

 $.ajax({
        url : 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + $("#origin").val() + '&destinations=' + $("#destinations").val() +'&mode=driving&key=AIzaSyASanevdiCI4t1h8LMf5FgWHMD52K3QeB0',
        type: 'GET',
        success : function(data){
        //My code
        }
    });

I was wondering if there was any better cleaner way to do this. I know string concatenation is an option, but I want to know if I have any other options. I just feel like I'm doing this wrong.

You may want to put your query string into the data property of your XHR request in order to clean up your request as well.

$.ajax({
  url: "https://maps.googleapis.com/maps/api/distancematrix/json",
  type: "GET",
  data: {
    origins: $("#origin").val(),
    destination: $("#destinations").val(),
    mode: "driving",
    key: "AIzaSyASanevdiCI4t1h8LMf5FgWHMD52K3QeB0"
  },
  success: function(data) {
    console.log(data);
  }
});


Java executing rSync shell command with progress display I basically want to write a simple GUI program to sync to directories using the rsync command. The core part of the code is below. My main question is, do I need to have the waitFor method included? At present, I have left it out, because I would like to show the user the --progress responses as it would in terminal, not wait until the end. Is this a bad idea?

public void executeCommand(String src, String dest) {
        System.out.println("Starting shell");
    Process p;
    try {
                System.out.println("Creating process...");
        p = Runtime.getRuntime().exec("rsync --progress -va "+src +" "+ dest );
        //p.waitFor(); <- is this important?
                    System.out.println("Creating reader...");
        BufferedReader reader =
                        new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String line = "";
                    System.out.println("Starting sync...");
        while ((line = reader.readLine())!= null) {
                            System.out.println(line);
                            textAreaAppend(line);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

   public void textAreaAppend(String line){
    textArea.append(line +"\n");
}

Process.waitFor will terminate the current thread until the process is terminated. Thus, at the place where you commented it out, it does not make any sense at all. You might consider putting a p.waitFor() after the loop, as to continue with your program only when the process has terminated.

Apart from that, sorry to say so, your code is a mess. You use a very outdated method to start the process, you do not read stderr (which may lead to blocking conditions on stdout), code format is all over the place, p is declared outside the try block without any reason, exception handling is not present.

To at least cover the basic necessities of reading both stdin and stderr, you should go for process builder and redirect stderr to stdout:

    ProcessBuilder builder = new ProcessBuilder(Arrays.asList("rsync", "--progress", "-va", src, dest));
    builder.redirectErrorStream(true);
    builder.redirectOutput(ProcessBuilder.Redirect.PIPE);
    Process p = builder.start();


Caesar Shift in Haskell I started learning Haskell a couple of days ago and decided to build a Caesar shift in it.

import Data.Char

shift_str :: Int -> ([Char] -> [Char])
shift_str num
         | num > 1 = \str -> shift_str_forwards (shift_str (num-1) str)
         | num == 1 = shift_str_forwards
         | num == 0 = no_shift
         | num == -1 = shift_str_backwards
         | num < -1 = \str -> shift_str_backwards (shift_str (num+1) str)

no_shift :: [Char] -> [Char]
no_shift str = str

shift_str_forwards :: [Char] -> [Char]
shift_str_forwards str = map shift_forwards str

shift_str_backwards :: [Char] -> [Char]
shift_str_backwards str = map shift_backwards str

shift_forwards :: Char -> Char
shift_forwards char
             | char == 'z' = 'a'
             | otherwise = chr (1 + ord char)

shift_backwards :: Char -> Char
shift_backwards char
              | char == 'a' = 'z'
              | otherwise = chr (ord char - 1)

However, this seems far too complex to be the right way of doing it. Any advice?

First of all, it's great that you use type signatures. However, your using snake_case, whereas Haskell usually uses camelCase for functions, e.g. no_shift should be called noShift.

Next, your shift functions for characters can be simplified by both pattern matching and succ and pred:

shiftForwards :: Char -> Char
shiftForwards 'z' = 'a'
shiftForwards c   = succ c

shiftBackwards :: Char -> Char
shiftBackwards 'a' = 'z'
shiftBackwards c   = pred c

Next, your "global" function gets easier if you use str as an argument and not in a lambda.

shiftStr :: Int -> [Char] -> [Char]
shiftStr num str
       | num > 0  = shiftStr (num - 1) (map shiftForwards str)
       | num < 0  = shiftStr (num + 1) (map shiftBackwards str)
       | num == 0 = str

The special cases for num == 1 and num == -1 aren't necessary, since shiftStr will return immediately if the subsequent call uses num = 0.


Check existence of item in collection Checking whether an item exist in a collection isn't straightforward in VBA, it requires error checking and during error handling we need to clear the error and also resume code to be able to correctly manage the next error.

In my codes I generally use this structure, is it a good practice?

    With MyWorkBook
        On Error GoTo NoItem
        With .Sheets(SheetName)
            ' do stuff here if sheet exists
        End With
NoItem:
        If False Then
            Err.Clear
            ' code to do if sheet doesn't exist (e.g. add a new one)
            Resume NoItem
        End If
        On Error GoTo 0 ' (or specify another label for error handling)
        ' continue macro ...
    End With

Don't make errors a part of your program flow
If an error doesn't cause you to prematurely end your Sub/Function, then it should be handled less severely, or your program needs restructuring. I also caution against using GOTOs. They are sometimes necessary, but they have the potential to cause far more problems than they solve.
This is the only situation in which I regularly use GOTOs in VBA:
    Public Sub DoThing()

        On Error GoTo CleanFail

        ...

        ...

        ...

CleanExit:

        '/ Clean Up
        Exit Sub

CleanFail:

        '/ Error Handling
        '/ Error handling
        '/ Error handling
        Resume CleanExit

    End Sub

Handling Conditions
If you are going to continue your macro anyway, but want to avoid running some code if a condition fails then why not just:
[Check Condition]
If [condition] Then
    DoThing
End If

In the specific case of the Sheets() Collection, you have a number of options.

Option #1: Write a utility function to do the checking for you
    Public Function GetSheet(ByRef targetBook As Workbook, ByVal sheetName As String) As Worksheet
        '/ Tries to return the sheet object.
        '/ If the sheet does not exist, return Nothing

        Dim targetSheet As Worksheet
        On Error GoTo CleanFail
            Set targetSheet = targetBook.Worksheets(sheetName)
        On Error GoTo 0

CleanExit:
        Set GetSheet = targetSheet
        Exit Function

CleanFail:
        On Error GoTo 0
        Err.Clear
        Set targetSheet = Nothing
        Resume CleanExit

    End Function

And now your code can be structured like so:
    Dim targetSheet As Worksheet
    Set targetSheet = GetSheet(ThisWorkbook, sheetName)
    If Not targetSheet Is Nothing Then
        ' do stuff here (don't do it if SheetName doesn't exist)
    End If

Much cleaner.

Option #2: Use a data structure that supports .Exists()
For VBA, this would be a Dictionary. You'll need to set a reference to the Microsoft Scripting Runtime library in Tools --> References. Then do the following:
    Dim sheetnames As Dictionary
    Set sheetnames = New Dictionary

    Dim sheetName As String
    Dim sheetObject As Worksheet
    For Each sheetObject In ThisWorkbook.Sheets()
        sheetName = sheetObject.Name
        sheetnames.Add sheetName, sheetName
    Next sheetObject

    If sheetnames.Exists("Some sheet name") Then
        ' do stuff here (don't do it if SheetName doesn't exist)
    End If

Option #3: Restructure your program to make the check redundant
I don't know if this is a good idea for your code. I'd have to know more about its' wider purpose, structure and context, but it's always worth thinking about.


Split a string into chunks of the same length Inspired by this question in chat

  Is there an easy way in .NET to split a string into an array by pulling chunks of the text in. I.e. I have an 18 character string I would like in 3 6-character pieces.

I thought that ain't be that hard. I would like to get any thoughts and improvements you can think of.

public static string[] Split(this string value, int desiredLength, bool strict = false)
{

    EnsureValid(value, desiredLength, strict);

    if (value.Length == 0) { return new string[0]; }

    int numberOfItems = value.Length / desiredLength;

    int remaining = (value.Length > numberOfItems * desiredLength) ? 1 : 0;

    IList<string> splitted = new List<string>(numberOfItems + remaining);

    for (int i = 0; i < numberOfItems; i++)
    {
        splitted.Add(value.Substring(i * desiredLength, desiredLength));
    }

    if (remaining != 0)
    {
        splitted.Add(value.Substring(numberOfItems * desiredLength));
    }

    return splitted.ToArray();
}

private static void EnsureValid(string value, int desiredLength, bool strict)
{
    if (value == null) { throw new ArgumentNullException(nameof(value)); }

    if (value.Length == 0 && desiredLength != 0)
    {
        throw new ArgumentException($"The passed {nameof(value)} may not be empty if the {nameof(desiredLength)} <> 0");
    }

    if (value.Length != 0 && desiredLength < 1) { throw new ArgumentException($"The value of {nameof(desiredLength)} needs to be > 0"); }

    if (strict && (value.Length % desiredLength != 0))
    {
        throw new ArgumentException($"The passed {nameof(value)}'s length can't be split by the {nameof(desiredLength)}");
    }
}

I know the tests aren't complete and the naming could be better, like the missing of a test if the passed in value == null, but here they are for review as well

[TestMethod()]
public void SplitTest()
{
    string input = "123456";
    string[] expected = new string[] { "123", "456" };
    string[] actual = input.Split(3);

    CollectionAssert.AreEqual(expected, actual);
}

[TestMethod()]
public void SplitTestNotEqual()
{
    string input = "12345";
    string[] expected = new string[] { "123", "45" };
    string[] actual = input.Split(3);

    CollectionAssert.AreEqual(expected, actual);
}

[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void SplitTestDesiredlengthIsZero()
{
    string input = "12345";
    string[] actual = input.Split(0);
}

[TestMethod()]
public void SplitTestDesiredlengthIsZeroWithEmptyString()
{
    string input = "";
    string[] expected = new string[0];
    string[] actual = input.Split(0);

    CollectionAssert.AreEqual(expected, actual);
}

[TestMethod()][ExpectedException(typeof(ArgumentException))]
public void SplitTestWillThrowBecauseOfStrict()
{
    string input = "12345";
    string[] actual = input.Split(3,true);
}

Algorithm can't be improved (or at least I see no reason to do it, ignoring a minor micro-optimization about List<string> which usage, however, helps to keep code much more readable) and code is pretty clear, however:

You're returning string[] but consumers may not need it. List.ToArray() won't simply return internal array (because its capacity != size). It implies you will make another (relatively expansive) copy. I'd simply return IEnumerable<string>: if consumer needs an array it can call ToArray() LINQ extension method (which will/may check for underlying implementation), it he doesn't need an array then you saved an Array.Copy().
You're partitioning over Char but String is UTF-16 encoded then you may produce broken strings in, at least, three cases:

One character is encoded with more than one code unit. Unicode code point for that character is encoded as two UTF-16 code units, each code unit may end up in two different slices (and both strings will be invalid).
One character is composed by more than one code point. You're dealing with a character made by two separate Unicode code points (for example Han character ).
One character has combining characters or modifiers. This is more common than you may think: for example Unicode combining character like U+0300 COMBINING GRAVE ACCENT used to build à and Unicode modifiers such as U+02BC MODIFIER LETTER APOSTROPHE.

Definition of character for a programming language and for a human being are pretty different, for example in Czech Slovak (thanks svick to correct me about this) dž is a single character however it's made by 2/3 Unicode code points which are in this case also 2/3 UTF-16 code units then "dž".Length > 1. More about this and other cultural issues on this Stack Overflow post.
Ligatures exist. Assuming one ligature is one code point (and also assuming it's encoded as one code unit) then you will treat it as a single glyph however it represents two characters. What to do in this case? In general definition of character may be pretty vague because it has a different meaning according to discipline where this word is used. You can't (probably) handle everything correctly but you should set some constraints and document code behavior.

To address all these issues (also third point if current culture is correctly set but not last one) I'd use:

string[] characters = StringInfo.GetTextElementEnumerator(value).ToArray();

And I'd perform subsequent processing over characters array instead of value. Note that this may lead to strings made of different length but with the same number of characters. For example (when performance are not an issue):

public static IEnumerable<string> Split(this string value, int desiredLength)
{
    var characters = StringInfo.GetTextElementEnumerator(value);
    while (characters.MoveNext())
        yield return String.Concat(Take(characters, desiredLength));
}

private static IEnumerable<string> Take(TextElementEnumerator enumerator, int count)
{
    for (int i = 0; i < count; ++i)
    {
        yield return (string)enumerator.Current;

        if (!enumerator.MoveNext())
            yield break;
    }
}

To do not reinvent the wheel you may just create your own AsEnumerable() extension method to walk through an existing enumerator:

public static IEnumerable<T> AsEnumerable<T>(this IEnumerator enumerator)
{
    while (enumerator.MoveNext())
        yield return (T)enumerator.Current;
}

Your code will be then simplified to:

public static IEnumerable<string> Split(this string value, int desiredLength)
{
    var characters = StringInfo.GetTextElementEnumerator(value);
    do
    {
        yield return String.Concat(characters.AsEnumerable<string>().Take(desiredLength));
    } while (characters.MoveNext());
}

If you don't need string[] return type you may live with IEnumerable<string> and use LINQ ToArray() when/if required (code is slightly simplified for demonstrative purposes, in real world you will need some error checking).

If you're processing US ASCII text and you won't need to partition horse d'œvre then you can simply ignore these issues.


Allowing developers to quickly create image hover effects I've created a simple jQuery plugin to allow developers to quickly create image hover effects with very simple markup. I also created an option to automatically create the mouseover or mouseout versions of the image via TimThumb.

Here is a link. for more information and a demo.

(function($){
$.fn.hovr = function(options) {

    // Default Options
    var defaults = {
        speed:           'normal',
        animateOver:     {'opacity': '0'},
        animateOut:      {'opacity': '1'},
        timThumb:        false,
        timThumbInverse: false,
        timThumbPath:    'images/img.php',
        timThumbParams:  'f=2'
        //http://www.binarymoon.co.uk/2012/02/complete-timthumb-parameters-guide/
    };
    var options = $.extend({}, defaults, options);

    // Create Images
    if (options.timThumb) {
        this.each(function() {
            var strOrig = $(this).prop('src');
            var strNew  = options.timThumbPath +
                '?src=' + strOrig +
                '&w=' + $(this).prop('width') +
                '&h=' + $(this).prop('height') +
                '&' + options.timThumbParams;

            if (options.timThumbInverse) {
                $(this)
                    .prop('src', strOrig)
                    .attr('data-hovr', strNew);
            }
            else {
                $(this)
                    .prop('src', strNew)
                    .attr('data-hovr', strOrig);
            }
        });
    }

    // Create Rollovers
    return this.each(function() {
        $(this).hover(
            function() {
                $(this).stop().animate(options.animateOver, options.speed);
            },
            function() {
                $(this).stop().animate(options.animateOut, options.speed);
            }
        ).each(function() {
            var intWidth  = ($(this).attr('width'))  ? $(this).attr('width')  : $(this).prop('width');
            var intHeight = ($(this).attr('height')) ? $(this).attr('height') : $(this).prop('height');
            var strAlign  = ($(this).attr('align'))  ? $(this).attr('align')  : '';
            var strClass  = ($(this).attr('class'))  ? $(this).attr('class')  : '';
            var strStyle  = ($(this).attr('style'))  ? $(this).attr('style')  : '';

            $(this).wrap('

');

            $(this).before($(this).clone(true))
                .attr('style', 'position:absolute; left:auto; top:auto;')
                .prop('src', $(this).attr('data-hovr'))
                .removeAttr('data-hovr')
                .removeAttr('class');

            $(this).prev('img')
                .attr('style', 'position:absolute; left:auto; top:auto; z-index:10;')
                .removeAttr('data-hovr')
                .removeAttr('class');
        });
    });

};
})(jQuery);

As a rule of thumb, when you use a jQuery selection more than once, you should cache its value. When you do $(".someElement"), jQuery now has to go find that element in the DOM, wrap it in the jQuery object and return it. If you save what it returns, then you only do the search once - not every time you use it.

The hard part is caching this. This is relative to where you are in the code, function, callback, etc. and changes to provide context. For example:

var Object = {
    init: function() {
        //this in here references Object
        //You could call this function elsewhere by doing: "this.init();"
    },

    bindEvents: function() {
        $(".someElement").hover(function() {
            //This is a callback function
            //In here "this" refers to the element your .hover() was called on - ".someElement"
        });

        //However, outside the callback, "this" now refers to Object again

        $(".someOtherElement").each(function(){
            //This is another callback
            //Here "this" refers to the element in question
        });
    }
}

The reason the plugin is breaking when you cache it is because you have to cache it at each point the reference changes. Watch this next example:

var Object = {
    init: function() {
        //Here "this" refers to Object
        //You don't need to cache this here because the Object is already saved in a variable
    },

    bindEvents: function() {
        $(".someElement").hover(function() {
            //In here however, the reference changed
            //In here "this" refers to the element your ".hover()" was called on. ie.: ".someElement"
            //You would cache it in here
        });

        //However, outside the callback, "this" now refers to Object again so you don't need to cache it

        $(".someOtherElement").each(function(){
            //This is another callback
            //The reference has changed again, so now we cache it again
        });
    }
}

From what I could understand from reading your plugin, I've cached your this references for you. I didn't change anything else except for .removeAttr() calls at the end. You can use a space and put in several attributes to be removed at once.

Anyways here's your code:

(function($){
$.fn.hovr = function(options) {

    // Default Options
    var defaults = {
        speed:           'normal',
        animateOver:     {'opacity': '0'},
        animateOut:      {'opacity': '1'},
        timThumb:        false,
        timThumbInverse: false,
        timThumbPath:    'images/img.php',
        timThumbParams:  'f=2'
        //http://www.binarymoon.co.uk/2012/02/complete-timthumb-parameters-guide/
    };
    var options = $.extend({}, defaults, options);

    // Create Images
    if (options.timThumb) {
        this.each(function() {
            var $this = $(this),
                strOrig = $this.prop('src'),
                strNew  = options.timThumbPath +
                '?src=' + strOrig +
                '&w=' + $this.prop('width') +
                '&h=' + $this.prop('height') +
                '&' + options.timThumbParams;

            if (options.timThumbInverse) {
                $this
                    .prop('src', strOrig)
                    .attr('data-hovr', strNew);
            }
            else {
                $this
                    .prop('src', strNew)
                    .attr('data-hovr', strOrig);
            }
        });
    }

    // Create Rollovers
    return this.each(function() {
        $(this).hover(
            function() {
                $(this).stop().animate(options.animateOver, options.speed);
            },
            function() {
                $(this).stop().animate(options.animateOut, options.speed);
            }
        ).each(function() {
            var $this = $(this),
                intWidth  = ($this.attr('width'))  ? $this.attr('width')  : $this.prop('width'),
                intHeight = ($this.attr('height')) ? $this.attr('height') : $this.prop('height'),
                strAlign  = ($this.attr('align'))  ? $this.attr('align')  : '',
                strClass  = ($this.attr('class'))  ? $this.attr('class')  : '',
                strStyle  = ($this.attr('style'))  ? $this.attr('style')  : '';

            $this.wrap('

');

            $this.before($this.clone(true))
                .attr('style', 'position:absolute; left:auto; top:auto;')
                .prop('src', $this.attr('data-hovr'))
                .removeAttr('data-hovr class');

            $this.prev('img')
                .attr('style', 'position:absolute; left:auto; top:auto; z-index:10;')
                .removeAttr('data-hovr class');
        });
    });
};
})(jQuery);


Simple vector calculator I am fairly new to Python and programming. I created this simple calculator inspired by my physics class. However, I feel this code could have been done more efficiently. Is there any advice for efficiency?

import math

#calculates vector x component
#x = side length y = angle

def fxcomponent(x, y):
  number = x
  y = math.cos(math.radians(y))
  result = number * y
  return result

#calculates vector y component
def fycomponent(x, angle):
  number = x
  angle = math.sin(math.radians(angle))
  result = number * angle
  return result

prompt = 'Welcome to my Python vector components calculator!'
prompt += '\nPlease select what you wish to find: \n-type x for x-component
prompt += '\n-type y for y-component'\n-type quit to end program'

flag = True

while flag == True:
  number = input(prompt + '\n>')

  #ends program when quit
  if number.lower() == 'quit':
    flag = False

#calculates x component and continues with y component if desired
  elif number.lower() == 'x':
    print ('Please tell me the x and the angle:')
    x, angle = [int(x) for x in input('>').split()]
    result = fxcomponent(x, angle)
    print('The x component of %d at %d° is: %d' % (x, angle, result))

    answer = input('Now do you wish to find the y component? \nType Y/N\n>')

    if answer.lower() == 'y':
      print ('Please tell me the y and the angle:')
      y, angle = [int(x) for x in input('>').split()]
      result = fycomponent(y, angle)
      print('The y component of %d at %d° is: %d' % (y, angle, result))

    elif answer.lower() == 'n':
      print('Thanks for using my program! See you later!')
      flag = False

    elif answer.lower() != 'y' or 'n':
      print('Invalid command! try again')

#calculates y component and continues with x component if desired
 elif number.lower() == 'y':
  print ('Please tell me the y and the angle:')
  y, angle = [int(x) for x in input('>').split()]
  result = fycomponent(y, angle)
  print('The y component of %d at %d° is: %d' % (y, angle, result))

  answer = input('Now do you wish to find the x component? \nType Y/N\n>')

  if answer.lower() == 'y':
     print ('Please tell me the y and the angle:')
     y, angle = [int(x) for x in input('>').split()]
     result = fycomponent(y, angle)
     print('The x component of %d at %d° is: %d' % (x, angle, result))

  elif answer.lower() == 'n':
     print('Thanks for using my program! See you later!')
     flag = False

  elif answer.lower() != 'y' or 'n':
     print('Invalid command! try again')

  else:
    print ('Invalid command; try again!')
    continue

Simplify your components functions:

def fxcomponent(x, angle):
    return x * math.cos(math.radians(angle))

def fycomponent(y, angle):
    return y * math.sin(math.radians(angle))

Instead of using number.lower() in every IF statement, convert it once putting number = number.lower() after get the value from input.'
Focusing on readability and maintainability you should extract the copy+paste code of calculating x and y and create a generic function that encapsulates that. So, your code will look like this:

def calculate_fcomponent(component):
    print ('Please tell me the %c and the angle:' % (component))
    value, angle = [int(x) for x in input('>').split()]
    result = fxcomponent(value, angle) if component == 'x' else fycomponent(value, angle)
    print ('The %c component of %d at %d° is: %d' % (component, value, angle, result))
    print()

def run():
    print('Welcome to my Python vector components calculator!')
    print()

    prompt = ('Please select what you wish to find:'
              '\n-type x for x-component'
              '\n-type y for y-component'
              '\n-type quit to end program')

    flag = True

    while flag:
        cmd = input(prompt + '\n>')
        cmd = cmd.lower()

        if cmd == 'quit':
            flag = False

        elif cmd in ('x', 'y'):
            calculate_fcomponent(cmd)

        else:
            print ('Invalid command; try again!')

if __name__ == "__main__":
    run()


RAII object for releasing pointer with arbitrary function The following class is a sort of "smart pointer" that can be used for automatically releasing pointers:

template <class Type>
class Releaser {
 public:
  Releaser(std::function<void(Type *)> function = [](Type *value) {
    value->Release();
  });
  ~Releaser();
  Type *operator->();
  Type &operator*();
  Type *get();
  Type **fill();

 private:
  Type *value_ = nullptr;
  std::function<void(Type *)> function_;
};

template <class Type>
Releaser<Type>::Releaser(std::function<void(Type *)> function)
    : function_(function) {}

template <class Type>
Releaser<Type>::~Releaser() {
  if (value_) function_(value_);
}

template <class Type>
Type *Releaser<Type>::operator->() {
  return value_;
}

template <class Type>
Type &Releaser<Type>::operator*() {
  return *value_;
}

template <class Type>
Type *Releaser<Type>::get() {
  return value_;
}

template <class Type>
Type **Releaser<Type>::fill() {
  return &value_;
}

It can be used for example like this:

Releaser<IMFAttributes> attributes;
auto status = MFCreateAttributes(attributes.fill(), 1);

where MFCreateAttributes has the following signature:

MFCreateAttributes(IMFAttributes** ppMFAttributes, unsigned int cInitialSize);

Do you see any way to improve this (e.g by getting rid of the std::function), or make it safer?

unique_ptr has capability for custom deleters.

Besides that assuming you are doing this to deal with COM objects then you can use ComPtr and its GetAddressOf

If you define a destructor you should also define (or disallow in this case) the copy construct and copy assign. Failure to do so will result in dangling pointers and double frees:

Releaser<IMFAttributes> attributes;
auto status = MFCreateAttributes(attributes.fill(), 1);
{
    Releaser<IMFAttributes> att = attributes;
} // att gets cleaned up

//attributes contains a dangling pointer


Convert string to pig latin in Rust I'm new to Rust and am working through the exercises found on the bottom of this page. The function below converts a string into pig latin. The requirements are as follows.

  Convert strings to Pig Latin, where the first consonant of each word
  is moved to the end of the word with an added “ay”, so “first” becomes
  “irst-fay”. Words that start with a vowel get “hay” added to the end
  instead (“apple” becomes “apple-hay”).

I would like to ensure that my code is as idiomatic as possible, specifically in the string manipulation area. Behold.

fn pigify(text: &str) -> String {
    let map_func = |word: &str| -> String {
        let mut chars = word.chars();
        let first_char = chars.next().unwrap();
        match first_char {
            'a' | 'e' | 'i' | 'o' | 'u' => String::from(word) + "-hay",
            _ => {
                let mut xform = String::new();
                for ch in chars {
                    xform.push(ch);
                }
                xform.push('-');
                xform.push(first_char);
                xform.push_str("ay");
                xform
            }
        }
    };

    let folder = |current: String, next: String| -> String {
        let mut this_str = String::new();
        this_str.push_str(&current);
        if !current.is_empty() {
            this_str.push(' ');
        }
        this_str.push_str(&next);
        this_str
    };

    text.split_whitespace()
        .map(map_func)
        .fold(String::new(), folder)
}

You've got a good use of match and some solid iterator usage, very nice!

Your closures don't need to be closures -- they don't capture any environment. You can just make them functions (even defined inside the other function, if you'd like). Normally, prefer to define closures at the site of use, instead of as variables ahead of the use. This allows type inference to work on them more effectively (probably why you had to specify types for the closure arguments and return values).
Chars::as_str allows you to get the remainder of the underlying string, so you don't need to iterate though all the remaining characters.
The format! macro allows you to build a string from components in a nicer way.
The code doesn't handle empty strings (unwrap makes this easy to find); there's no reason to not handle them.
You don't need to create a new String in folder, just mark the incoming String as mutable

fn pigify_one(word: &str) -> String {
    let mut chars = word.chars();

    let first_char = match chars.next() {
        Some(c) => c,
        None => return String::new(),
    };

    match first_char {
        'a' | 'e' | 'i' | 'o' | 'u' => format!("{}-hay", word),
        _ => format!("{}-{}ay", chars.as_str(), first_char),
    }
}

fn folder(mut current: String, next: String) -> String {
    if !current.is_empty() {
        current.push(' ');
    }
    current.push_str(&next);
    current
}

fn pigify(text: &str) -> String {
    text.split_whitespace()
        .map(pigify_one)
        .fold(String::new(), folder)
}

I'm a big fan of itertools, which provides methods like join:

extern crate itertools;

use itertools::Itertools;

fn pigify(text: &str) -> String {
    text.split_whitespace()
        .map(pigify_one)
        .join(" ")
}

See What's an idiomatic way to print an iterator separated by spaces in Rust?


Basic product builder I'm developing a very basic product builder. Part of the builder has a basic text editor including some text color presets. As it stands, the presets remove a class that defines the text color and add in their own color class.

Looking at my code, it feels absurdly clunky and inefficient. I'm sure there has to be a better way to achieve what I'm working on, but I'm having a hard time figuring out even a starting point to research on what I would need to do to fix this.

$(".black-sel").click(function(){
  $("#prevTex").removeClass (function (index, css) {
    return (css.match (/\btextc-\S+/g) || []).join(' ');});
  $("#prevTex").addClass("textc-black");
});
$(".white-sel").click(function(){
  $("#prevTex").removeClass (function (index, css) {
    return (css.match (/\btextc-\S+/g) || []).join(' ');});
  $("#prevTex").addClass("textc-white");
});
$(".red-sel").click(function(){
  $("#prevTex").removeClass (function (index, css) {
    return (css.match (/\btextc-\S+/g) || []).join(' ');});
  $("#prevTex").addClass("textc-red");
});

Abstract a common function out:

var myFunction = function(myClass){
  $("#prevTex").removeClass (function (index, css) {
    return (css.match (/\btextc-\S+/g) || []).join(' ');});
  $("#prevTex").addClass(myClass);
});

Then apply it like so:

$(".black-sel").click(function(){ myFunction("textc-black"); });
$(".white-sel").click(function(){ myFunction("textc-white"); });
$(".red-sel").click(function(){ myFunction("textc-red"); });


Checking hash and passwords with a wordlist, more efficient I have done a small code in which with a wordlist (out68.lst) I get the passwords from the hashes in the file 'shadow3'.

import crypt
import string
import itertools
import datetime

dir = "shadow3"                          #File that contains hashes and users
file = open(dir, 'r').readlines()

username = []
hashed = []
k=0

for x in file:
    usr, hshd, wtf, iss, this, thing, here, doing, example = x.split(':')
    username.append(usr)
    hashed.append(hshd)
#Loop in order to split the data in the file and store it in username and hashed

grupo1=open('out68.lst','r').readlines()
long=len(grupo1)
print(long)
for y in grupo1:    #Loop in order to go through all the possible words available
  c = 0
  y=y.rstrip('\n')
  y=y.capitalize()
  k = k+1
  if k==(long//100):
    print('1%')
  if k==(long//10):
    print('10%')
  if k==(long//5):
    print('20%')
  if k==(3*long//10):
    print('30%')
  if k==(4*long//10):     #Just to check the progress
    print('40%')
  if k==(5*long//10):
    print('50%')
  if k==(6*long//10):
    print('60%')
  if k==(7*long//10):
    print('70%')
  if k==(8*long//10):
    print('80%')
  if k==(9*long//10):
    print('90%')

  for x in hashed:
      rehashed = crypt.crypt(y, x) #Hash verification f(passwor+hash)=hash?
      if rehashed == x:
          print('La contraseña del usuario ' + username[c] + ' es ' + y)
      c = c + 1

It does work but depending on the size of the files, it can last now from 30 minutes to 6 hours.  So I am asking if there is any way to improve the performance, by paralelization, or GPU processing (but I have no idea about this).

Some suggestions:

Run the code through at least one linter such as flake8 or pycodestyle to produce more idiomatic code.
Don't read all the lines into a variable before starting processing - this will slow things down and use much more memory than necessary for large files. Instead you can use for line in file.readlines().
You are doing ten calculations in order to run a single print statement. Either get rid of them or do something simpler like print("{}/{} complete".format(k, long)).
If you know y has exactly one newline at the end you can do y[:-1] instead of y.rstrip('\n').
Capitalizing each word is expensive. Avoid it if at all possible.
If you don't need a bunch of the fields in an input file add a limit to your split() and mark the last stuff as discarded by using the _ variable. For example: usr, hshd, _ = x.split(':', 3)
Rather than keeping track of k manually you can just do for k, y in enumerate(grupo1).
Rather than having a list of usernames and a list of their hashed passwords, a Dict[str, str] of username to hash should be easier to keep track of.


Calculation of Hamming distance between two adjacency lists I have written a Java program to calculate the Hamming distance between two adjacency lists. The program calculates the Hamming distance correctly, but it takes a very long time, especially when dealing with bigger lists. Can anyone suggest a better way to optimize my program?

Below are the sample lists and the method that calculates Hamming distance:

Adjacency list for a:

0 => 0 1 2
1 => 0 1
2 =>

Adjacency list for b:

0 => 0
1 => 0 1 2
2 => 0 1 2

Hamming distance between Adjacency List A and B is: 6

public int hamming(ArrayList[] a, ArrayList[] b) {
    int distance = 0;
    for (int i2 = 0; i2 < b.length; i2++) {
        for (int j2a = 0; j2a < a[i2].size(); j2a++) {
            boolean found = false;
            for (int k = 0; k < b[i2].size(); k++) {
                if ((int) a[i2].get(j2a) == (int) b[i2].get(k)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                distance++;
            }
        }
        for (int j2b = 0; j2b < b[i2].size(); j2b++) {
            boolean found = false;
            for (int k = 0; k < a[i2].size(); k++) {
                if ((int) b[i2].get(j2b) == (int) a[i2].get(k)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                distance++;
            }
        }
    }
    System.out.println("Hamming distance between Adjacency List  A and B is: " + distance + "\n");
    return distance;
}

First what you want is not the Hamming distance but the Levenshtein distance (the Hamming distance in fact assumes that the two strings (in this case lists) have the same size).
Computing the Levenshtein distance is not trivial and to build an efficient algorithm you need to use the dynamic programming (otherwise you can come up with a recursive algorithm that is less efficient).

The approach is the following:
A list can be transformed in a second one by applying tree different operations to an element: insert, remove, modify.

With this in mind we design the algorithm as follow:
we keep a matrix M where

M[i][j] = distance between the first i-th elms of the the first list and the first j-th elems of the second list.

Thus, the first row of the matrix represents the distance between an empty list and the second list if you consider only the first i-th elements. Thus it has to initialized as follow:

for i in range(len(l1)):
    M[0][i] = i

because we can always transform a list to the empty one by dropping all the elements (so i operations).

Similarly first column also  is initialized in the same way:

for i in range(len(l2)):
    M[i][0] = i

At this point to compute the distance between the first i elements of l1 and the first j elements of l2 we have to consider which is the operation that will transform l1 to l2 with fewer operations. So we take the minimum between

the number of operations to transform l1[0:i-1] into l2[0:j] + 1 (the added 1 is the cost for this operation which is the deletion)
the number of operations that we had to perform to transform l1[0:i] into l2[0:j-1] + 1 (this represent the insertion operation)
and the number of operations to transform l1[0:i-1] into l2[0:j-1]. Summing 1 if l1[i] != l2[j] (we have to substitute te element), 0 otherwise.

This translated into formula is:

M[i][j] = min(M[i-1][j] + 1, M[i][j-1] + 1, M[i-1][j-1] + 1 if l1[i]==l2[j] else 0

Implementing everything in java is:

public static int editDistance(List<String> l1, List<String> l2)
{
    int[][] M = new int[l1.size()][l2.size()];
    for(int i = 0; i < l2.size();i++)
        M[0][i] = i;
    for(int i = 0; i < l1.size(); i++)
        M[i][0] = i;

    for(int i = 1; i < l1.size(); i++)
    {
        for(int j = 1; j < l2.size(); j++)
        {
            int substitute = 0;
            if(!l1.get(i).equals(l2.get(j)))
                substitute = 1;

            int minRemoveAdd = Math.min(M[i - 1][j] + 1, M[i][j - 1] + 1);
            M[i][j] = Math.min(minRemoveAdd, M[i-1][j-1] + substitute);
        }
    }
    return M[l1.size() - 1][l2.size() - 1];
}


Rails Grape API Endpoint optional params validation in update I have the following rails grape api endpoint in the users resource:

    desc 'updates a user'
    params do
      optional :first_name, type: String
      optional :active, type: Boolean
      optional :second_name, type: String
      optional :rating, type: Integer
      requires :id, type: Integer
    end
    put ':id' do
      user = User.find_or_create_by(id: params[:id])
      user.name = params[:name] if params[:name].present?
      user.active = params[:active] if params[:active].present?
      user.second_name = params[:second_name] if params[:second_name].present?
      user.rating = params[:rating] if params[:actratingve].present?
      user.save!
    end

Any nicer way to update model without asking per line if the param is present?

user.assign_attributes(params)
user.save

model.assign_attributes(hash) allows you to assign a key value hash to your ActiveRecord object. The only caveat is that the keys passed must correspond to your columns or an exception will be raised. You will need to call .save to persist the changes.

If you want to assign and save in one fell stroke, use model.update(hash).

http://api.rubyonrails.org/classes/ActiveRecord/AttributeAssignment.html


Is there a more elegant solution than this spaghetti code without completely revamping the whole page? I use 'GROUP_CONCAT' to get comma separated lists of a person's educational background.  Included in those lists are the type of degree, major, issuing establishment, and year received.  degreeType is a required field and cannot empty.  Prior to looping, I split the lists into arrays, like so:

$degreeType = explode(",", $degreeType);
$major = explode(",", $major);
$issuingEstablishment = explode(",", $issuingEstablishment);
$yearReceived = explode(",", $yearReceived);

I can then do a foreach loop and echo out the information returned.  However, since explode() returns an array, even if it's empty, I have to check it first before starting the foreach.  As shown below:

$counter = 0;
//echo out education
if($degreeType[0]!=""){
  foreach($degreeType as $dType) {
    if($counter == 0) $info .= "
Educational Background

";
    $info .= "
$dType - ";
    $info .= ($major[$counter]!="") ? "$major[$counter], " : "";
    $info .= $issuingEstablishment[$counter];
    $info .= ($yearReceived[$counter]!="") ? ", $yearReceived[$counter]" : "";
    $info .= "
";
    $counter++;
  }
  $info .= "
";
}

Alternatively, I could run a check prior to separating the lists.  Either solution seems inelegant.  Is there a cleaner/faster/better way to split the lists and loop through them, but only if they actually contain information?  Initially I was going to dabble with using an object, but mysqli doesn't support that with prepared statements.  Any advice is much appreciated!

Your script is alright, there are just some minor issues:

1.) If string is enclosed inside "" then PHP interpreter checks whether there are some variables or not, if string is enclosed inside '' PHP interpreter does not check it.

2.) You forgot to declare $info variable, it is always good to declare your variables before doing some operations on them like .=.

3.) I don't like using this shorter syntax, because it can be source of bugs which are hard to find, in my opinion it is usually better to use {}:

if($counter == 0) $info .= "
Educational Background

";

4.) You don't need to repeat $info .= on every line, it can be replaced by ..

I rewrote the script in respect to previously mentioned points:

$degreeType = explode(',', $degreeType);
$major = explode(',', $major);
$issuingEstablishment = explode(',', $issuingEstablishment);
$yearReceived = explode(',', $yearReceived);

$counter = 0;
$info = '';
if($degreeType[0] != ''){
    foreach($degreeType as $dType) {
        if(!$counter) {
            $info .= '
Educational Background

';
        }

        $info .= "
$dType - "
            . (($major[$counter] != '') ? "$major[$counter], " : '')
            . $issuingEstablishment[$counter]
            . (($yearReceived[$counter] != '') ? ", $yearReceived[$counter]" : '')
            . '
'
        ;

        $counter++;
    }
    $info .= "
";
}


Isn't this dynamic programming? I was solving problem 18  and 67 on Project Euler and came up with an algorithm that actually goes through almost all the possibilities to find the answer in O(n) time. However, ProjecEuler claims that a Brute force solution will take too long.
Many have implemented this problem using trees, dp and what not.

Is my approach not a Brute force?

n = []
for i in range(100):
    n.append(map(int,raw_input().split()))
newresult = [int(59)]
n.pop(0)
for i in range(99):
    x = n.pop(0)
    result = list(newresult)
    newresult =[]
    t = len(x)
    for j in range(t):
        if(j==0):
            newresult.append(result[0]+x.pop(0))
        elif(j==t-1):
            newresult.append(result[0]+x.pop(0))
        else:
            newresult.append(max((result.pop(0)+x[0]),result[0]+x.pop(0)))
print max(newresult)

UPDATE:
here's a idea how my algorithm works (taking max when needed)

Is my approach not a Brute force?

Nope, you've implemented dynamic programming

n = []
for i in range(100):
    n.append(map(int,raw_input().split()))
newresult = [int(59)]

I'm not clear why you pass 59 to int, it doesn't do anything.
    n.pop(0)

why didn't you do newresult = n.pop() instead of recreating the first row in the code?

for i in range(99):
    x = n.pop(0)
    result = list(newresult)

This makes a copy of newresult, which is pointless here since you don't keep the original around anyways

    newresult =[]
    t = len(x)
    for j in range(t):

        if(j==0):

You don't need the parens

            newresult.append(result[0]+x.pop(0))

I think the code is a bit clearer if you don't use x.pop just calculate the appropriate indexes

        elif(j==t-1):
            newresult.append(result[0]+x.pop(0))
        else:
            newresult.append(max((result.pop(0)+x[0]),result[0]+x.pop(0)))

Figuring out the logic of what happens with all this popping is tricky. Again, I think calculating the index will be more straightforward. Also it'll probably be faster since popping the first element of a list is expensive.

print max(newresult)

A brute force solution would iterate over every possible path down the triangle. You are iterating over every possible position in the triangle which is much much smaller.

EDIT

The dynamic programming solutions starts with a recursive definition of the solution:

cost(i) = number(i) + max( cost(j) for j in predeccesors(i) )

Where i, j corresponds to positions on the triangle, and predecessors(i) is the set of all positions which can move onto i.

The top-down approach works by using memoization, remembering a value of cost(j) after it has been calculated. When cost(j) is needed again, it is simply reused.

However, you can also use the bottom-up approach to dynamic programming. In this case, you calculate the values of cost(i) starting from the first cells and work your way forward. Ever cost(i) only depends on the costs of cells before the current cell, and since those have already been calculated they can be reused without even using memoization.

If you look at your code, you'll find that the innermost loop is calculating the same formula as above. Furthermore, you'll find that it is calculating the cost of reach each cell starting from the cells at the top of the triangle and moving its way down. That's why I characterize it as dynamic programming.

I think you don't see this as DP, because you really didn't follow any DP logic in coming up with the solution. I think you are viewing it in terms of repeatedly reducing the complexity of the problem by eliminating the top row. In the end you are doing the same calculations as the DP version although you came at it from a different angle.

  I think dp uses the same solution again and again, wheras there is
  no need of such memorization here

All that's necessary for DP is to reuse solutions more than once. In this case, every number you calculate gets used in two places (one for the right, one for the left)


MVC controller and action that handles favorite items in a session-based list I've written a Controller and a corresponding Action for a Symfony 2.8 project, that does the following:

handles a list of favorite items of a user
the ids of the favorites are stored in the session
multiple entites can be favorized
possible actions on the favorite list are [add|remove]
the controller's action is called via AJAX and returns a JSON object

My questions are:

Can the PHP Code be optimized?
Is this code DRY?
Is this code safe?
Is this too much logic for one action?
Is it too much or not enough or even wrongly documented?

A few notes:

$this->getRepositoryName() is a custom function from the AbstracController base class that returns the correct repository name for a given entity
the returned JSON object is more then just the state of success, so the JavaScript can see, what exactly failed, if one ore more properties come back empty
I only need the favorites in the session for a filter later, they are not going to be stored or tracked using a database

class FavoritesController extends AbstractController
{
    private $validEntites = ['entityA', 'entityB'];
    private $validActions = ['add', 'remove'];

    /**
     * Can add or remove favorites to/from the list in the session.
     *
     * @Route("/handle-favorites", name="handle_favorites")
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function handleFavoritesAction(Request $request)
    {
        // initiate return value, will be send as JSON
        $result = [
            'success' => true,
            'entity' => null,
            'count' => null,
            'id' => null,
            'action' => null,
        ];

        // test for XHR request
        if(!$request->isXmlHttpRequest()) {
            $result['success'] = false;
            return new JsonResponse($result);
        }

        // retrieve values from session and create favorites array if necessary
        $session = $request->getSession();
        $favorites = $session->get('favorites');

        if (!$favorites) {
            $favorites = [];

            foreach ($this->validEntites as $value) {
                $favorites[$value] = [];
            }
        }

        // get and test request parameters
        $entity = $request->get('entity');
        $id = $request->get('id');
        $action = $request->get('action');

        if (in_array($entity, $this->validEntites)) {
            $result['entity'] = $entity;
        } else {
            $result['success'] = false;
        }

        if (in_array($action, $this->validActions)) {
            $result['action'] = $action;
        } else {
            $result['success'] = false;
        }

        if (false !== filter_var($id, FILTER_VALIDATE_INT, array('options' => array('min_range'=> 1)))) {
            $result['id'] = $id;
        } else {
            $result['success'] = false;
        }

        // add or remove item
        if ($result['success']) {
            if ('remove' === $action) {
                $favorites[$entity] = array_diff($favorites[$entity], [$id]);
            }

            if ('add' === $action && !in_array($id, $favorites[$entity])) {
                $repository = $this->getDoctrine()->getRepository($this->getRepositoryName(ucfirst($entity)));
                $object = $repository->find($id);

                if ($object) {
                    $favorites[$entity][] = $id;
                } else {
                    $result['success'] = false;
                    $id = null;
                    $result['id'] = $id;
                }
            }

            // update session
            $session->set('favorites', $favorites);
        }

        // update count
        $result['count'] = count($favorites[$entity]);

        return new JsonResponse($result);
    }
}

A few thoughts.

Consider building a result or response class to:

provide better structure around the returned result
provide possible re-use in other controllers
and clean up this code.

For example:

// instantiation
$result = new Result();

// usage
$result->setSuccess(true);
$result->setEntity($entity);

You could have this class implement JsonSerializable interface so you can pass it directly to JsonResponse() for serialization.  This also allows you to do things like add validation that setters are passed valid values (i.e. boolean for setSuccess())

You have a number of cases where you could remove else blocks and code nesting if you invert your conditionals.

For example:

    if (in_array($entity, $this->validEntites)) {
        $result['entity'] = $entity;
    } else {
        $result['success'] = false;
    }

can become:

   $result['success'] = false;
   if (in_array($entity, $this->validEntites)) {
        $result['entity'] = $entity;
   }

or:

  if(!in_array($entity, $this-.validEntities)) {
      $result['success'] = false;
      return JsonResponse($result);
  }
  $result['entity'] = $entity;

Similarly:

if($result['success']) {
    // nested code
}

could become:

if(!$result['success']) {
    return JsonResponse($result);
}
// rest of code, now without nesting

Look for opportunities to remove code paths and complex nesting by getting rid of unnecessary else blocks (many of which truly are unnecessary) and exiting early by inverting conditions.  The fewer code paths you have in your code, the less fragile, easier to test, and easier to maintain it will be.

I think if you clean those things up, you will probably save 40% of the lines of code in this method. So it might not look like there is "too much" happening in this single method.  That being said, I think you could possibly fork the execution path along the lines of $action value , and hand off to protected/private class methods to finish that particular work.

For example:

switch($action) {
    case 'remove':
        return $this->removeFavorite(...);
    case 'add':
        return $this->addFavorite(...);
    default:
        $result['success'] = false;
        return JsonResponse($result);
}

This would allow to more easily unit test those individual methods that represent some subset of logic on dealing with "favorites".

Similarly, you could perform all your upfront Request validation in a separate method as well to where you are getting towards something more like this in your main method.

Ex:

public function handleFavoritesAction(Request $request) {
    // here $result could be Result object as suggested above
    $result = $this->validateRequest($request);
    if($result->isSuccess === false) {
       return JsonResponse($result);
    }
    $action = $request->get('action');
    switch ($action) {
        // switch as shown above
    }
}

With regards to your documentation, I find many of your comments to be unnecessary. I think you generally have meaningfully named variables and appropriate use of vertical whitespace between logical sections of code to where comments become superfluous.  Especially, if you consider breaking this main method into several other well-named methods, you should not have much need to comment this code.


Elixir/Ecto find_or_create with custom error I need to find_or_create user, but first, check if his email ends with a required domain.

Can I somehow write following code using pattern matching with/case block?

  def create_user(attrs \\ %{}) do
    %User{}
    |> User.changeset(attrs)
    |> Repo.insert()
  end

  def find_or_create_user(attrs \\ %{}) do
    if String.ends_with?(attrs.email, "@test.com") do
      user = Repo.get_by(User, %{email: attrs.email}) # returns nil or user
      if user do
        {:ok, user}
      else
        create_user(attrs) # returns {:ok, user} or {:error, :reason}
      end
    else
      {:error, :invalid_email_domain}
    end
  end

I think it is a perfect fit for with. It will be something like:

def find_or_create_user(attrs \\ %{}) do
  with  true <- String.ends_with?(attrs.email, "@test.com"),
        nil <- Repo.get_by(User, %{email: attrs.email}),
        {:ok, user} <- create_user(attrs)
  do
    {:ok, user}
  else
    false -> {:error, :invalid_email_domain}
    %User{} = user -> {:ok, user}
    {:error, changeset} -> {:error, changeset}
    _anything_else -> {:error, "cannot find or create user"}
  end
end


Single Digit Math Quiz I decided to write a very simple web-game:

function write_at(x, y, text, color, font) {
  ctx.fillStyle = color || "black";
  ctx.font = font || "50px Arial";
  ctx.fillText(text, x + 50, y + 50);
}

function write_at_random(text, color, font) {
  write_at(random_choice(range(0, canvas.width - 250)),
    random_choice(range(200, canvas.height - 250)),
    text, color, font);
}

function random_choice(array) {
  index = Math.random() * array.length
  return array[Math.floor(index)]
}

function range(start, end) {
  return Array.apply(0, Array(end))
    .map(function(element, index) {
      return index + start;
    });
}

function gen_math_expression() {
  start = random_choice(range(0, 20));
  operator = random_choice(['+', '-', '*']);
  end = random_choice(range(0, 20));
  return start + operator + end;
}

function single_digit(expr) {
  return eval(expr) <= 9 && eval(expr) >= 1
}

function gen_single_digit_expression() {
  expr = gen_math_expression();
  while (!single_digit(expr)) {
    expr = gen_math_expression();
  }
  return expr;
}

function number_from_keycode(keycode) {
  return keycode.which - 48;
}

function draw_welcome_and_score() {
  write_at(0, 0, "Single Digit Math Quiz");
  write_at(600, 0, points);
}

function lose_sound() {
  var snd = new Audio("http://www.soundjay.com/misc/sounds/fail-buzzer-02.mp3");
  snd.play();
}

function win_sound() {
  var snd = new Audio("http://www.soundjay.com/misc/bell-ringing-05.mp3");
  snd.play();
}

function main() {
  canvas = document.getElementById("canvas")
  ctx = canvas.getContext('2d');
  points = 0
  draw_welcome_and_score()
  write_at(0, 100, "Press the result of the operation on your keyboard.", 0, "20px Arial");

  expr = gen_single_digit_expression()
  write_at_random(expr);

  function check_expr_and_go_next(e) {
    if (number_from_keycode(e) == eval(expr)) {
      points++;
      color = '#7CFC00'; // light green
      win_sound()
    } else {
      points--;
      color = 'red';
      lose_sound()
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    canvas.style.background = color;
    draw_welcome_and_score()
    expr = gen_single_digit_expression()
    write_at_random(expr);
  }

  window.addEventListener("keydown", check_expr_and_go_next, true);

}

main()
<html>
<canvas id="canvas" width="800" height="600" style="border:1px solid #000000;">
</canvas>
</html>

You can't currently play with the numbers on the numpad of a keyboard - they have different keycodes to the numbers along the top.

It's normal to camelCase function names rather than snake_case.

Avoid abbreviations e.g. the gen in gen_single_digit_expression.

function number_from_keycode(keycode) { - keycode isn't a keycode at all, it's an event.

Try to remember your semicolons - it's not required but many people (myself included) prefer to see them. There are a couple of very subtle edge cases that can cause problems if you omit them.

eval is evil. You really don't need to invoke the interpreter to do a simple sum!

Here's an example of a simple constructor function (and usage) to show you a way of doing it without eval.

var MathExpression = function(left, operator, right) {
    this.evaluate = function () {
        switch (operator) {
            case '+':
                return left + right;
            case '-':
                return left - right;
            case '*':
                return left * right;
        }
    };
};

var e1 = new MathExpression(1, '+', 8);
console.log(e1.evaluate()); // 9

You don't need to brute force expression generation either. Choose the operator first, then choose the LHS and finally choose a number for the RHS that is within the allowed range.

'+' (addition)
Choose LHS: 1 <= LHS <= 8
Choose RHS: 1 <= RHS <= 9 - LHS

LHS choose 5.
RHS can be 1, 2, 3 or 4 to yield a single digit answer.

You can do the same for the other operators:

'*' (multiplication)
Choose LHS: 1 <= LHS <= 4
Choose RHs: 1 <= RHS <= 9/LHS (rounded down).

LHS choose 4.
RHS can be 1 or 2 to yield a single digit number. (9/4 = 2.25 -> 2)

I'll leave '-' for you to do.


C++ Grid gravity simulation opzimization (Kattis Falling Apples) I have a solution for the Kattis Falling Apples problem (link).  The input is a grid of R rows (up to 50000) by C columns (up to 10).  At each timestep, apples (indicated by 'a') move down one cell into an empty space (denoted by .) or rest upon an obstacle (marked by #).

My solution exceeds time limit only at the last test case.  I'm thinking the while loop is the problem, but I have no idea what I could do to optimize it.

#include <iostream>

using namespace std;

int main()
{
    int r; // Grid rows
    int c; // Grid columns

    scanf("%d %d", &r, &c);

    char grid[r][c];

    // Establish grid
    for (int i = 0; i < r; i++) {
        char line[c];
        scanf("%s", &line);
        for (int j = 0; j < c; j++) {
            grid[i][j] = line[j];
        }
    }

    // Loop to change
    while (true) {
        bool change = false;

        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {

                if (grid[i][j] == 'a' && grid[i + 1][j] == '.') {
                    grid[i + 1][j] = 'a';
                    grid[i][j] = '.';
                    change = true;
                }

            }
        }

        if (!change) {
            break;
        }
    }

    // Print the grid
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            cout << grid[i][j];
        }
        printf("\n");
    }

    return 0;
}

Avoid allocating large arrays on a stack. According to the restrictions, grid may take up to half a meg. You are dangerously close to stack overflow.
Avoid single letter identifiers. Spelling out row and col wouldn't make your program any slower, but it would make it much more readable.
scanf adds a null terminator to a string. Your char line[c] is one character short. Definite UB.
The problem statement clearly says that

  Merely iterating the gravity rule, a step at a time, will likely take too long on large datasets.

but that is exactly what your code is doing. No optimization may salvage this algorithm. You need to rethink the approach.

I don't want to spell out a solution, but here are few hints:

Columns are totally independent. Do one column at a time.
Do not drop apples. Count them.
It is beneficial to add an artificial row of obstacles at the bottom.


Get relative path from to/from path Is there a better way to optimize this code? It started with \$O(n^2)\$ (nested loops) then \$O(n)\$ (with index).

public static String getRelativePath(String from, String to) {
    String relative = "";
    String regexPath = "/";
    String regexLow = "..";

    List<String> toList = Arrays.asList(to.split(regexPath));
    List<String> fromList = Arrays.asList(from.split(regexPath));

    int toSize = toList.size();
    int fromSize = fromList.size();

    relative += regexPath;

    for(int index = 0; index < fromSize; index++) {
        if(index <= toSize-1) {
            String toValue = toList.get(index);
            String fromValue = fromList.get(index);

            if(toValue.equals(fromValue)) {
                relative += regexLow + regexPath;
            }
            else
                relative += fromValue + regexPath;
        }
        else {
            if(index != fromSize-1)
                relative += fromList.get(index) + regexPath;
            else
                relative += fromList.get(index);
        }
    }

    return relative;
}

Inputs:

  fromPath -> "/a/b/c" toPath -> "/a/b/d/f"

Output:

  relativePath -> "/../../d/f

Performance-wise, yes, you can optimize it by going character-by-character through the input looking for / characters, such as below. It's weakly tested, and I wouldn't ever consider it in a whiteboard interview. This runs an order of magnitude faster than your method on my old laptop.

public static String getRelativePathMessy(final String from, final String to) {
    final int lastIndex = Math.min(from.length(), to.length());
    int index = 0;
    while ((index < lastIndex) && (from.charAt(index) == to.charAt(index))) {
        index += 1;
    }

    final StringBuilder relativePath = new StringBuilder();
    int fromIndex = from.lastIndexOf(PATH_SEPARATOR, index);
    while (fromIndex > 0) {
        relativePath.append("../");
        fromIndex = from.indexOf(PATH_SEPARATOR, fromIndex + 1);
    }

    if (index < lastIndex) {
        final String toPath = to.substring(to.lastIndexOf(PATH_SEPARATOR, index) + 1);
        relativePath.append(toPath);
    }
    return relativePath.toString();
}

Readability-wise, yes you can optimize it. This is marginally faster than your implementation, probably because it avoids the unnecessary use of Lists. I would argue it's a lot easer to understand what's going on. Why? Fewer branches, especially nested ones, and better names.

public static String getRelativePathNeat(final String from, final String to) {
    final String[] fromPathElements = from.split(PATH_SEPARATOR);
    final String[] toPathElements = to.split(PATH_SEPARATOR);

    final int firstDifferentPathIndex = findFirstDifferentPathIndex(fromPathElements, toPathElements);

    final StringBuilder relativePath = new StringBuilder();
    for (int i = firstDifferentPathIndex; i < fromPathElements.length; i++) {
        relativePath.append("..");
        relativePath.append(PATH_SEPARATOR);
    }

    for (int i = firstDifferentPathIndex; i < toPathElements.length; i++) {
        relativePath.append(toPathElements[i]);
        relativePath.append(PATH_SEPARATOR);
    }
    relativePath.delete(relativePath.length() - 1, relativePath.length());

    return relativePath.toString();
}

private static int findFirstDifferentPathIndex(final String[] fromPathElements, final String[] toPathElements) {
    final int maxIndex = Math.min(fromPathElements.length, toPathElements.length);
    int arrayIndex = 0;
    while ((arrayIndex < maxIndex) && fromPathElements[arrayIndex].equals(toPathElements[arrayIndex])) {
        arrayIndex += 1;
    }

    return arrayIndex;
}


Validating input in a React app I was writing some validation logic for a React-native app and thought I had so many bools flying around in my code!

Is there any way to reduce redundancy in this code or is this the best that can be done?

_validatePhone() {
    if (!validate.validatePhone(this.state.phone)) {
      this.setState({ phoneError: true });
      return false;
    }
  return true;
}

_validateName() {
    if (!validate.validateName(this.state.name)) {
      this.setState({ nameError: true });
      return false;
    }
    return true;
  }

  _validateForm() {
    this._resetErrors(); // Reset errors before validating
    if (!this._validateName()) {
      return false;
    } else if (!this._validatePhone()) {
      return false;
    }
    return true;
  }

_validateForm can be reduced to

_validateForm() {
    this._resetErrors(); // Reset errors before validating
    return this._validateName() && this._validatePhone();
}