Better way to use pseudo elements Here is a JSFiddle of an accordion menu that i've done. I have used :before to add the icons.

My question is, is there a better way to Add different icon to each li item?

My code is as follows:

HTML Structure:

Profile

Messages

Inbox

Sent

Drafts

Settings

Logout

CSS:

    body {
background-image: url(http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tiny_grid.png);
}

ul{
  list-style-type:none;
  padding:0;
  margin:0;
}

#accordion{
  margin: 20% auto 80% auto;
  width:200px;
  height:auto;
  background-color:#212830;
  border-radius:5px;
  color: #BECEDB;
  font-family: 'Maven Pro', sans-serif;
  border: 1px solid #191E24;
  box-shadow: 0px 0px 5px 2px #666666;
}

#accordion > li > div{
  background-color:#383C48;
  font-weight:700;
  -moz-box-shadow:inset 0 1px 1px -1px #A1B3C9;
  -webkit-box-shadow:inset 0 1px 1px -1px #A1B3C9;
  box-shadow:inset 0 1px 1px -1px #A1B3C9;
  border-bottom:1px solid #191E24;
}

#accordion > li > div, #accordion > li > ul > li{
  padding:10px 15px;
}

#accordion li{
  cursor:pointer;
}

#accordion > li:first-child >div{
  border-radius: 5px 5px 0 0;
}

#accordion > li:last-child >div{
  border-radius: 0 0 5px 5px;
}

#profile:before,
#messages:before,
#settings:before,
#logout:before,
.submenu>li:before
{
  font-family:FontAwesome;
}

#profile:before{
  content:"\f007  ";
}
#messages:before{
  content:"\f0e0";
}

#settings:before{
  content:"\f013";
}

#logout:before{
  content:"\f08b";
}

.submenu li:before{
  content:"\f0da"
}

#accordion *:before{
  margin-right:10px;
}

.submenu li{
  margin-left:10px;
}

JS code: (No problem with this)

 $("#accordion > li > div").click(function(){
  if(false == $(this).next().is(':visible')){
        $('#accordion ul').slideUp(400);
    }
  $(this).next().slideToggle(300);
 });

$('#accordion ul:eq(0)').show();

Also I would like to know if there are other areas this can be optimized.
Thank you

First things first: You have a navigation but refuse to use anchor tags. Why? This is potentially harmful. How are you going to navigate if you don't have links? The only possible way would be completely relying on JavaScript. All users with disabled JavaScript have a useless list of words instead.

HTML:

Use a tags instead of the div's in your HTML (Use <a href="#"> to test this)
I'd suggest using classes instead of ID's in this scenario as well. The lower specificity of classes will ease your live later. Overwriting an ID instead could be hard

CSS:

If you use actual links for your navigation, there is no need for cursor: pointer; on list-items.
If you want the icons to be clickable as well, add the pseudo-elements to the links instead of the list-items
Don't reset the general styling for lists on the type selector ul. Doing this makes you unable to use lists as regular lists in text etc. You can reset the styles for the navigation on #accordion
Adding a class accordion-item to your list-items could help you. You don't selecting like this: #profile:before, #messages:before, #settings:before...

You have some things to consider now. There are more things to improve, but I'd like to see a new question for an updated navigation with the given advice.


Node.js Data-Completion script Following task:

Customer-data, given in a JSON-file, have to be completed with additional address-data. Given in a second JSON-file.

Then these data-stock has to be saved into a MongoDB-database.

Schema of the customer-JSON:

[
    {
      "id": "1",
      "first_name": "Ario",
      "last_name": "Noteyoung",
      "email": "anoteyoung0@nhs.uk",
      "gender": "Male",
      "ip_address": "99.5.160.227",
      "ssn": "509-86-9654",
      "credit_card": "5602256742685208",
      "bitcoin": "179BsXQkUuC6NKYNsQkdmKQKbMBPmJtEHB",
      "street_address": "0227 Kropf Court"
    },
    {
      "id": "2",
      "first_name": "Minni",
      "last_name": "Endon",
      "email": "mendon1@netvibes.com",
      "gender": "Female",
      "ip_address": "213.62.229.103",
      "ssn": "765-11-9543",
      "credit_card": "67613037902735554",
      "bitcoin": "135wbMcR98R6hqqWgEJXHZHcanQKGRPwE1",
      "street_address": "90 Sutteridge Way"
    },
...
]

Schema of the addresses-JSON:

[
  {
    "country": "United States",
    "city": "New Orleans",
    "state": "Louisiana",
    "phone": "504-981-8641"
  },
  {
    "country": "United States",
    "city": "New York City",
    "state": "New York",
    "phone": "212-312-1945"
  },
...
]

Desired result:

[
  {
    "_id" : ObjectId("5b3f16f5743a6704739bf436"),
    "id" : "1",
    "first_name" : "Ario",
    "last_name" : "Noteyoung",
    "email" : "anoteyoung0@nhs.uk",
    "gender" : "Male",
    "ip_address" : "99.5.160.227",
    "ssn" : "509-86-9654",
    "credit_card" : "5602256742685208",
    "bitcoin" : "179BsXQkUuC6NKYNsQkdmKQKbMBPmJtEHB",
    "street_address" : "0227 Kropf Court",
    "country" : "United States",
    "city" : "New Orleans",
    "state" : "Louisiana",
    "phone" : "504-981-8641"
  },
  ...
]

My solution:

const mongodb = require("mongodb");

const filePathCustomer = "./customers.json";
const filePathAddresses = "./addresses.json";

const MongoClient = mongodb.MongoClient;

completeCustomers = (filePathCustomers, filePathAddresses) => {
  const customers = require(filePathCustomers);
  const addresses = require(filePathAddresses);

  return (updatedCustomers = customers.map((customer, index) => {
    const updatedCustomer = Object.assign(customer, addresses[index]);

    return updatedCustomer;
  }));
};

MongoClient.connect(
  "mongodb://localhost:27017/bitcoinExchange",
  (error, client) => {
    if (error) {
      throw new Error("Connecting to MongoDb has failed.");
    }

    const db = client.db();

    let execCompleteCustomer = new Promise(resolve => {
      resolve(completeCustomers(filePathCustomer, filePathAddresses));
    });

    execCompleteCustomer
      .then(customer => {
        db.collection("customers").insertMany(customer, (error, result) => {
          if (error) {
            db.close();
            throw new Error("Writing to database has failed");
          }
          console.log(
            "Count of customer documents inserted:",
            result.insertedCount
          );

          return true;
        });
      })
      .then(result => {
        if (result) db.close();
      })
      .catch(() => {
        db.close();
        throw new Error("The merging of the customer-data has failed.");
      });
  }
);

What would you have done different and why?

Is my error-handling done in a good way and fashion? How could it be improved?

What bothers me a bit are this multiple occurences of db.close().

Is there a way in Node to avoid these redundancy?

Something like finally in Java.

Just a few things

To start out, the return statement in your function completeCustomers should/could be changed.

The way the function is defined should also be changed. But we'll get to that in a second.

return (updatedCustomers = customers.map((customer, index) => {
  const updatedCustomer = Object.assign(customer, addresses[index]);

  return updatedCustomer;
}));

I would replace with:

return (updatedCustomers = customers.map((customer, index) => ({
  ...customer,
  ...addresses[index]
})))

Note, you don't have to make it take up multiple lines if you don't want.

Use const when you don't modify a variable, or arrow function

This means that the two functions below need to change:

completeCustomers = (filePathCustomers, filePathAddresses) => {

Would become:

const completeCustomers = (filePathCustomers, filePathAddresses) => {

let execCompleteCustomer = new Promise(resolve => {

And this would become:

const execCompleteCustomer = new Promise(resolve => {

That's all I have for now, but I'm not getting what part you are saying is redundant. And I think you handled the errors well.


Rock paper scissor game in Python Hello am a new to Python and my programming concept is catching up to me.
I just created my first ever project. I did not look else where for an answer, and it took me 6 hours to write.
How can I improve this code? Is their a way to use for loop to check the if player1 beats player2.
Please don't recomend using functions.
choice = ['r', 'p', 's']
player = ['1', '2']
user_Ply = []
ply_round = 0
draw = 0

print("--------------------------------------------------------------------")
print(r"""THIS IS A GAME OF ROCK, PAPER AND SICSSORS TO PLAY EITHER ENTER
R FOR "ROCK" P FOR "PAPER" AND "S" FOR SCISSORS """)

 while True:
        ply_round += 1
        win = ''
        active_player = player[0]
        isPlayer1_TheActive_Player = True
        if isPlayer1_TheActive_Player:
            for i, players in enumerate(player):
                if active_player == player[i]:
                    print('------------------------------------------')
                    print('Player One it your Turn')
                    ply_1 = input('Enter "Rock","Paper","Scissors :" ')
                    user_Ply.append(ply_1)
                    for j, v in enumerate(choice):
                        if choice[j] in ply_1:
                            print(f'you choose {choice[j]}')
                else:
                    print('------------------------------------------')
                    print('Player Two it your Turn')
                    ply_2 = input('Enter "Rock","Paper","Scissors :" ')
                    user_Ply.append(ply_2)
                    for j, v in enumerate(choice):
                        if choice[j] in ply_2:
                            print(f'you choose {choice[j]}')
                            isPlayer1_TheActive_Player = False

        if ((user_Ply[0] == choice[-1] and user_Ply[1] == choice[-1]) or (user_Ply[0] == choice[1] and user_Ply[1] == choice[1]) or (user_Ply[0] == choice[0] and user_Ply[1] == choice[0])):
            print(fr'The result of round {ply_round} is a draw')
            draw += 1
            user_Ply.clear()
        elif (user_Ply[0] == choice[0] and user_Ply[1] == choice[-1]):
            print(fr'The result of round {ply_round} is a win for P1')
            user_Ply.clear()
        elif (user_Ply[1] == choice[0] and user_Ply[0] == choice[-1]):
            print(fr'The result of round {ply_round} is a win for P2')
            user_Ply.clear()
        elif (user_Ply[0] == choice[-1] and user_Ply[0] == choice[1]):
            print(fr'The result of round {ply_round} is a win for P1')
            user_Ply.clear()
        elif (user_Ply[1] == choice[1] and user_Ply[0] == choice[-1]):
            print(fr'The result of round {ply_round} is a win for P2')
            user_Ply.clear()
        elif (user_Ply[0] == choice[1] and user_Ply[0] == choice[0]):
            print(fr'The result of round {ply_round} is a win for P1')
            user_Ply.clear()
        elif (user_Ply[1] == choice[0] and user_Ply[0] == choice[1]):
            print(fr'The result of round {ply_round} is a win for P2')
            user_Ply.clear()
        else:
            user_Ply.clear()
        if ply_round == 5:
            break
    print('------------------------------')
    print('Game over')
    print()

There is a lot of room for improvement in your code.
First, I'd like to address an unusual request you made:

Please don't recomend using functions.

Why not? They are a fundamental notion in programming, and can't really be avoided. Glossing over the fact that you already use a bunch of functions like print, input, append, etc., and assuming you are referring to functions that you define yourself in the code, it is still a puzzling request. Functions can make your code cleaner, easier to read, easier to maintain and more reusable, so why would you want to avoid them?
Take for example the part of the code where you ask for user input: the same code is copied and pasted twice. There are improvements to be made to that snippet. Implementing one these improvements would mean changing the code in two places. If it were encapsulated in a function, you would need to make that change only once, reducing the risk for errors.
Also, when reviewing your code, or when re-reading it yourself for further reference, encountering a properly named function is likely to be easier to process than what would effectively be the body of the function. I could see something like ask_for_input(player1) and focus on how the game move in handled, and then check out how you approach asking the user for input, independently from the previous logic. You could potentially reuse your ask_for_input function as is in future projects. Finally, you could then trivially replace the ask_for_input function with some sort of computer player if you want to expand this program.

As for the rest of the code, I won't provide a functional code, as there are already a lot of reviews on the site for "rock-paper-scissors" programs in Python. I'm sure you can find good, clean code that fits the bill.
However, I'll address a few design choices you made that can be improved upon, in no particular order.
Naming conventions
The PEP 8 Style Guide for Python Code recommends naming variables in lowercase snake_case, and constants in ALL_CAPS. Your variables and constants names are a mix of snake_case and CamelCase. While you may chose not to adhere to PEP 8 (although it's good practice to keep your code consistent with what is expected), at least pick a convention and stick with it.
PEP 8 is also a comprehensive style guide, and include cases that you may not even have thought about (like using a different style for constants, making the identifiable at first glance), so it is at the very least an interesting read.
Main loop
Most of your logic is enclosed in a while loop:
while True:
    ply_round += 1
    # ...
    if ply_round == 5:
        break

A while loop is clearly not the best fit here, as you effectively iterate over an incrementing index. A for loop would be functionally the same, while eliminating some overhead:
for ply_round in range(1, 6):
    # ...

Or better yet, use a named constant or a variable to specify how many rounds are played, so that you can see at first glance what the number means.
enumerate
You use enumerate a lot in your for loops. enumerate returns a tuple of (index, value), and you usually just use one of them. Instead of using enumerate, use for item in list if you only need the item, or for i in range(len(list)) if you only need the index.
Some times (although it is not your case here), you can't avoid using a throwaway variable. It is common practice to use _ in these cases, clearly showing that you don't need that variable.
Sanitizing inputs
When getting user input, you should check if the inputted value matches what the program expects. In your case, the program expects on of the values r, p, or s. If the user enters anything else, the program continues on and gives no output, while still incrementing the round counter.
This is made even worse because the prompts first ask for R, P or S, then for Rock, Paper or Scissors. The user has no way to know what the expected input is.
At the very least, you should change the prompts to ask for the correct value, and use .lower() on the inputs, so that the case doesn't matter. Then, if the value isn't what is expected, discard the value and ask again, instead of silently accepting wrong inputs.
At this point, you should really put the input code into a function, or else your program will get absolutely unreadable.
Backwards logic
Consider this piece of code:
for j, v in enumerate(choice):
    if choice[j] in ply_1:
        print(f'you choose {choice[j]}')

Ignoring the enumerate issue addressed earlier, what happens here is:

you loop over accepted inputs
check if the accepted input is in the actual input (which should be 1 character long)

It makes much more sense to do this the other way (check if the actual input is in the accepted range), and it's simpler too:
if ply_1 in choice:
    # do something

Winner determining logic
To determine which player wins, you basically check every possible case individually. That is a lot of code for a rather simple task. In fact, is is about on fourth of your code, and you only handle the most basic case of 2 players and 3 weapons. What if you wanted to improve your game to allow for more players or more weapons (think "rock-paper-scissors-lizard-spock")? Then it would become absurdly long.
Possible solutions can include a lookup table, a dictionary associating each weapon to the weapon it beats, implementing a Weapon class with comparison operators, or maybe other things.
At the very least, you can check for ties with if user_Ply[0] == user_Ply[1] instead of comparing both to multiple common values.
Using a list instead of multiple variables
I feel like two variables, named for example player_1_move and player_2_move, would be more readable and more suited than putting them both in a list.
Anti-cheat measures
Player 2 can see what move player 1 made, making it trivial for him to win every round.
I'm aware that this is a programming exercise and no-one wants to actually play rock-paper-scissors on a terminal, but clearing the console would simply make sense to me.


Loading icons in two different sizes I am loading 3000 individual icons at run time one of my controls uses large icons, the other uses small icons. This works however seems terribly inefficient. The only way I can get the icons to be available in the small/large size is to have multiple image lists and have to load the file twice into each list.

 public partial class Form1 : Form
{

    ImageList imageListSmall = new ImageList();
    ImageList imageListLarge = new ImageList();
    BackgroundWorker IconLoaderBGWorker = new BackgroundWorker();
    DirectoryInfo IconDir = new DirectoryInfo("icons");

    FileInfo[] IconFiles;

    public Form1()
    {

        InitializeComponent();

        // Setup Icon Lists
        imageListSmall.ImageSize = new Size(16, 16);
        imageListSmall.ColorDepth = ColorDepth.Depth32Bit;
        imageListLarge.ImageSize = new Size(32, 32);
        imageListLarge.ColorDepth = ColorDepth.Depth32Bit;

        // Setup Progress bar events and Icon Loader
        IconLoaderBGWorker.DoWork += new DoWorkEventHandler(bg_DoWork);
        IconLoaderBGWorker.WorkerReportsProgress = true;
        IconLoaderBGWorker.ProgressChanged += new ProgressChangedEventHandler(bg_ProgressChanged);
        IconLoaderBGWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);

        IconFiles = IconDir.GetFiles("*.png");
        int allFiles = IconFiles.Count();
        progressBar1.Maximum = allFiles;

    }

    private void bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
    }

    private void bg_DoWork(object sender, DoWorkEventArgs e)
    {
        int i = 0;

        foreach (FileInfo fileinfo in IconFiles)
        {
            imageListLarge.Images.Add(Path.GetFileNameWithoutExtension(fileinfo.Name), Image.FromFile(fileinfo.FullName));
            imageListSmall.Images.Add(Path.GetFileNameWithoutExtension(fileinfo.Name), Image.FromFile(fileinfo.FullName));
            IconLoaderBGWorker.ReportProgress(++i);
            Application.DoEvents();
        }

    }

    private void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        object result = e.Result;
        progressBar1.Dispose();
    }
}

I guess I was able to figure it out, not sure how I missed it but by simply adjusting the bg_DoWork the application loads twice as fast, as it only creates an Image once instead of twice.

    private void bg_DoWork(object sender, DoWorkEventArgs e)
    {
        int i = 0;
        Image tempImage;
        foreach (FileInfo fileinfo in IconFiles)
        {
            tempImage = Image.FromFile(fileinfo.FullName);
            imageListLarge.Images.Add(Path.GetFileNameWithoutExtension(fileinfo.Name), tempImage);
            imageListSmall.Images.Add(Path.GetFileNameWithoutExtension(fileinfo.Name), tempImage);
            IconLoaderBGWorker.ReportProgress(++i);
            Application.DoEvents();
        }
    }


Grouping comma-separated lines together I have comma-delimited files like these, where the first field is sorted in increasing order:

Case 1 ( 1st file ) :

abcd,1
abcd,21
abcd,122
abce,12
abcf,13
abcf,21

Case 2 ( and another file like this ) :

abcd,1
abcd,21
abcd,122

What I want to do is convert the first file to like this :

abcd 1,21,122
abce 12
abcf 13,21

And similarly, for the second file like this :

abcd 1,21,122

Now, I wrote a very ugly code with a lot of if's to check whether the next line's string before the comma is same as current line's string so, if it is then do ....

It's so badly written that, I wrote it myself around 6 months back and it took me around 3-4 minutes to understand why I did what I did in this code.
Well in short it's ugly, in case you would like to see, here it is ( also there's a bug currently in here and since I needed a better way than this whole code so I didn't sort it out, for the curious folks out there the bug is that it doesn't print anything for the second case mentioned above and I know why ).

def clean_file(filePath, destination):
    f = open(filePath, 'r')
    data = f.read()
    f.close()
    curr_string = current_number = next_string = next_number = ""
    current_numbers = ""
    final_payload = ""
    lines = data.split('\n')[:-1]
    for i in range(len(lines)-1):
        print(lines[i])
        curr_line = lines[i]
        next_line = lines[i+1]
        curr_string, current_number = curr_line.split(',')
        next_string, next_number = next_line.split(',')
        if curr_string == next_string:
            current_numbers += current_number + ","
        else:
            current_numbers += current_number    # check to avoid ',' in the end
            final_payload += curr_string + " " + current_numbers + "\n"
            current_numbers = ""
    print(final_payload)
    # For last line
    if curr_string != next_string:
        # Directly add it to the final_payload
        final_payload += next_line + "\n"
    else:
        # Remove the newline, add a comma and then finally add a newline
        final_payload = final_payload[:-1] + ","+next_number+"\n"
    with open(destination, 'a') as f:
        f.write(final_payload)

Any better solutions?

To solve the grouping problem, use itertools.groupby.
To read files with comma-separated fields, use the csv module.
In almost all cases, open() should be called using a with block, so that the files will be automatically closed for you, even if an exception occurs within the block:

with open(file_path) as in_f, open(destination, 'w') as out_f:
    data = csv.reader(in_f)
    # code goes here

filePath violates Python's official style guide, which recommends underscores, like your curr_line.


Implementing a stack and using it to print alternate elements in reverse Challenge:

  Implement a stack interface.

Specifications:

  The interface should have ‘push’ and ‘pop’ functions.
  Your task is to ‘push’ a series of integers and then ‘pop’ and print every alternate integer.
  Your program should accept a file as its first argument.
  The file contains a series of space delimited integers, one per line.
  Print out every alternate space delimited integer, one per line.

Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;

public class Stack<T> {
    LinkedList<T> list = new LinkedList<>();

    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File(args[0]));

        while (input.hasNextLine()) {
            System.out.println(
                retrieveAlternates(input.nextLine().split("\\s+"))
            );
        }
    }

    private static String retrieveAlternates(String[] input) {
        Stack<Integer> stack = new Stack<>();
        StringBuilder result = new StringBuilder();

        for (String s : input) {
            stack.push(Integer.parseInt(s));
        }

        for (int i = 0; i < input.length; i++) {
            if ((i & 1) == 0) {
                result.append(' ').append(stack.pop());
            } else {
                stack.pop();
            }
        }

        return result.substring(1);
    }

    public void push(T t) {
        list.add(t);
    }
    public T pop() {
        return list.removeLast();
    }
}

Tests:

@Test
public void test1 {
    assertEquals("4 2", Stack.retrieveAlternates("1 2 3 4"));
}

@Test
public void test2 {
    assertEquals("4 -2", Stack.retrieveAlternates("10 -2 3 4"));
}

I've never really had an "Implement X" challenge, before. This passed, but did I effectively do what was expected? Could it be better?

Since you passed this may be a moot point,
but if this was an interview question,
when the spec says "implement an interface",
I would expect to see an interface:

public interface Stack<T> {

    void push(T item);

    T pop();
}

And an implementation:

public class StackImpl<T> implements Stack<T> {

    LinkedList<T> list = new LinkedList<>();

    @Override
    public void push(T item) {
        list.add(item);
    }

    @Override
    public T pop() {
        return list.removeLast();
    }
}

It's better to separate the interface, the implementation, and the runnable.
So the code of the main program,
and the retrieveAlternates method doesn't belong in a Stack class.

Also note that you don't need a stack at all to solve the problem.
You can just reference the elements of the input by the right indexes,
and you don't need to convert them to integers either:

static String retrieveAlternates(String[] input) {
    StringBuilder result = new StringBuilder();

    for (int i = 0; i < input.length; i++) {
        if ((i & 1) == 0) {
            result.append(' ').append(input[input.length - i - 1]);
        }
    }

    return result.substring(1);
}

I know this is cheating,
but actually,
you're already cheating when you implement a Stack interface using a LinkedList...
At an interview I would expect that you'd have to implement an array-backed stack or something,
without using the wonderful high level elements of the JDK.

Unit testing

Oddly, your unit tests have syntax errors: () missing from test1(),
and both tests call a method whose signature doesn't exist.
It's as if you've never run these tests,
just typed them up here because you know I would pick on not having any tests...

Also, test1 and test2 are not good names:
it's best when tests have descriptive names,
so that they are easier to understand,
both when reading the code later,
and when something fails and reading the error messages.

I would propose this naming style:

@Test
public void test_1_2_3_4_gives_4_2() {
    assertEquals("4 2", Solution.retrieveAlternates("1 2 3 4".split("\\s+")));
}

@Test
public void test_10_m2_3_4_gives_4_m2() {
    assertEquals("4 -2", Solution.retrieveAlternates("10 -2 3 4".split("\\s+")));
}

The splitting, necessitated by the method under test is tedious,
using new String[]{ ... } in each test case would also be tedious,
so I'd suggest to simplify using a helper method:

void assertAlternates(String expected, String input) {
    assertEquals(expected, Solution.retrieveAlternates(input.split("\\s+")));
}

@Test
public void test_1_2_3_4_gives_4_2() {
    assertAlternates("4 2", "1 2 3 4");
}

@Test
public void test_10_m2_3_4_gives_4_m2() {
    assertAlternates("4 -2", "10 -2 3 4");
}

And I suggest adding some more potential corner cases:

@Test
public void test_1_gives_1() {
    assertAlternates("1", "1");
}

@Test
public void test_1_2_gives_2() {
    assertAlternates("2", "1 2");
}

Note that I'm not following camelCase for test method naming.
I'm not aware of a standard for this,
and static code analysis tools like Sonar don't complain about this kind of naming,
even though I'm using the most strict rule set.

Keep in mind that unlike regular code,
it's acceptable (and even recommended) to use long names for test methods.
And these names tend to get long,
snake_case is far more readable (in my opinion) than camelCase.


HackerEarth problem : number of occurrences of a number in the array I have written a solution to Memorise me problem on Hacker Earth but it takes a lot of memory space and time limit exceeds in the last test case.

The first line of input will contain \$N\$, an integer, which is the total number of numbers shown to your team.

The second line of input contains \$N\$ space separated integers.

The third line of input contains an integer \$Q\$, denoting the total number of integers.

The Next \$Q\$ lines will contain an integer denoting an integer, \$Bi\$, for which you have to print the number of occurrences of that number (\$Bi\$) in those \$N\$ numbers on a new line.

If the number \$Bi\$ isn’t present then print NOT PRESENT on a new line.

Constraints

\$1 \le N \le 105,
0 \le Bi \le 1000,
1 \le Q \le 1055\$

This is my code :

public static void main(String args[]) throws Exception {

    // BufferedReader
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String noOfElements = br.readLine();
    int n = Integer.parseInt(noOfElements);
    int i = 0;

    String[] numberArray = br.readLine().split(" ");

    String noOfQueries = br.readLine();
    int q = Integer.parseInt(noOfQueries);

    String[] queries = new String[q];

    for (i = 0; i < q; i++) {
        String query = br.readLine();
        String queryNumber = query.trim();
        queries[i] = queryNumber;
    }

    for (i = 0; i < queries.length; i++) {
        int count = 0;
        for (int j = 0; j < n; j++) {
            if (queries[i].equals(numberArray[j])) {
                count++;
            }
        }
        if (count == 0) {
            System.out.println("NOT PRESENT");
        } else {
            System.out.println(count);
        }
    }

}

You can maintain a HashMap where key will be the number and value will be its frequency.


Controller action to process orders and payments I'm trying to reduce the if statements and simplify this create action.

def create
@order = Order.create_from_result(JSON.parse(params['order']), JSON.parse(params['customer']))

# Ensure order saves before processing payment
if @order.persisted?

  # Braintree transaction
  result = @order.make_payment(params[:payment_method_nonce])

  if result.success?
    @order.paid!
    @order.process!
    render :json => { :status => 200 }
  else
    p "#Error: #{result.message}"
    render :json => { :error => "#{result.message}" }
  end

else
  p "Error: Order did not save successfully"
  render :json => { :error => "Something went wrong. Don't worry, no transaction was made." }
end
end

I thought about moving most of this logic to a single @order.process! call, but then I'm not sure of the best way to handle the Braintree transaction result & return any errors.

Basically, three things take place in this action for an @order:

Order is created from JSON result
Order payment is made
Order is processed (order data is crunched and sent to supplier)

I would suggest using a service object. I would like to see what others think about this. It looks like there's too much going on for the controller.

The controller should be responsible for execution and value return. The model for processing the object. The service for wiring up the object and giving it prepared params to do its job.

This is not tested, but just to give you an idea. I would go further and condense the paid! and process! methods in the model so that the service just receives an error or an OK to give back to the controller.

def create
  @order = OrderCreationService.new(params).process

  if @order.processed?
    render json: { status: 200 }
  else
    render json: { error: @order.errors }
  end
end

Your service would look something like this:

require 'json'

class OrderCreationService
  attr_reader :order_params, :customer_params, :payment_method_nonce, :errors

  def initialize(params)
    @order_params = JSON.parse(params['order'])
    @customer_params = JSON.parse(params['customer'])
    @payment_method_nonce = JSON.parse(params['payment_method_nonce'])
    @errors = []
  end

  def process
    order = Order.create_from_result(order_params, customer_params)

    if order.persisted?
      result = order.make_payment(payment_method_nonce)

      if result.success?
        order.process!
      else
        errors << result.message
      end
    else
      errors << order.errors
    end

    self
  end

  def processed?
    errors.none?
  end
end

Some would argue that a service object adds a needless complication. They may have a point. I think it depends on each use case.


Choosing a CSS class based on an HTTP status code I was having a discussion with my coworker about a function that returns either an empty string, or a string of a css class. The function is passed an object which has an HTTP status code, and then depending on that statusCode, it returns a value. We couldn't agree which is cleaner.

He wanted the function written as so:

function getCssClass(options) {
  var statusCodeCssClass = '';
  var statusCode = parseInt(options.statuscode, 10);

  if ((statusCode >= 100 && statusCode < 200) || statusCode >= 400) {
    statusCodeCssClass = 'text-danger';
  }
  return statusCodeCssClass;
};

And I wanted it written as so:

function getCssClass(options) {
  var statusCode = parseInt(options.statuscode, 10);
  if ((statusCode >= 100 && statusCode < 200) || statusCode >= 400) {
    return 'text-danger';
  }
  return '';
};

The main difference is that I don't think the initial empty variable should be there, and he does. His argument is that the variable makes it easier to read, and my argument is that the variable obfuscates the function.

I know it's splitting hairs, but I was unable to find an answer in the Clean Code book or on Google about unnecessary variable declarations.

Can someone tell me why one is better than the other?

One very important principle of modern software design is that mutability should be minimised. The first case needlessly introduces mutability by potentially modifying the value of statusCodeCssClass. Thus I'd argue it's bad practice to write code like this, regardless of whether it's easier to read (which is a completely subjective claim as both are simple and easy-to-read).

However, the second approach ignores the fact that JavaScript supports an idiomatic solution to to a "test a value and return one of two results based on that test" problem: the ternary operator. This can be used in this situation to yield a third solution that makes better use of language features:

function getCssClass(options) {
    var statusCode = parseInt(options.statuscode, 10);
    return (statusCode >= 100 && statusCode < 200) || statusCode >= 400) ? 'text-danger' : '';
}

However, the code could be further improved by respecting the single responsibility principle. The function should only have one responsibility. Currently, it has two: it extracts the status code from options and it returns a CSS value based on that code. By splitting out obtaining the status code into another function, this one becomes more focused.


Task Scheduler for small interval and one number of start Scenario:

I want a task scheduler that enables my application to schedule some tasks in small time interval. I want to use it in my socket server application. For example, when the user connects to the socket application schedule some task in 15 seconds to disconnect user if no actions were made.

Queuing task for specific time
Ability to stop scheduled jobs
Running jobs in separate thread

So, I've decided to create my own Task Schedule. It can schedule tasks. It use System.Timers.Timer to find tasks to run. I want you to review my decision, may be solution has architecture errors etc.

public abstract class ScheduleJob
{
    //Date when task must be executed
    public DateTime DateTrigger { get; set; }

    //Task Id (for search and cancel)
    public string TaskId { get; set; }

    //For logs
    public abstract string TaskName { get; }

    //Main task method
    protected abstract void OnStart();

    //Default task class delay (for example 15 seconds)
    public abstract TimeSpan ScheduleTo { get; }

    private bool _isRunning = false;

    public void Start()
    {
        _isRunning = true;

        var s = new Stopwatch();
        s.Start();

        try
        {
            //run task in separated thread
            Task.Factory.StartNew(OnStart).ContinueWith(t =>
            {
                s.Stop();
                _isRunning = false;

                //if (t.Exception != null)
                //{
                //TODO work with exceptions
                //}
            });
        }
        catch (Exception ex)
        {
            //TODO work with exceptions
        }
    }
}

Manager to work with jobs

public sealed class ScheduleManager : IDisposable
{
    private static ScheduleManager _instance = new ScheduleManager();

    public static ScheduleManager Instance { get { return _instance; } }

    private List<ScheduleJob> _jobs;
    private object _lock = new object();

    private Timer _timer;

    private ScheduleManager()
    {
        _jobs = new List<ScheduleJob>();
        _timer = new Timer();
        _timer.Interval = 1000;
        _timer.Elapsed += TimerOnElapsed;
        _timer.Start();
    }

    private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
    {
        lock (_lock)
        {
            var tasks = _jobs.Where(x => x.DateTrigger <= DateTime.Now).ToList();

            foreach (ScheduleJob scheduleJob in tasks)
            {
                scheduleJob.Start();
                _jobs.Remove(scheduleJob);
            }
        }
    }

    public void Schedule(ScheduleJob job)
    {
        lock (_lock)
        {
            job.DateTrigger = DateTime.Now + job.ScheduleTo;
            _jobs.Add(job);
        }
    }

    public void Remove(string taskId)
    {
        lock (_lock)
        {
            _jobs.RemoveAll(x => x.TaskId.Equals(taskId, StringComparison.OrdinalIgnoreCase));
        }
    }

    public void Dispose()
    {
        if (_timer != null)
        {
            _timer.Stop();
            //todo stop or cancel jobs
            _timer = null;
        }
    }
}

Example of job UserShouldSendAuthTokenAfterConnectToSocketTask

public class UserShouldSendAuthTokenAfterConnectToSocketTask : ScheduleJob
{
    private string _connectionId;

    public UserShouldSendAuthTokenAfterConnectToSocketTask(string connectionId)
    {
        _connectionId = connectionId;
        TaskId = GenerateTaskId(_connectionId);
    }

    public static string GenerateTaskId(string connectionId)
    {
        return $"UserShouldSendAuthTokenAfterConnectToSocketTask_{connectionId}";
    }

    public override string TaskName { get { return "User should auth to socket"; } }

    protected override void OnStart()
    {
        SocketServer.Instance.SendMessage(new UserShouldSendAuthTokenAfterConnectToSocket(), _connectionId);
    }

    public override TimeSpan ScheduleTo
    {
        get
        {
            return TimeSpan.FromSeconds(GameConfig.SecondsUserShouldSendAuthTokenAfterConnectToSocket);
        }
    }
}

Good work. A few comments and questions.

In SchduleJob class, I think that DateTrigger and TaskId need to be defined as internal and the SchduleManager only need to set them. If they will be public, the concrete class may set them to some value and the manager will override it in the Schedule method.
I think you need to constraint the TaskId to be unique and the manager only set it with a unique validation. For user define name\id you the TaskName property.
According to section 2, in the Remove method, replace RemoveAll by Remove.
Consider to change the type to long\int instead string, I don't talk about performance but about meaning although string is also make sense.
If you prefer to use string for the id, use string.CompareOrdinal() for the comprasion.
I think all the logging (add, remove, start, stop, error) need to be in the manager. The ScheduleJob need to be dedicated to the job. It can handle exception if you want, but the manager need to log it also.
Make the ScheduleManager IDisposable is dangerhere. Its a singleton and no body going to use it with using statement, but if somebody will do it, it make a problem because your timer will be disposable...


Check whether a list of list of string fits a regex efficiently I have the following structure for my object:

Word (Object)

Word (String)
List<Symbol>

Symbol (Object)

Symbol (String)
List<SymbolChoice>

SymbolChoice (Object)

Symbol (String)

The background of this is that this is processed OCR output and I want to force a word to match a certain regex. If it cannot find a match, it should return an empty List<SymbolChoice>, otherwise it should return all List<SymbolChoice> that match the specified regex.

Example:

Found word: "1o0"
Symbols: "1", "o" and "0"
Choices of "1": "1"
Choices of "o": "o", "0"
Choices of "0": "0"

When forcing this word to abide regex "\\d{3}", it has to return [["1", "0", "0"]], here I am denoting the SymbolChoice objects as strings.

I have a solution, however it is not fast enough, more details after the method:

public List<List<SymbolChoice>> forceFitRegex(final String regex) {
    Objects.requireNonNull(regex, "regex");

    if (getSymbols().size() <= 1) {
        return new ArrayList<List<SymbolChoice>>();
    }

    int combinations = 1;
    for (Symbol symbol : getSymbols()) {
        combinations *= symbol.getSymbolChoices().size();
    }
    System.out.println("Combinations: " + combinations);

    List<List<SymbolChoice>> listOfSymbolChoices = new ArrayList<List<SymbolChoice>>();
    for (SymbolChoice symbolChoice : getSymbols().get(0).getSymbolChoices()) {
        List<SymbolChoice> symbolChoices = new ArrayList<SymbolChoice>();
        symbolChoices.add(symbolChoice);
        listOfSymbolChoices.add(symbolChoices);
    }

    int i = 1;
    while (i < getSymbols().size()) {
        List<List<SymbolChoice>> listOfSymbolChoicesCopy = new ArrayList<List<SymbolChoice>>(listOfSymbolChoices);
        for (SymbolChoice symbolChoice : getSymbols().get(i).getSymbolChoices()) {
            for (List<SymbolChoice> symbolChoicesCopy : listOfSymbolChoicesCopy) {
                List<SymbolChoice> symbolChoices = new ArrayList<SymbolChoice>(symbolChoicesCopy);
                symbolChoices.add(symbolChoice);
                listOfSymbolChoices.add(symbolChoices);
            }
        }
        i++;
    }

    Pattern pattern = Pattern.compile(regex);
    ListIterator<List<SymbolChoice>> symbolChoicesListIterator = listOfSymbolChoices.listIterator();
    while (symbolChoicesListIterator.hasNext()) {
        List<SymbolChoice> symbolChoices = symbolChoicesListIterator.next();
        StringBuilder stringBuilder = new StringBuilder();
        for (SymbolChoice symbolChoice : symbolChoices) {
            stringBuilder.append(symbolChoice.getSymbol());
        }
        if (!pattern.matcher(stringBuilder.toString()).matches()) {
            symbolChoicesListIterator.remove();
        }
    }
    return listOfSymbolChoices;
}

Let n be the number of combinations possible, calculated as the product of the size of all symbol choices. In my example that would be 1 * 2 * 1 = 2.

For n <= 288 I observe it to run very quick, however with for example n = 5760 it takes a few minutes to process. I also spot here another case of n = 311040 and have a feeling that it will never finish.

What can I do to solve my problem efficiently? I need to stick to Java 6 for Android compatibility.

(Bonus points if someone can calculate the asymptotic time my algorithm takes)

Bonus points if someone can calculate the asymptotic time my algorithm takes.

Too much. It's exponential, as you're generating the whole candidate set. Even the improvement by rolfl doesn't change it.
You could do much better by analyzing the regex. For example "\\d{3}" will never match anything starting with a letter and you could cut off many possibilities. However, doing this in general is pretty complicated.
There's a method which might do this for you: hitEnd. I'm not sure if it does the right thing, but I guess so:

Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.
When this method returns true, then it is possible that more input would have changed the result of the last search.

So you could test you incomplete candidates against the regex and possibly save yourself the work with expanding them.


Help optimizing this query with multiple where exists In the application I'm building, the user is able to define 'types' where each 'type' has a set of 'attributes'.

The user is able to create instances of products by defining a value for each attribute the product's type has.

A pic of the schema:

I'm creating the query where the user specifies the attributes values and the product type and with that I should return all the product id's that meets the query.

The problem I see in my query is that I'm performing a whole select * from attributes_products ... for each attribute that the product's type has.

Is there a way to optimize this?
If I create an index in the column attributes_products.product_id would this query be actually optimal?

Example of a query where I'm looking for a product whose type has 3 attributes:

select p.id
from Products as p
where
exists(
    select * from attributes_products
    where
        product_id = p.id AND
        attribute_id = 27 AND
        value = 'some_value'
) AND
exists(
    select * from attributes_products
    where
        product_id = p.id AND
        attribute_id = 28 AND
        value = 'other_value'
) AND
exists(
    select * from attributes_products
    where
        product_id = p.id AND
        attribute_id = 29 AND
        value = 'oother_value'
)

Many thanks.

Conclusions

So, Gareth Rees (selected answer) proposed another solution which involves multiple Joins.
Here is the explanation of its query (done by PGAdmin):

This is the explanation of the original query:

I believe that the selected answer is slightly faster, but consumes a lot more memory (because of the triple join).
I believe that my original query is slightly slower (very slightly, since there's an index on the attributes_products table) but a lot more efficient in memory.

SQL allows you to join the same table multiple times, so what you need here is:

SELECT p.id FROM products AS p
JOIN attributes_products AS ap1
  ON ap1.product_id = p.id AND ap1.attribute_id = 27 AND ap1.value = '...'
JOIN attributes_products AS ap2
  ON ap2.product_id = p.id AND ap2.attribute_id = 28 AND ap2.value = '...'
JOIN attributes_products AS ap3
  ON ap3.product_id = p.id AND ap3.attribute_id = 29 AND ap3.value = '...'

Here's the toy MySQL database that I'm using to answer this question:

CREATE TABLE products (
    id INTEGER PRIMARY KEY AUTO_INCREMENT
);
CREATE TABLE attributes_products (
    product_id INTEGER NOT NULL,
    attribute_id INTEGER NOT NULL,
    value CHAR(40)
);
CREATE INDEX ap_product ON attributes_products (product_id);
CREATE INDEX ap_attribute ON attributes_products (attribute_id);

INSERT INTO products VALUES (1);
INSERT INTO products VALUES (2);
INSERT INTO attributes_products VALUES (1, 27, 'a');
INSERT INTO attributes_products VALUES (1, 28, 'b');
INSERT INTO attributes_products VALUES (1, 29, 'c');

With my query above, MySQL reports the following query plan:

+----+-------------+-------+--------+-------------------------+--------------+---------+---------------------+------+--------------------------+
| id | select_type | table | type   | possible_keys           | key          | key_len | ref                 | rows | Extra                    |
+----+-------------+-------+--------+-------------------------+--------------+---------+---------------------+------+--------------------------+
|  1 | SIMPLE      | ap1   | ref    | ap_product,ap_attribute | ap_attribute | 4       | const               |    1 | Using where              |
|  1 | SIMPLE      | ap2   | ref    | ap_product,ap_attribute | ap_attribute | 4       | const               |    1 | Using where              |
|  1 | SIMPLE      | ap3   | ref    | ap_product,ap_attribute | ap_attribute | 4       | const               |    1 | Using where              |
|  1 | SIMPLE      | p     | eq_ref | PRIMARY                 | PRIMARY      | 4       | temp.ap3.product_id |    1 | Using where; Using index |
+----+-------------+-------+--------+-------------------------+--------------+---------+---------------------+------+--------------------------+

See the MySQL documentation for an explanation of the EXPLAIN output.

This looks better than the plan for the OP's query:

+----+--------------------+---------------------+-------+-------------------------+--------------+---------+-------+------+--------------------------+
| id | select_type        | table               | type  | possible_keys           | key          | key_len | ref   | rows | Extra                    |
+----+--------------------+---------------------+-------+-------------------------+--------------+---------+-------+------+--------------------------+
|  1 | PRIMARY            | p                   | index | NULL                    | PRIMARY      | 4       | NULL  |    2 | Using where; Using index |
|  4 | DEPENDENT SUBQUERY | attributes_products | ref   | ap_product,ap_attribute | ap_attribute | 4       | const |    1 | Using where              |
|  3 | DEPENDENT SUBQUERY | attributes_products | ref   | ap_product,ap_attribute | ap_attribute | 4       | const |    1 | Using where              |
|  2 | DEPENDENT SUBQUERY | attributes_products | ref   | ap_product,ap_attribute | ap_attribute | 4       | const |    1 | Using where              |
+----+--------------------+---------------------+-------+-------------------------+--------------+---------+-------+------+--------------------------+

But results will vary from one database to another: a good query planner might be able to make something efficient out of the OP's query.


Merging Two Sorted Lists in Python In Linear Time I am trying to implement a merge of two sorted lists of integers in Python using only the basic list abstract data type operations. That is, I do not want to use sorted() which comes with Python.

Could someone tell me if this code is alright? Also, am I correct to understand that it is linear to the core? That is, it uses no Python operation that is non-linear in time?

 def mergeSortedLists(list1, list2):
     list3 = []
     while list1 and list2:
         if list1[len(list1) - 1] > list2[len(list2) - 1]:
             list3.append(list1.pop())
         else:
             list3.append(list2.pop())
     return list3 + list1 + list2

Correctness

First of all, your merging code is not correct. If you have list1 = [1, 2, 3] and list2 = [4, 5, 6], the result would be [6, 5, 4, 1, 2, 3].

Assuming, you are up to [1, 2, 3, 4, 5, 6], you should be comparing the first elements of the lists. The problem with that is that "pop" from the left is an expensive operation for a regular Python list. Switching to the collections.deque double-ended queue would solve it - popleft() is O(1).

Fixed version:

from collections import deque

def merge_sorted_lists(left, right):
    """
    Merge sort merging function.
    TODO: Improve, add examples."""
    result = deque()

    left = deque(left)
    right = deque(right)

    while left and right:
        if left[0] > right[0]:
            result.append(right.popleft())
        else:
            result.append(left.popleft())
    return result + left + right

Time Complexity Analysis (for your "incorrect" version)

You are operating Python lists, according to the Time Complexity page:

the "get length" operation is O(1) (even though you can use -1 in place of len(list1) - 1 and len(list2) - 1)
the "pop from the right" operation is O(1)
the "append to the right" operation is O(1)

Which leads to overall complexity as O(N + M) where N is the length of the list1 and M - the length of the list list2.

Stylistic issues:

as per PEP8 guide, use 4 spaces for indentation
the function name should be merge_sorted_lists according to PEP8 variable naming guidelines
list1 should be better called left, list2 - right, list3  - result for clarity purposes
missing docstring explaining what function does


4 sum challenge (part 2) This is a continued discussion from (4 sum challenge) by return count only.

  Problem

  Given four lists A, B, C, D of integer values, compute how many tuples
  (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

  To make problem a bit easier, all A, B, C, D have same length of N
  where \$0 \le N \le 500\$. All integers are in the range of \$-2^{28}\$ to \$2^{28} - 1\$
  and the result is guaranteed to be at most \$2^{31} - 1\$.

  Example:

  Input:

A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

  Output:

2

  Explanation:

  The two tuples are:

  (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
  (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

I'm wondering if there are any ideas to have a solution less than \$O(n^2)\$ time complexity.

Source code in Python 2.7,

from collections import defaultdict
def four_sum(A, B, C, D):
    sum_map = defaultdict(int)
    result = 0
    for i in A:
        for j in B:
            sum_map[i+j] += 1
    for i in C:
        for j in D:
            if -(i+j) in sum_map:
                result += sum_map[-(i+j)]

    return result

if __name__ == "__main__":
    A = [1, 2]
    B = [-2, -1]
    C = [-1, 2]
    D = [0, 2]
    print four_sum(A,B,C,D)

I’m not sure I can get it any better than \$O(n^2)\$, but I would point you towards the itertools module as a way to tidy up your code by reducing the number of nested for loops. Like so:

def four_sum(A, B, C, D):
    sums = defaultdict(int)
    result = 0
    for (a, b) in itertools.product(A, B):
        sums[a + b] += 1
    for (c, d) in itertools.product(C, D):
        result += sums[-(c + d)]
    return result

I’ve also tweaked the names of some of the variables to make the code easier to follow, and changed it so it only has to compute (c+d) once.


Determining if a pair exists in a large sorted array I'm doing practice interview questions from here. Here is the one I am currently on - if you are given a very large sorted int array, then check of there exists a pair.

public static int sumOfTwoExists(int[] largeArray, int a, int b) {
    A: for(int count = 0; count < largeArray.length; count ++) {
        for(int counter = count + 1; counter < largeArray.length; counter ++) {
            if(largeArray[count] + largeArray[counter] == a + b) {
                return 1;
            } else if(largeArray[count] + largeArray[counter] > a + b) {
                break A;
            }
        }
    }
    return -1;
}

I tested this code and it works. What I am having trouble with is the next part of the question - he asked if there's an optimal method \$O(1)\$ to find the match for the previous question?

How would you optimize this code so that the match is a constant time operation? I still don't how that would be done because it looks like iteration is still required.

\$O(1)\$ is impossible indeed. Your solution is \$O(n^2)\$, because you ignore the most important part of the question: the array is sorted.

The \$O(n)\$ solution is to set a pair of iterators to the beginning and the end of the array. Then if a sum of their values is less than target, advance the beginning; if it greater, retreat the end. Keep going until they meet (or a target is found).


Parsing Websites and transferring Data between Objects I have a DiningHall class that has the 3 properties: openingTime, closingTime, and nextMealOpeningTime, and I need to set these NSDate properties from the data from this website.

Each DiningHall object corresponds to a particular meal. For example, there is a separate "De Neve" dining hall object  for breakfast, lunch, and dinner.

As an example, if I have a De Neve hall object corresponding to "Lunch", and the times were

  breakfast (9-11) lunch (12-2) dinner (5-8)

then openingTime is 12pm, closingTime is 2pm, and nextMealOpeningTime is 5pm.

The general algorithm is:

given a particular meal:

for each hall

    in data, find row corresponding to hall

    find column corresponding to current meal

    parse text, convert toNSDate

    pass 3 NSDate's to DiningHall as array

I'm using an open source DOM parser, and below is the code for extracting the text once I obtain the correct row.  Specific concerns are dealing with "Closed" meals and a better way to pass data to DiningHall class, but any optimizations will help.

- (NSArray*) getHourDataForRow:(TFHppleElement*)row Meal:(NSString*)meal {

    NSArray *meals = [row childrenWithTagName:@"td"];
    NSArray *mealNames = [NSArray arrayWithObjects:@"breakfast", @"lunch", @"dinner", nil];
    int index = [mealNames indexOfObject:meal]+1;
   TFHppleElement *cell = meals[index];
NSArray *strong = [cell childrenWithTagName:@"strong"];

NSMutableArray *retArr = [NSMutableArray array];

NSString *opening = [strong[0] firstChildWithTagName:@"text"].content;
NSDate *openingAsDate = [self dateFromString:opening];
if (openingAsDate){
    [retArr addObject:openingAsDate];
    NSString *closing = [strong[1] firstChildWithTagName:@"text"].content;
    [retArr addObject:[self dateFromString:closing]];
}
else{
    [retArr addObject:[NSNull null]];
    [retArr addObject:[NSNull null]];
}
    if (index +1 <= 3) {

        TFHppleElement *nextCell = meals[index+1];
        NSArray *strong1 = [nextCell childrenWithTagName:@"strong"];
        NSString* nextOpening = [strong1[0] firstChildWithTagName:@"text"].content; //strong[0] is opening time, don't need closing time from next cell
        [retArr addObject:[self nextOpening.content]];
    }
    else // nextMealOpeningTime is always nil for dinner
        [retArr addObject:[NSNull null]];

    return retArr;

 }

- (NSDate*) dateFromString:(NSString*)time {

    if ([time isEqualToString:@"CLOSED"])
        return nil;

        NSArray *digits = [time componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];

        int hour = [digits[0] intValue];
        hour+= (([time rangeOfString:@"pm"].location == NSNotFound) ? 0:12) ; //add 12 for pm
        int minutes = [digits[1] intValue];
        //format nsdate
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *components = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit ) fromDate:[NSDate date]];
        [components setHour:hour];
        [components setMinute:minutes];
        return [calendar dateFromComponents:components];

}

In DiningHall class

- (void) setHoursFromData:(NSArray*)data {

    if (data[0] != [NSNull null] && data[1] != [NSNull null]){
    _openingTime = data[0];
    _closingTime = data[1];

    }

    if (data[2] != [NSNull null])
    _nextOpeningTime = data[2];

}

For now, I will avoid commenting too much on - (NSArray*) getHourDataForRow:(TFHppleElement*)row Meal:(NSString*)meal as I think the real answer here is to look into NSXMLParser and see if that will work for you.  Other than that, for now I'll simply comment that your spacing is inconsistent and you should work in cleaning that up to make the code more readable.

I will, however, comment on dateFromString:

- (NSDate*) dateFromString:(NSString*)time {

    if ([time isEqualToString:@"CLOSED"])
        return nil;

        NSArray *digits = [time componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];

        int hour = [digits[0] intValue];
        hour+= (([time rangeOfString:@"pm"].location == NSNotFound) ? 0:12) ; //add 12 for pm
        int minutes = [digits[1] intValue];
        //format nsdate
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *components = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit ) fromDate:[NSDate date]];
        [components setHour:hour];
        [components setMinute:minutes];
        return [calendar dateFromComponents:components];

}

First of all, you left brackets off of your if statement.  This in combination with the awkward indentation leaves the code quite confusing.  Despite being optional, curly braces should never be omitted.

The rest of the method however.... can be completely replaced.  There's a class called NSDateFormatter which is made specifically for converting NSDate objects to NSString objects and vice versa.

First, we need this link.  This lets us know what our date format string should look like.  We have hours without a leading zero and in 12-hour format, minutes, we have minutes, and we have an am/pm symbol.

So our format string will look like this:

@"h:mma"

Our AM symbol is @"am" and our PM symbol is @"pm".  Now we have all the information we need to create our NSDateFormatter object:

- (NSDate*) dateFromString:(NSString*)time {
    if ([time isEqualToString:@"CLOSED"]) {
        return nil;
    } else {
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"h:mma"];
        [df setAMSymbol:@"am"];
        [df setPMSymbol:@"pm"];

        return [df dateFromString:time];
    }
}


Rock-Paper-Scissors-Lizard-Spock C++ Pogram I'm writing the C++ program that involves a twist on Rock, Paper, Scissors. How the added Lizard and Spock affect the game is very simple and you could look it up if you want, but its not needed as I'm 99% sure my issue lies with the formatting of my if-else statements.
In every iteration, no matter what configuration the computer or the user chooses, the outcome is always the same - i.e. "You win! :)". Even in the cases where the user should have tied, or the user should have lost. If you are experienced, you will probably very easily see where I am messing up, please take a look. I apologize for the confusing curly braces but inputting my code was being very finnicky so I had to add random indents to make it format.
#include <iostream>
int main(){

srand(time(NULL));
int computer = rand() % 5 + 1;

int user = 0;

std::cout << "=============================================\n";
std::cout << "Rock    Paper    Scissors    Spock    Lizard!\n";
std::cout << "=============================================\n";
std::cout << "1) Rock\n";
std::cout << "2) Paper\n";
std::cout << "3) Scissors\n";
std::cout << "4) Lizard\n";
std::cout << "5) Spock\n";
std::cout << "\n";
std::cout << "Shoot!\n";

std::cin >> user;
std::cout << "Computer chose: " << computer << "\n";

if(user == 1){
if(computer == 3 || 4){
  std::cout << "You win! :)\n";
}
else if(computer == 1){
  std::cout << "You tied! :/\n";
}
else{
  std::cout << "Computer wins! :(\n";
}
    }
else if(user == 2){
if(computer == 1 || 5){
  std::cout << "You win! :)\n";
}
else if(computer == 2){
  std::cout << "You tied! :/\n";
}
else{
  std::cout << "Computer wins! :(\n";
}
 }
else if(user == 3){
if(computer == 2 || 4){
  std::cout << "You win! :)\n";
}
else if(computer == 3){
  std::cout << "You tied! :/\n";
}
else{
  std::cout << "Computer wins! :(\n";
}
}
else if(user == 4){
if(computer == 2 || 5){
  std::cout << "You win! :)\n";
}
else if(computer == 4){
  std::cout << "You tied! :/\n";
}
else{
  std::cout << "Computer wins! :(\n";
}
  }
else{
if(computer == 1 || 3){
  std::cout << "You win! :)\n";
}
else if(computer == 5){
  std::cout << "You tied! :/\n";
}
else{
  std::cout << "Computer wins! :(\n";
}
 }
  }

Spacing
Before anything, I would recommend fixing your spacing and tabbing. Four spaces for each level of nesting is recommended. It makes your code a lot more readable.
Bug
There is a pretty obvious bug in your code I noticed on my first pass. It's how you're checking the computers number versus the users number. For instance, take a look at this line:
if (user == 0 || 1)

To a novice, it looks like if user == 0 OR user == 1, but that is not happening here. Instead, this is only checking if user is equal to 0, OR if 1 is true. And 1 is always true. This can result in some unexpected behavior. Take a look:
if (user == 0 || 1) {
    std::cout << "Greetings!" << std::endl;
} else {
    std::cout << "Hello!" << std::endl;
}

Now, if I only enter 0, I will get the expected output of just "Greetings!". However, if I enter literally any other number, I will instead only get "Greetings!", instead of getting "Hello!".
Repetition
You have tons of repeated code. You can simplify this by first checking for if the computers input is the same as the users at the start of the program. Then you won't have to keep checking on the goat if/else chunk.
if (computer == user) {
    std::cout << "You tied! :/" << std::endl;
    return 0;
}

Then, you can just assume the user loses at the start.
std::string message = "Computer wins! :(";

Now, you only have to check for win conditions, and if any are met, you change the message variable.
if (
    (user == 1 && (computer == 3 || computer == 4)) ||
    (user == 2 && (computer == 1 || computer == 5)) ||
    (user == 3 && (computer == 2 || computer == 4)) ||
    (user == 4 && (computer == 2 || computer == 5)) ||
    (user == 5 && (computer == 1 || computer == 3))
) message = "You win! :)";

Then, you just output the message variable.
std::cout << message << std::endl;

End
All in all, with these changes made your code now looks like this:
#include <iostream>

int main() {

    srand(time(NULL));
    int computer = rand() % 5 + 1;
    int user = 0;

    std::cout << "=============================================\n";
    std::cout << "Rock    Paper    Scissors    Spock    Lizard!\n";
    std::cout << "=============================================\n";
    std::cout << "1) Rock\n";
    std::cout << "2) Paper\n";
    std::cout << "3) Scissors\n";
    std::cout << "4) Lizard\n";
    std::cout << "5) Spock\n";
    std::cout << "\n";
    std::cout << "Shoot!\n";

    std::cin >> user;
    std::cout << "Computer chose: " << computer << "\n";

    if (computer == user) {
        std::cout << "You tied! :/" << std::endl;
        return 0;
    }

    std::string message = "Computer wins! :(";

    if (
        (user == 1 && (computer == 3 || computer == 4)) ||
        (user == 2 && (computer == 1 || computer == 5)) ||
        (user == 3 && (computer == 2 || computer == 4)) ||
        (user == 4 && (computer == 2 || computer == 5)) ||
        (user == 5 && (computer == 1 || computer == 3))
    ) message = "You win! :)";

    std::cout << message << std::endl;

    return 0;
}


Simple task list frontend rewrite I was recently going through some code that I wrote a while ago as an effort to improve my code.

There was one foreach statement that I was especially proud of the rewrite as I believe it is much more readable than it was before, and I believe it will last longer now.

This code in particular is simply a table body that has a check box (Basically a status check) and a plaintext "task" that was assigned to users stored in a database.

Here is the old code:

<?
    $taskuid = $tasks['uid'];
    $type    = "task";
    foreach($taskData as $key => $value) {
        echo "
";
        echo "  " . (($value['status'] == 1) ? "" : //Status complete
            "") . "  	"; //Status incomplete
        echo "$value[task]	";
        echo "
";
    }
?>

Here is the new code:

<?
    foreach($taskData as $key => $value) {
        echo "
";
        echo "  ";
        echo "      ";
        echo "          ";
        echo "      ";
        echo "  $value[task]	";
        echo "
";
    }
?>

While writing this, I realized the code actually has the same amount of lines, but there is (what I consider to be) a significant difference in the amount of symbols used (The old code being 752 characters and the new one being 564 characters That's nearly 200 characters!)

My question is this, what would you have done differently while rewriting this code? I'm very interested in the different ways code can be written, I know there are a lot of ways this simple task could be done.

Consider

<?php
    foreach ($taskData as $key => $value) {
        $class = ($value['status']) ? 'check-' : '';
        $trClass = ($value['status'] == 1) ? ' class="checkedTR"' : '';
        echo <<<EOHTML

  {$value['task']}

EOHTML;
    }
?>

I prefer the long versions of tags.  So no <? or <=.  It may not matter as much now, but it used to be that some sites would turn off the short versions.  So software could suddenly stop working for no apparent reason.

I prefer to use single quotes in PHP unless I have to use double quotes, e.g. for variable interpolation.  This way I can see at a glance that a string is not using variable interpolation.

If I'm working with a block of lines in PHP, I prefer to use Heredocs and Nowdocs.  I prefer Nowdoc, but it won't work here.  We need the variable interpolation.  The original code will put the entire thing on one line.  This version will display it more like it looks here.

I prefer to use double quotes in HTML.  No particular reason except that it looks better to me.

I prefer to avoid the $tasks[uid] syntax.  Outside of a string, it's wrong and unreliable.  Inside of a string it's reliable, but it can be misleading.  People see it working inside of a string and don't know why the behavior is special.  Also, if people copy something like $tasks[FIELD] into a string, it may not be obvious why it doesn't work the same way inside a string as outside.  Always using the curly braces is clearer in my opinion.

In this case, I would pick the Javascript quoting to avoid escaping, i.e. single quotes.

Your HTML indentation is inconsistent.  Sometimes two spaces and sometimes four.

You lost a closing 	 in the refactor.


Simple arithmetic game in Python Coming from a C/C++ background, this was my first python code I wrote to grasp a few basic concepts. The game involves giving random arithmetic operations to the users and scoring their responses. Player has 3 lives i.e he can mark 3 wrong answers at most. I've tried to time the game i.e the player gets 60 seconds to solve as many questions as possible.

Any suggestions and improvements are welcome.

import random
import time

# Function to generate expressions
from typing import List

def generate_expression(no_of_operators):
    operands = []
    operators = []
    operations = ['+', '-', '*', '/']
    expression = []
    operands_count = 0
    operators_count = 0
    for i in range(0, no_of_operators):
        operands.append(random.randint(0, 20))
    for i in range(0, no_of_operators - 1):
        operators.append((random.choice(operations)))
    for i in range(0, len(operators) + len(operands)):
        if i % 2 == 0:
            expression.append(operands[operands_count])
            operands_count += 1
        else:
            expression.append(operators[operators_count])
            operators_count += 1
    expression = ''.join(str(x) for x in expression)
    return expression

# Function to calculate the solution
def result(expression):
    return (int(eval(expression)))

# Function to evaluate if the answer is right
def evaluate(solution, user_solution):
    if solution == user_solution:
        return True
    else:
        return False

# Display Message

print("""Welcome to the maths game !!!
-----------------------------
Test your basic arithematic skills by playing this simple game. With every 5 correct answers, the level increase
increasing the difficulty of the questions.
Remember :
----------
        1. Write only the integral part of the answer
        2. Operator precedence applies
        3. You have 3 lives.
        4. Total of 60 seconds will be provided.
        5. The timer starts after the first answer is entered """)
input("Are you ready ?? Press any key to begin ! ")

# Variables on which the game operates
score = 0
level = 1
lives = 3
start = time.time()
finish_time = time.time() + 60  # for the timed mode, 60 seconds are needed

# While loop to drive the game
while lives != 0 and time.time() < finish_time:
    # Increase the level of difficulty every 5 questions.
    if score != 0 and score % 5 == 0:
        level = level + 1
    print("LEVEL : ", level)
    no_of_operands = level + 1
    question_expression = generate_expression(no_of_operands)
    print(question_expression, end='')
    # Checking for any divide by zero or numerical errors that may show up
    correct_answer = 0
    try:
        correct_answer = result(question_expression)
    except:
        print("OOPS ! I messed up ! Lets do it again !")
        continue
    answer = int(input(" = "))

    if evaluate(correct_answer, answer):
        print("CORRECT ! ", end='')
        score = score + 1
        print("SCORE = ", score, "LIVES = ", lives)
    else:
        print("WRONG ! ", end='')
        lives = lives - 1
        print("SCORE = ", score, "LIVES = ", lives)
print("GAME OVER !!!")
print("Maximum Level = ", level, "SCORE = ", score)

Quick comment: If you have code which is supposed to run when you call the script (in your case its the "run the game" part of the code), its good practice to put it in a main() function and call the main function rather than keep all that code at the highest level of the file. At the bottom of the file, it would look something like this:

def main():
    functions_to_play_math_game()

if __name__ == "__main__":
    main()

When a python script runs, it gets a __name__ attribute depending on how it was called. If it was run through the command line (with $ python my_script.py), the __name__ attribute gets set to "__main__". So the second part of my code sample checks if the __name__ attribute indicates the script is being called to run, and if so, executes the code inside main().

The reason this is important is because when you import a module in python, it runs all the code inside that file. Now, if the file only contains function definitions, nothing out of the ordinary happens. But if you imported your file into another file, at the import my_file line your game would start running because there is no safeguard to prevent it from going. The catch is that when being imported, __name__ is not set to __main__ like it is when you call the script from a command line. So, if you have this safeguard at the bottom of your code, it wont run when its imported.


Imitate UITableView reordering interaction I have a UIScrollView full of vertically stacked subviews which I want the user to rearrange as they desire. I've implemented a UILongPressGestureRecognizer on my UIScrollView to successfully move the items around.

The more difficult part is when the user brings their finger to the edges of the scrolling area, the UIScrollView needs to scroll, while the gesture recognizer holds onto the floating reordering view. You get this behaviour for free in UITableView when you implement reordering. You can see an example of this when you edit your Safari bookmarks.

My implementation produces the same result, but I have a concern about it. Let me explain.

With each update of the UILongPressGestureRecognizer I check the touch point to see if it is within 20 points of the visual boundaries of my UIScrollView.
If we are within this boundary, I move the content offset by one pixel.
To continue this process as long as the user's finger is within bounds, I repeat the method call.

- (void)handleReorderGestureRecognizerChange:(id)sender
{
    if (!self.reorderGestureRecognizerActive) return;

    // Scroll the scroll view
    BOOL scheduleRecursion = NO;
    if (sender == self.reorderGestureRecognizer && self.scrollViewIsAutomaticallyScrolling)
    {

    }
    else
    {
        // Determine the bounds of the scroll view
        const CGPoint superviewTouchPoint = [self.reorderGestureRecognizer locationInView:self.view];
        const CGPoint currentContentOffset = self.scrollView.contentOffset;
        CGPoint newContentOffset = currentContentOffset;

        // Determine if we are at the bottom
        const CGFloat scrollingBottomArea = (self.scrollView.bottom - 20);
        if (superviewTouchPoint.y > scrollingBottomArea)
        {
            const CGFloat maximumYContentOffset = self.scrollView.contentSize.height - self.scrollView.height;
            newContentOffset = CGPointMake(self.scrollView.contentOffset.x, fmin((self.scrollView.contentOffset.y + SMCompatibilitySinglePixelSize()), maximumYContentOffset));
        }

        // Determine if we are at the top
        if (superviewTouchPoint.y < 20)
        {
            newContentOffset = CGPointMake(self.scrollView.contentOffset.x, fmax((self.scrollView.contentOffset.y - SMCompatibilitySinglePixelSize()), -self.scrollView.contentInset.top));
        }

        // Schedule a change
        if (!CGPointEqualToPoint(currentContentOffset, newContentOffset))
        {
            self.scrollViewIsAutomaticallyScrolling = YES;
            self.scrollView.contentOffset = newContentOffset;

            scheduleRecursion = YES;
        }
        else
        {
            self.scrollViewIsAutomaticallyScrolling = NO;
        }
    }
    ...
    if (scheduleRecursion)
    {
        SM_run_block_after_delay(0.0005, ^{ // <- this hooks through to a dispatch_after call
            [self handleReorderGestureRecognizerChange:self];
        });
    }
}

As I said, this works as expected, I am just very uncomfortable with the idea of continually scheduling this method from itself.

It is however the only way I can think of to make UIScrollView scroll continuously on its own.

As a reviewer would you say this is safe and efficient?

Technically this is not true recursion - dispatch_after(...) adds the block to whatever queue you assign it, so there's no chance of a stack overflow (although I'm not sure what will happen if you add too many blocks to the queue...)  The block is handled by GCD so there's no chance of a retain cycle either.  Plus, the block creation is inexpensive so it's not too inefficient (although the screen refreshes every 1/60 or ~0.017 seconds, so there is an inefficiency in having your timer interval at 0.0005s, about 33x faster than the refresh rate).  Overall, however, this method is very hacky and there is a more conventional way to do this, using a CADisplayLink.
Two pointers for you:

Refactor the code that actually does the scrolling into a new method, instead of having it all in one place.
Use a CADisplayLink to call that method, thus managing the scrolling behavior.

Can provide code example if necessary.
Food For Thought
Unless you are challenging yourself, optimizing existing technology, or doing some research, it's good practice in general to skip reinventing the wheel.  Why are you using a scroll view when you can get the functionality you desire, plus cell recycling and memory management for free with a UITableView?
In the context of your original question, I say it is far safer and more efficient to use technology that's already been proven to work.  For example, here's one I use a lot, that supports long-pressing to reorder :  https://github.com/hpique/HPReorderTableView


A Tumbler, or a format-preserving-encryption shuffle I wanted to implement a simple algorithm for encoding id of entries in a database to avoid:

Storing the UID (unique id) in the table along with the id
Complex and costly algorithm.
Users to give meaning to the id in the sense:

Yeah if this id is bigger than that id it was inserted later in the DB
I can probably get the previous and the next element by adding one to my id

So I need two inputs:

One id
The domain of my id, or the maximum number of entries in that table.

A nice kind of algorithms for this purpose is a FFX algorithm (Format Preserving Encryption). But they usually rely on complex hash function such as SHA or MD5. In my case I just want a very simple simple algorithm that I could implement in MySQL as a generated column for instance.

So I wrote this code:

import math

class Tumbler:
    def __init__(self, maximum, rounds=12):
        bits = math.ceil(math.log(maximum, 2))
        u, v = bits // 2, bits - bits // 2
        self.u = u
        self.v = v
        self.bits = bits
        self.rounds = rounds
        self.maximum = maximum

    def hash(self, x, m):
        """ Jenkins Hash 32bits."""
        x = (x + int('7ed55d16', 16)) + (x << 12)
        x = (x ^ int('c761c23c', 16)) ^ (x >> 19)
        x = (x + int('165667b1', 16)) + (x << 5)
        x = (x + int('d3a2646c', 16)) ^ (x << 9)
        x = (x + int('fd7046c5', 16)) + (x << 3)
        x = (x ^ int('b55a4f09', 16)) ^ (x >> 16)
        return x % m

    def split(self, x, u):
        return (x >> u, x & (2 ** u - 1))

    def _encrypt(self, x, nonce=1):
        for i in range(self.rounds):
            a, b = self.split(x, self.v)
            c = a ^ self.hash(b * i + nonce, (2 ** self.u - 1))
            x = b << self.u | c
        return x

    def _decrypt(self, x, nonce=1):
        for i in reversed(range(self.rounds)):
            b, c = self.split(x, self.u)
            a = c ^ self.hash(b * i + nonce, (2 ** self.u - 1))
            x = (a << self.v) | b
        return x

    def encrypt(self, x, nonce=1):
        while True:
            x = self._encrypt(x, nonce)
            if x <= self.maximum:
                return x

    def decrypt(self, x, nonce=1):
        while True:
            x = self._decrypt(x, nonce)
            if x <= self.maximum:
                return x

Here an output:

>>> t = Tumbler(162)
>>> [(i, t.encrypt(i), t.decrypt(t.encrypt(i))) for i in range(min(16, t.maximum))]

[(0, 48, 0),
 (1, 97, 1),
 (2, 80, 2),
 (3, 159, 3),
 (4, 95, 4),
 (5, 3, 5),
 (6, 38, 6),
 (7, 108, 7),
 (8, 50, 8),
 (9, 162, 9),
 (10, 24, 10),
 (11, 94, 11),
 (12, 69, 12),
 (13, 126, 13),
 (14, 43, 14),
 (15, 120, 15)]

Another example would be to shuffle a deck of 52 cards:

shuffling_method = 1
t = Tumbler(52, shuffling_method)
[(i, t.encrypt(i), t.decrypt(t.encrypt(i))) for i in range(t.maximum)]

If I want another shuffle set, I could use a different shuffling_method.

And of course I could use a better hashing function:

import hashlib

class Tumbler2(Tumbler):
    def hash(self, x, m):
        return int(hashlib.md5(bytes(str(x))).hexdigest, 16) % m

Part of code review is challenging assumptions, so to begin with I'd like to challenge the motivation for this code.

You say you want to avoid "Storing the UID (unique id) in the table along with the id". Why would you have two? Any one of those is enough to uniquely identify a row - they are both unique, after all. If you mean the surrogate key (serial number, UUID or similar) and the business key (for example username), then it absolutely makes sense to store both of them in the same table. Surrogate keys have been discussed for decades, but the industry consensus nowadays seems to be:

The business key should be exposed to end users. That is, a user should know their own username and employee number, even if these are created by the system.
Tables should have a surrogate key, and this key should not be exposed to end users. This does not just include direct user interfaces, but also for example URLs. The reason for this is to be sure that the surrogate key remains an implementation detail which could later be changed, such as when moving from a guessable serial number to a UUID.

You also want to avoid a "[c]omplex and costly algorithm". Version-4 UUIDs are probably the cheapest unguessable surrogate keys you can get your hands on these days without massive implementation effort, as long as you use pretty much any database other than MySQL - PostgreSQL has them, as does the major closed-source databases.

The last reason is related to unguessable IDs, already discussed above.

All in all it looks like implementing v4 UUIDs in MySQL is probably the cheapest option if you must use that database, otherwise you can just use an existing, safe, fast and F/LOSS solution.

That said, some suggestions for the Python code:

__init__ takes an optional rounds parameter, but the only place that's used it's called shuffling_method, which seems inconsistent. Changing the number of rounds doesn't constitute changing the "method".
Rather than assigning u and v at the same time you can save one operation by assigning u first and reusing its value to define v.
Naming is incredibly important for maintainability. I basically have to read the entire code block to guess what a, b, c, m, u, v and x mean. A good variable name is better than a good comment, and will allow the reader to understand a piece of code with as little context as possible.
Having twinned methods encrypt and _encrypt, decrypt and _decrypt is a code smell. If they are doing the same thing, why are they not one method? If they are doing different things, why are they named effectively the same?
There are four different Jenkins hash functions, but it's not obvious which one this is. That would be very helpful for someone trying to verify the implementation.
This comes under the category of implementing your own crypto, since you're trying to make the sequence non-guessable. This hash function looks fairly niche based on the Wikipedia article, and it even looks like the Jenkins hash without an additional secret is guessable.


Directory's disk usage list For my classes, I had to finish this task:

  Directory's disk usage list

  For indicated directory print a list of files and subdirectories in
  descending order according to their total disk usage. Disk usage of a
  simple file is equivalent to its size, for a subdirectory - a sum of
  the sizes of all files in its filesystem branch (subtree). Printed
  list format:

  <disk usage> <holder name> <type> <name> In the preceding print format
  is in case of a file not being a directory an owner, otherwise, the
  holder of a directory is the owner of the files having greatest total
  disk usage in it. <type> is a letter: d for a directory, - for a
  standard file, l - for a symbolic link etc.

  Below file disk usage list, print a summary:

  Total disk usage of the files in directory's subtree, the list of
  total disk usage of files in directory's subtree with respect to the
  owners (sums over owners). CAUTION: during recursive directories
  listing do not dereference symbolic links.

Here is my code:

#!/bin/bash

cd "$1"
ls -lA | awk 'NR != 1{
        name=$8
        for ( i=9; i<=NF; i++) name=name " " $i
        type=substr($1,1,1)
        if (type!="d")
        {
                print $5,$3,type,name
                sum_all+=$5
                usr_sum_all[$3]+=$5
        }
        else
        {
                sum=0;delete usr_sum;
                find_proc="find " name " -printf \"%s %u\\n\" 2>/dev/null"
                while ( find_proc | getline )
                {
                        sum+=$1;usr_sum[$2]+=$1;
                        sum_all+=$1;usr_sum_all[$2]+=$1;
                }
                close(find_proc)

                owner=""
                owner_sum=-1
                for ( iowner in usr_sum ) if ( usr_sum[iowner] > owner_sum ) {owner = iowner; owner_sum=usr_sum[iowner]}
                print sum " " owner " d " name
        }
}
END {
        print "Space taken: " sum_all
        for ( iowner in usr_sum_all ) print "\t user: " iowner " " usr_sum_all[iowner]
}' | sort -gr

Is it ok? Should I make any changes?

I just copied your code, pasted it in to a terminal, ran it, and it did exactly what it is supposed to do. Now, how to make it better?
You don't mention it in the question, but using ls, awk, find, and sort together somehow seems unlikely to be the answer your tutor expected. You don't mention what your course is in, but I would have expected there to be a less 'cobbled together' solution, using perhaps bash only, or perl, python, or something else.
I certainly would not have solved this problem this way (I would have used perl).
Still, assuming your code meets the expectations for tool use (as in, you are supposed to use awk), there are some things that are off.
Single-line multi-statements
You have a number of 1-liners that you should have expanded. You already have the massive awk code-block, why mix the compact 1-liner and block statements like you have done?

for ( iowner in usr_sum ) if ( usr_sum[iowner] > owner_sum ) {owner = iowner; owner_sum=usr_sum[iowner]}

The above should be:
for ( iowner in usr_sum )
{
    if ( usr_sum[iowner] > owner_sum )
    {
         owner = iowner
         owner_sum=usr_sum[iowner]
    }
}

Note, the use of block {} braces for the single if statement, and not using the semi-colon ; to separate statements on a single line.
These other statements should also be on their own lines (and the for statement should have a {} block):

for ( i=9; i<=NF; i++) name=name " " $i
...
sum=0;delete usr_sum;
...
sum+=$1;usr_sum[$2]+=$1;
sum_all+=$1;usr_sum_all[$2]+=$1;

Negative if
Your main if-block would be better if done as a positive check, not a negative check. your code is:

if (type!="d")
{
    ... do not a directory stuff
}
else
{
    ... do directory stuff
}

but would be more readable as:
if (type == "d")
{
    ... do directory stuff
}
else
{
    ... do not a directory stuff
}

Breathing space
Your code is suffocating since it has little breathing space. Many of your statements are compressed around the operators and other symbols. Consider lines like:

          print $5,$3,type,name
          sum_all+=$5
          usr_sum_all[$3]+=$5

Which should be written as:
            print $5, $3, type, name
            sum_all += $5
            usr_sum_all[$3] += $5

Performance
The multiple calls to find may be hurting your performance. In general I can't help but think there's a better way to do this without all the nested OS calls.
Still, it ran fast enough for me on my machine, so it is probably not a real problem.


Async operations in WebMethod How can I improve this code, without to return async Task?

[WebMethod]
public string Login(string login, string password, string deviceId, string appVersion, string xuid)
{
    var authTask = _SSOFrontendService.GetSSOTokenAsync(login, password, deviceId, appVersion);
    var tokenTimestampTask = _SSOFrontendService.GetSSOTokenTimestampAsync();

    Task.WhenAll(authTask, tokenTimestampTask);
    var authResult = authTask.Result;

    if (authResult.Status == ResultStatus.OK)
    {
        var token = new MappedToken(xuid, login, password, deviceId, appVersion, authResult.Content, tokenTimestampTask.Result.Content);
        var mapTokenTask = _mapTokenService.MapAsync(token);

        Task.WhenAll(_mapTokenService.MapAsync(token));
        return _serializer.Serizalize(mapTokenTask.Result);
    }
    return _serializer.Serizalize(authResult);
}

How can I improve this code, without to return async Task?

Doing this doesn't make much sense. If the whole method is going to be synchronous, then you're not gaining much by using asynchronous methods in it, because the synchronous method still needs to block a thread.

Though there might be a way to make async-await work with ASMX.

Task.WhenAll(authTask, tokenTimestampTask);

This doesn't do anything at all. WhenAll() returns a Task that represents the two Tasks combined, so that you can await them. But you're not doing anything with that Task.

You could instead use WaitAll(), but I don't see any reason for that, using Result makes sure that the Task is already completed before returning the value (it does this by blocking the thread if the Task is not completed yet, just like Wait() and WaitAll()).

Task.WhenAll(_mapTokenService.MapAsync(token));

I can see three things wrong with this line:

The WhenAll() issue mentioned above.
You have only a single Task, so you don't need WhenAll() or WaitAll().
You're calling MapAsync() for the second time unnecessarily.

if (authResult.Status == ResultStatus.OK)
{
   …
}
return _serializer.Serizalize(authResult);

It's often best to deal with the failure state immediately by inverting the if:

if (authResult.Status != ResultStatus.OK)
{
    return _serializer.Serizalize(authResult);
}

…

This way reduces the level of nesting for the main part of the code and also improves its flow (you're dealing with the failure in a single place).