Quiz based learning system in Python Description:

I am building a quiz based learning system in Python. The idea is once a day you have to give this test to improve your learning, it's different from regular rote learning. The user will be shown question first and optionally series of hints, the user then can match his answer to the original answer and honestly gives score to his attempt. I didn't go for programmatically checking the answers because it would be difficult to check semantics of two strings.

Goal:

The end goal is to provide a flexible way to add new questions and hints and add new question types. I am not favour of very fancy UI but something
which feels intuitive should work.

In the long run, I will be integrating it with Slack as a bot.

Code:

from enum import Enum

class Category(Enum):
  CS, MATH, PUZZLE = range(3)

class Score(Enum):
  BAD, OK, GOOD = range(3)

data = [{
  'question': 'What does the fox say?',
  'hints': ['not the sound of cat', 'not the sound of dog'],
  'answer': 'Its a mystery',
  'category': Category.PUZZLE,
  'score': Score.BAD
}, {
  'question': 'What is the worst case run time of binary search of n elements?',
  'hints': [
    'Think about the best case',
    'Would need to search exhaustively until one element'],
  'answer': 'Log(n) base 2',
  'category': Category.CS,
  'score': Score.BAD
}];

def runQuiz(questions, category):
  total = 0
  needHint = '/h'
  for q in filter(lambda q: q['category'] == category, questions):
    answer = input(q['question'])
    if answer == needHint:
      for hint in q['hints']:
        moreHints = input(hint)
        if moreHints != needHint:
          break
    print('Correct answer is: {0}'.format(q['answer']))
    rating = int(input('Rate your solution(1-3): '))
    q.update({'score': rating})
    total += rating
  print('You are done for today, your score is {0}'.format(total))
  return input('Want to start again?(y/*)')

def selectCategory():
  category = input("""
    Select category
      1. Computer Science
      2. Mathematics
      3. Puzzles
      4. Random (Default)
  """)
  selectedCategory = {
    1: Category.CS,
    2: Category.MATH,
    3: Category.PUZZLE
  }.get(int(category), Category.CS)
  return selectedCategory

def main():
  print('Make sure you are not feeling thirsty')
  input()
  print('Clean your surrounding')
  input()
  print('Remember your goal')
  input()
  print('If you need any hint type /h')
  input()
  print('Lets go')
  selectedCategory = selectCategory()
  print('You have selected {0} category'.format(selectedCategory.name))
  print('')
  shouldStartAgain = runQuiz(data, selectedCategory)
  if shouldStartAgain == 'y':
    main()
  else:
    print('You are done for today, sleep well!')

if __name__ == '__main__':
  main()

Note:

Although the current solution doesn't meet all the requirements but it is complete in itself as its fully functional code. Its in early stage of development so I would like to take proper design decisions as soon as possible.

TODO:

Find a way to persist the questions with updated score.
Make the questions with lower score come first.

Questions:

Is there any better way to deal with terminal?
Keeping in mind that I would like to use this system as web service too, what design decisions would be helpful?
It may be too broad, but what good programming practices should I follow, for example when and where to choose objects, enums etc?

Expanding a bit on what the first answer mentioned: There are no Quiz, Question etc. classes.

Your current code has this data:

data = [{
  'question': 'What does the fox say?',
  'hints': ['not the sound of cat', 'not the sound of dog'],
  'answer': 'Its a mystery',
  'category': Category.PUZZLE,
  'score': Score.BAD
}, {
  'question': 'What is the worst case run time of binary search of n elements?',
  'hints': [
    'Think about the best case',
    'Would need to search exhaustively until one element'],
  'answer': 'Log(n) base 2',
  'category': Category.CS,
  'score': Score.BAD
}];

So it is a list of objects of this:

Question - String
Hints - array of String
Answer - String
Category - enum value
Score - enum value

This looks like the start of a Question class. But wait, how/why does a Question have a Score? What does it mean that the score for a question is "Bad"? That depends on how you answer that question, doesn't it? I would remove that from this data, that value belongs elsewhere. You could possibly have some "points" integer value in the data to indicate how many points a question is worth though.

You say that you are not looking to make your program give the points, but the user to honestly give the points. This is good, and reminds me about Anki Flashcards (although Anki doesn't have hints AFAIK).

  TODO: Find a way to persist the questions with updated score. Make the questions with lower score come first.

Ah, this is where the score comes in again. It's important to distinguish between a Question and the user's answer to a question. Maybe your system should support multiple users that should be able to answer different things? Then you need to connect each question that a user has answered to a score.

So, besides the Question class that I've already mentioned, you could have some more things:

UserAnswer (contains reference to Question and to a Score), a list of UserAnswers is basically a user's progress, so you could load/save multiple of these for each "Lesson" a user has ongoing/completed.
Quiz (contains a list of question, might not be necessary though as you have a category so you could filter the list of all questions based on a category)
Category can be a string instead of an enum, as I don't see a reason to programmatically hard-code a limit of possible categories

Also, I would strongly recommend to keep your data as a file or in a database and not inside your code.


Approximating the square root using an iterative method I wrote this code, based on the Newton-Raphson method, to find the square root of a number. I'm wondering how I can optimise this code, as I am out of ideas.

#include <stdio.h>

int main(void)
{
     float n, x, i;

     printf("Enter the number you wish to find the square root of.\n");
     printf("\n");
     scanf("%f", &n);

     x = n/2;

     for (i = 0; i < 100; i++)
         x = x - (((x*x) - n)/(2*x));

     printf("The square root of %.0f is %.4f.\n", n, x);

     return 0;

}

Do not rely on a fixed number of iterations. Stop when reaching a desired discrepancy (e.g. fabs(x*x - n) < epsilon)
I do not see any reason for not simplifying the calculations into x = (x + n/x)/2.0.
Assure that the input is positive.


Simple Dice Roll game Is there a more efficient algorithm to generate random numbers in C++?

(This code is working on Dev-C++, but I'm not sure if it works on a Borland compiler.)

/*
  Author: Arpit Agrawal
  Email: arpitagrawal294@gmail.com
  Description: Dice Roll Algorithm.
  Project Name: e-Roll.

*/

#include<iostream.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#include <stdio.h>
#include <Windows.h>

void call();
void one();
void two();
void three();
void four();
void five();
void six();
void call();
int main()
{

    //gotoxy(30,15);
    cout<<"\n\n\n\n\t\tAuthor: Arpit Agrawal\n\t\tEmail: arpitagrawal294@gmail.com\n\t\tDescription: Dice Roll Algorithm.\n\t\tProject Name: e-Roll.\n\t\t" ;
    cout<<"\n\n\t\tLoading. . . . . . . ";
    Sleep(3000);
    cout<<"\n\n\t\tPress r to roll or q to quit the game "<<endl;
    char ch;
    ch = getch();
    xm:
    if (ch=='r'){
    system("cls");
    call();  }
    else
    exit (0);
    cout<<endl<<endl<<"Press r to roll again q to quit!";
    ch = getch();
    goto xm;
    getch();
}

    void call()
    {
        srand (time(NULL));

        int n;
        n= rand();
        n = 1 + n % 6;

        switch (n)
        {
         case 1:
              one();
              break;
         case 2:
              two();
              break;
         case 3:
              three();
              break;
         case 4:
              four();
              break;
         case 5:
              five();
              break;
         case 6:
              six();
              break;
         default:
                 cout<<"NONUM";

        }
    }

        void one()
        {
        cout << " -----" << endl;
        cout << "|     |" << endl;
        cout << "|  O  |" << endl;
        cout << "|     |" << endl;
        cout <<  " -----" << endl;
        }
        void two()
        {
        cout << " -----" << endl;
        cout << "|    O|" << endl;
        cout << "|     |" << endl;
        cout << "|O    |" << endl;
        cout <<  " -----" << endl;
        }
        void three()
        {
        cout << " -----" << endl;
        cout << "|    O|" << endl;
        cout << "|  O  |" << endl;
        cout << "|O    |" << endl;
        cout <<  " -----" << endl;
        }
        void four()
        {
        cout << " -----" << endl;
        cout << "|O   O|" << endl;
        cout << "|     |" << endl;
        cout << "|O   O|" << endl;
        cout <<  " -----" << endl;
        }
        void five()
        {
        cout << " -----" << endl;
        cout << "|O   O|" << endl;
        cout << "|  O  |" << endl;
        cout << "|O   O|" << endl;
        cout <<  " -----" << endl;
        }
        void six()
        {
        cout << " -----" << endl;
        cout << "|O   O|" << endl;
        cout << "|O   O|" << endl;
        cout << "|O   O|" << endl;
        cout <<  " -----" << endl;
        }

Only call srand() once in an application:

    srand (time(NULL));

Should be just after main() starts.

This does not generate an evenly distributed the random numbers.

    n= rand();
    n = 1 + n % 6;

This is because rand() returns a number from [0,RAND_MAX) or [0,32767) which is not exactly divisible by 6. So you get:

    1:  1/5462        Notice this is one more than the others.
    2:  1/5461
    3:  1/5461
    4:  1/5461
    5:  1/5461
    6:  1/5461

Probably not an issue for a simple app but worth noting. The proper way to do this is:

int dieRoll() // 1-6 evenly distributed.
{
     static int const max = RAND_MAX/6*6;

     int r = rand();
     while(r >= max) { r = rand();}

     return r%6+1;
}

Probably best not to use goto:

xm:
if (ch=='r'){
system("cls");
call();  }
else
exit (0);
cout<<endl<<endl<<"Press r to roll again q to quit!";
ch = getch();
goto xm;

Prefer (a standard loop):

while (ch=='r') {
    system("cls");
    call();

    cout<<endl<<endl<<"Press r to roll again q to quit!";
    ch = getch();
}

Lets also compress your switch statement:

    switch (n) {
        case 1:   one();break;
        case 2:   two();break;
        case 3: three();break;
        case 4:  four();break;
        case 5:  five();break;
        case 6:   six();break;
        // We know the number will never be anything else
        // so don't need the default.
    }

Don't need to use so many std::endl.

    cout << " ----- \n"
         << "|O   O|\n"
         << "|     |\n"
         << "|O   O|\n"
         <<  " -----" << endl;

std::endl is used to flush the output. If you just want a new line use "\n".


Handle concurrent request by waiting the result of an already running operation I need to handle concurrent request by waiting the result of an already running operation.

Requests for data may come in simultaneously with same/different credentials.

For each unique set of credentials there can be at most one GetDataInternal call in progress, with the result from that one call returned to all queued waiters when it is ready.

After this the results of the previous call are invalidated, and a new GetDataInternal call will be allowed with the same set of credentials.

Parallel calls to GetDataInternal with different credentials are allowed.

private readonly ConcurrentDictionary<Credential, Lazy<Data>> Cache
= new ConcurrentDictionary<Credential, Lazy<Data>>();

public Data GetData(Credential credential)
{
    // This instance will be thrown away if a cached
    // value with our "credential" key already exists.
    Lazy<Data> newLazy = new Lazy<Data>(
        () => GetDataInternal(credential),
        LazyThreadSafetyMode.ExecutionAndPublication
    );

    Lazy<Data> lazy = Cache.GetOrAdd(credential, newLazy);
    bool added = ReferenceEquals(newLazy, lazy); // If true, we won the race.
    Data data;

    try
    {
       // Wait for the GetDataInternal call to complete.
       data = lazy.Value;
    }
    finally
    {
        // Only the thread which created the cache value
        // is allowed to remove it, to prevent races.
        if (added) {
            Cache.TryRemove(credential, out lazy);
        }
    }

    return data;
}

Do I have a bugs? Is it thread safe? How can I improve my code? I'm using .net framework 4.5.2

Reading through the code, I can say that it is well written, concurrent access in mind, and at the first sight, it can be said that it has no flaws.

I especially liked these lines:

Lazy<Data> lazy = Cache.GetOrAdd(credential, newLazy);
bool added = ReferenceEquals(newLazy, lazy); // If true, we won the race.

To prove that it is properly working, I run a 100 concurrent threads test with random access to the GetData() operation with the same credential instance. This test revealed that,

The access is synchronized to the GetDataInternal() method. OK.
For the threads that call GetData() at the same time passing the same Credential instance, after the call to GetOrAdd(), added is true for only the first invoking thread. OK.
All other threads get the existing Lazy instance after calling GetOrAdd() and added is false. OK
GetDataInternal() is called on one of the first threads that call GetOrAdd(), most of the time the adding thread, but sometimes on another. OK
After the call to GetDataInternal(), all requesting threads get the same Data instance out of lazy.Value one by one, as returned by GetDataInternal(). OK
The first thread that gets the Data instance calls TryRemove() and succeeds. OK.
After the Lazy instance is removed, other threads continue to get the old Data instance because they have the removed Lazy instance. OK

No concurrency issues, nothing.

The code is working properly.

ORIGINAL ORDER  THREAD ID   METHOD  EVENT NAME  RESULT  TOTAL MS
2   T:8 M:GetData   E:end_call_GetOrAdd()->added    R:True  4,82
1   T:9 M:GetData   E:end_call_GetOrAdd()->added    R:False 5,09
12  T:21    M:GetData   E:end_call_GetOrAdd()->added    R:False 5,3
9   T:30    M:GetData   E:end_call_GetOrAdd()->added    R:False 5,32
13  T:3 M:GetData   E:end_call_GetOrAdd()->added    R:False 5,33
49  T:31    M:GetData   E:end_call_GetOrAdd()->added    R:False 5,56
20  T:22    M:GetData   E:end_call_GetOrAdd()->added    R:False 6,07
11  T:7 M:GetData   E:end_call_GetOrAdd()->added    R:False 6,19
8   T:18    M:GetData   E:end_call_GetOrAdd()->added    R:False 6,41
3   T:23    M:GetData   E:end_call_GetOrAdd()->added    R:False 7,01
4   T:10    M:GetData   E:end_call_GetOrAdd()->added    R:False 7,29
5   T:6 M:GetData   E:end_call_GetOrAdd()->added    R:False 7,29
15  T:28    M:GetData   E:end_call_GetOrAdd()->added    R:False 8,39
70  T:24    M:GetData   E:end_call_GetOrAdd()->added    R:False 9,26
10  T:17    M:GetData   E:end_call_GetOrAdd()->added    R:False 9,29
45  T:13    M:GetData   E:end_call_GetOrAdd()->added    R:False 9,31
18  T:20    M:GetData   E:end_call_GetOrAdd()->added    R:False 9,72
7   T:25    M:GetData   E:end_call_GetOrAdd()->added    R:False 10,38
40  T:26    M:GetData   E:end_call_GetOrAdd()->added    R:False 10,4
22  T:14    M:GetData   E:end_call_GetOrAdd()->added    R:False 10,6
65  T:15    M:GetData   E:end_call_GetOrAdd()->added    R:False 10,67
52  T:12    M:GetData   E:end_call_GetOrAdd()->added    R:False 11,04
47  T:5 M:GetData   E:end_call_GetOrAdd()->added    R:False 11,5
42  T:19    M:GetData   E:end_call_GetOrAdd()->added    R:False 11,81
51  T:4 M:GetData   E:end_call_GetOrAdd()->added    R:False 12,34
33  T:11    M:GetData   E:end_call_GetOrAdd()->added    R:False 12,91
27  T:29    M:GetData   E:end_call_GetOrAdd()->added    R:False 13,62
36  T:27    M:GetData   E:end_call_GetOrAdd()->added    R:False 14,01
6   T:16    M:GetData   E:end_call_GetOrAdd()->added    R:False 14,88
14  T:9 M:GetDataInternal   E:Return    R:[Data_1]  18,21
17  T:9 M:GetData   E:end_get_lazy.Value    R:[Data_1]  18,29
16  T:28    M:GetData   E:end_get_lazy.Value    R:[Data_1]  18,33
19  T:20    M:GetData   E:end_get_lazy.Value    R:[Data_1]  18,58
21  T:22    M:GetData   E:end_get_lazy.Value    R:[Data_1]  18,71
23  T:14    M:GetData   E:end_get_lazy.Value    R:[Data_1]  18,86
24  T:8 M:GetData   E:end_get_lazy.Value    R:[Data_1]  18,91
25  T:8 M:GetData   E:begin_call_TryRemove  R:- 18,96
50  T:25    M:GetData   E:end_get_lazy.Value    R:[Data_1]  19,83
26  T:8 M:GetData   E:end_call_TryRemove    R:True  19,86
39  T:10    M:GetData   E:end_get_lazy.Value    R:[Data_1]  20,67
38  T:6 M:GetData   E:end_get_lazy.Value    R:[Data_1]  21,56
31  T:17    M:GetData   E:end_get_lazy.Value    R:[Data_1]  21,6
28  T:29    M:GetData   E:end_get_lazy.Value    R:[Data_1]  22
29  T:32    M:GetData   E:end_call_GetOrAdd()->added    R:True  22,46
53  T:18    M:GetData   E:end_get_lazy.Value    R:[Data_1]  22,61
30  T:21    M:GetData   E:end_get_lazy.Value    R:[Data_1]  24,47
32  T:30    M:GetData   E:end_get_lazy.Value    R:[Data_1]  24,91
35  T:3 M:GetData   E:end_get_lazy.Value    R:[Data_1]  25,13
34  T:11    M:GetData   E:end_get_lazy.Value    R:[Data_1]  25,78
37  T:27    M:GetData   E:end_get_lazy.Value    R:[Data_1]  27,08
41  T:26    M:GetData   E:end_get_lazy.Value    R:[Data_1]  30,53
43  T:19    M:GetData   E:end_get_lazy.Value    R:[Data_1]  31,13
44  T:33    M:GetData   E:end_call_GetOrAdd()->added    R:False 31,3
46  T:13    M:GetData   E:end_get_lazy.Value    R:[Data_1]  32,4
48  T:5 M:GetData   E:end_get_lazy.Value    R:[Data_1]  33,04
54  T:23    M:GetData   E:end_get_lazy.Value    R:[Data_1]  33,16
64  T:16    M:GetData   E:end_get_lazy.Value    R:[Data_1]  33,7
56  T:31    M:GetData   E:end_get_lazy.Value    R:[Data_1]  33,96
58  T:7 M:GetData   E:end_get_lazy.Value    R:[Data_1]  34,27
59  T:32    M:GetDataInternal   E:Return    R:[Data_2]  34,65
55  T:4 M:GetData   E:end_get_lazy.Value    R:[Data_1]  35,23
57  T:34    M:GetData   E:end_call_GetOrAdd()->added    R:False 36,3
60  T:12    M:GetData   E:end_get_lazy.Value    R:[Data_1]  36,52
72  T:35    M:GetData   E:end_call_GetOrAdd()->added    R:False 37,29
63  T:33    M:GetData   E:end_get_lazy.Value    R:[Data_2]  40,92
74  T:34    M:GetData   E:end_get_lazy.Value    R:[Data_2]  41,08
76  T:32    M:GetData   E:end_get_lazy.Value    R:[Data_2]  41,12
61  T:36    M:GetData   E:end_call_GetOrAdd()->added    R:False 41,31
69  T:37    M:GetData   E:end_call_GetOrAdd()->added    R:False 43,2
62  T:36    M:GetData   E:end_get_lazy.Value    R:[Data_2]  43,6
66  T:15    M:GetData   E:end_get_lazy.Value    R:[Data_1]  45,93
67  T:38    M:GetData   E:end_call_GetOrAdd()->added    R:False 46,3
68  T:38    M:GetData   E:end_get_lazy.Value    R:[Data_2]  46,44
75  T:37    M:GetData   E:end_get_lazy.Value    R:[Data_2]  47,19
71  T:24    M:GetData   E:end_get_lazy.Value    R:[Data_1]  47,71
73  T:35    M:GetData   E:end_get_lazy.Value    R:[Data_2]  48,57
77  T:32    M:GetData   E:begin_call_TryRemove  R:- 49,97
78  T:32    M:GetData   E:end_call_TryRemove    R:True  50,04
79  T:50    M:GetData   E:end_call_GetOrAdd()->added    R:True  50,8
80  T:51    M:GetData   E:end_call_GetOrAdd()->added    R:False 51,58
81  T:44    M:GetData   E:end_call_GetOrAdd()->added    R:False 51,58
82  T:41    M:GetData   E:end_call_GetOrAdd()->added    R:False 52,3
83  T:49    M:GetData   E:end_call_GetOrAdd()->added    R:False 52,3
84  T:58    M:GetData   E:end_call_GetOrAdd()->added    R:False 52,78
85  T:42    M:GetData   E:end_call_GetOrAdd()->added    R:False 53,3
86  T:57    M:GetData   E:end_call_GetOrAdd()->added    R:False 53,3
90  T:52    M:GetData   E:end_call_GetOrAdd()->added    R:False 53,3
119 T:39    M:GetData   E:end_call_GetOrAdd()->added    R:False 53,33
112 T:45    M:GetData   E:end_call_GetOrAdd()->added    R:False 53,43
87  T:59    M:GetData   E:end_call_GetOrAdd()->added    R:False 54,53
88  T:54    M:GetData   E:end_call_GetOrAdd()->added    R:False 55,29
89  T:47    M:GetData   E:end_call_GetOrAdd()->added    R:False 57,1
92  T:46    M:GetData   E:end_call_GetOrAdd()->added    R:False 57,29
93  T:43    M:GetData   E:end_call_GetOrAdd()->added    R:False 57,33
91  T:53    M:GetData   E:end_call_GetOrAdd()->added    R:False 58,29
94  T:60    M:GetData   E:end_call_GetOrAdd()->added    R:False 59,56
95  T:50    M:GetDataInternal   E:Return    R:[Data_3]  60,29
96  T:50    M:GetData   E:end_get_lazy.Value    R:[Data_3]  60,37
99  T:51    M:GetData   E:end_get_lazy.Value    R:[Data_3]  60,69
97  T:50    M:GetData   E:begin_call_TryRemove  R:- 60,88
117 T:44    M:GetData   E:end_get_lazy.Value    R:[Data_3]  61,24
98  T:50    M:GetData   E:end_call_TryRemove    R:True  61,26
107 T:49    M:GetData   E:end_get_lazy.Value    R:[Data_3]  61,41
108 T:58    M:GetData   E:end_get_lazy.Value    R:[Data_3]  61,48
109 T:53    M:GetData   E:end_get_lazy.Value    R:[Data_3]  61,48
100 T:54    M:GetData   E:end_get_lazy.Value    R:[Data_3]  61,73
111 T:46    M:GetData   E:end_get_lazy.Value    R:[Data_3]  61,81
102 T:43    M:GetData   E:end_get_lazy.Value    R:[Data_3]  62,15
110 T:47    M:GetData   E:end_get_lazy.Value    R:[Data_3]  62,6
101 T:57    M:GetData   E:end_get_lazy.Value    R:[Data_3]  63,55
104 T:41    M:GetData   E:end_get_lazy.Value    R:[Data_3]  63,62
103 T:61    M:GetData   E:end_call_GetOrAdd()->added    R:True  64,3
106 T:60    M:GetData   E:end_get_lazy.Value    R:[Data_3]  64,63
105 T:42    M:GetData   E:end_get_lazy.Value    R:[Data_3]  65,05
116 T:52    M:GetData   E:end_get_lazy.Value    R:[Data_3]  66,18
121 T:59    M:GetData   E:end_get_lazy.Value    R:[Data_3]  66,56
114 T:56    M:GetData   E:end_call_GetOrAdd()->added    R:False 67,47
122 T:55    M:GetData   E:end_call_GetOrAdd()->added    R:False 69,18
118 T:48    M:GetData   E:end_call_GetOrAdd()->added    R:False 71,37
115 T:40    M:GetData   E:end_call_GetOrAdd()->added    R:False 71,63
113 T:45    M:GetData   E:end_get_lazy.Value    R:[Data_3]  72,02
123 T:61    M:GetDataInternal   E:Return    R:[Data_4]  74,29
120 T:39    M:GetData   E:end_get_lazy.Value    R:[Data_3]  77,3
124 T:56    M:GetData   E:end_get_lazy.Value    R:[Data_4]  79,26
130 T:61    M:GetData   E:end_get_lazy.Value    R:[Data_4]  79,27
149 T:63    M:GetData   E:end_call_GetOrAdd()->added    R:False 79,3
131 T:48    M:GetData   E:end_get_lazy.Value    R:[Data_4]  79,32
140 T:40    M:GetData   E:end_get_lazy.Value    R:[Data_4]  79,5
125 T:55    M:GetData   E:end_get_lazy.Value    R:[Data_4]  79,78
126 T:65    M:GetData   E:end_call_GetOrAdd()->added    R:False 80,76
127 T:65    M:GetData   E:end_get_lazy.Value    R:[Data_4]  80,93
128 T:66    M:GetData   E:end_call_GetOrAdd()->added    R:False 81,32
129 T:66    M:GetData   E:end_get_lazy.Value    R:[Data_4]  81,66
132 T:62    M:GetData   E:end_call_GetOrAdd()->added    R:False 82,32
134 T:61    M:GetData   E:begin_call_TryRemove  R:- 82,55
138 T:68    M:GetData   E:end_call_GetOrAdd()->added    R:False 83,3
142 T:74    M:GetData   E:end_call_GetOrAdd()->added    R:False 83,31
133 T:62    M:GetData   E:end_get_lazy.Value    R:[Data_4]  83,37
136 T:70    M:GetData   E:end_call_GetOrAdd()->added    R:False 84,94
135 T:61    M:GetData   E:end_call_TryRemove    R:True  84,95
141 T:75    M:GetData   E:end_call_GetOrAdd()->added    R:True  84,95
147 T:72    M:GetData   E:end_call_GetOrAdd()->added    R:False 85,1
137 T:64    M:GetData   E:end_call_GetOrAdd()->added    R:False 86
152 T:70    M:GetData   E:end_get_lazy.Value    R:[Data_4]  86
162 T:77    M:GetData   E:end_call_GetOrAdd()->added    R:False 86,29
144 T:67    M:GetData   E:end_call_GetOrAdd()->added    R:False 86,3
139 T:68    M:GetData   E:end_get_lazy.Value    R:[Data_4]  86,89
151 T:69    M:GetData   E:end_call_GetOrAdd()->added    R:False 88,22
143 T:74    M:GetData   E:end_get_lazy.Value    R:[Data_4]  88,98
155 T:78    M:GetData   E:end_call_GetOrAdd()->added    R:False 89,47
145 T:71    M:GetData   E:end_call_GetOrAdd()->added    R:False 89,51
148 T:76    M:GetData   E:end_call_GetOrAdd()->added    R:False 90,3
146 T:73    M:GetData   E:end_call_GetOrAdd()->added    R:False 90,37
150 T:63    M:GetData   E:end_get_lazy.Value    R:[Data_4]  94,68
153 T:64    M:GetDataInternal   E:Return    R:[Data_5]  96,6
154 T:64    M:GetData   E:end_get_lazy.Value    R:[Data_5]  97
158 T:75    M:GetData   E:end_get_lazy.Value    R:[Data_5]  97,04
168 T:69    M:GetData   E:end_get_lazy.Value    R:[Data_5]  97,15
170 T:73    M:GetData   E:end_get_lazy.Value    R:[Data_5]  97,17
166 T:76    M:GetData   E:end_get_lazy.Value    R:[Data_5]  97,2
157 T:67    M:GetData   E:end_get_lazy.Value    R:[Data_5]  97,35
156 T:78    M:GetData   E:end_get_lazy.Value    R:[Data_5]  98,39
165 T:72    M:GetData   E:end_get_lazy.Value    R:[Data_5]  99,16
169 T:71    M:GetData   E:end_get_lazy.Value    R:[Data_5]  99,91
159 T:75    M:GetData   E:begin_call_TryRemove  R:- 100,13
160 T:75    M:GetData   E:end_call_TryRemove    R:True  100,66
161 T:79    M:GetData   E:end_call_GetOrAdd()->added    R:False 101,06
164 T:79    M:GetData   E:end_get_lazy.Value    R:[Data_5]  101,29
163 T:77    M:GetData   E:end_get_lazy.Value    R:[Data_5]  101,84
167 T:80    M:GetData   E:end_call_GetOrAdd()->added    R:True  102,43
171 T:92    M:GetData   E:end_call_GetOrAdd()->added    R:False 105,32
172 T:93    M:GetData   E:end_call_GetOrAdd()->added    R:False 106,97
173 T:82    M:GetData   E:end_call_GetOrAdd()->added    R:False 106,97
175 T:91    M:GetData   E:end_call_GetOrAdd()->added    R:False 106,97
176 T:83    M:GetData   E:end_call_GetOrAdd()->added    R:False 106,97
174 T:95    M:GetData   E:end_call_GetOrAdd()->added    R:False 107,18
178 T:89    M:GetData   E:end_call_GetOrAdd()->added    R:False 107,35
179 T:94    M:GetData   E:end_call_GetOrAdd()->added    R:False 108,56
177 T:88    M:GetData   E:end_call_GetOrAdd()->added    R:False 108,58
180 T:90    M:GetData   E:end_call_GetOrAdd()->added    R:False 110,32
181 T:84    M:GetData   E:end_call_GetOrAdd()->added    R:False 111,31
183 T:97    M:GetData   E:end_call_GetOrAdd()->added    R:False 111,52
182 T:86    M:GetData   E:end_call_GetOrAdd()->added    R:False 111,8
186 T:81    M:GetData   E:end_call_GetOrAdd()->added    R:False 112,6
184 T:85    M:GetData   E:end_call_GetOrAdd()->added    R:False 113,3
185 T:96    M:GetData   E:end_call_GetOrAdd()->added    R:False 113,42
187 T:87    M:GetData   E:end_call_GetOrAdd()->added    R:False 115,35
188 T:80    M:GetDataInternal   E:Return    R:[Data_6]  117,87
189 T:80    M:GetData   E:end_get_lazy.Value    R:[Data_6]  122,92
192 T:92    M:GetData   E:end_get_lazy.Value    R:[Data_6]  122,93
195 T:83    M:GetData   E:end_get_lazy.Value    R:[Data_6]  122,93
207 T:96    M:GetData   E:end_get_lazy.Value    R:[Data_6]  122,98
193 T:97    M:GetData   E:end_get_lazy.Value    R:[Data_6]  123,28
190 T:80    M:GetData   E:begin_call_TryRemove  R:- 123,3
199 T:85    M:GetData   E:end_get_lazy.Value    R:[Data_6]  123,42
202 T:91    M:GetData   E:end_get_lazy.Value    R:[Data_6]  123,45
209 T:87    M:GetData   E:end_get_lazy.Value    R:[Data_6]  123,54
194 T:90    M:GetData   E:end_get_lazy.Value    R:[Data_6]  123,68
191 T:80    M:GetData   E:end_call_TryRemove    R:True  123,75
197 T:84    M:GetData   E:end_get_lazy.Value    R:[Data_6]  124,62
205 T:82    M:GetData   E:end_get_lazy.Value    R:[Data_6]  124,78
201 T:81    M:GetData   E:end_get_lazy.Value    R:[Data_6]  125,03
198 T:86    M:GetData   E:end_get_lazy.Value    R:[Data_6]  125,25
196 T:93    M:GetData   E:end_get_lazy.Value    R:[Data_6]  125,58
200 T:95    M:GetData   E:end_get_lazy.Value    R:[Data_6]  126,03
206 T:94    M:GetData   E:end_get_lazy.Value    R:[Data_6]  126,22
203 T:89    M:GetData   E:end_get_lazy.Value    R:[Data_6]  127,19
204 T:100   M:GetData   E:end_call_GetOrAdd()->added    R:True  127,58
211 T:88    M:GetData   E:end_get_lazy.Value    R:[Data_6]  129
208 T:102   M:GetData   E:end_call_GetOrAdd()->added    R:False 129,3
210 T:98    M:GetData   E:end_call_GetOrAdd()->added    R:False 130,3
212 T:99    M:GetData   E:end_call_GetOrAdd()->added    R:False 131,31
213 T:101   M:GetData   E:end_call_GetOrAdd()->added    R:False 136,3
214 T:100   M:GetDataInternal   E:Return    R:[Data_7]  138,3
215 T:100   M:GetData   E:end_get_lazy.Value    R:[Data_7]  138,4
218 T:102   M:GetData   E:end_get_lazy.Value    R:[Data_7]  138,4
221 T:101   M:GetData   E:end_get_lazy.Value    R:[Data_7]  138,56
219 T:99    M:GetData   E:end_get_lazy.Value    R:[Data_7]  138,58
216 T:100   M:GetData   E:begin_call_TryRemove  R:- 138,73
220 T:98    M:GetData   E:end_get_lazy.Value    R:[Data_7]  138,98
217 T:100   M:GetData   E:end_call_TryRemove    R:True  139,04


Find index of an object with a specific value stored in an array I am using the following code in order to retrieve the index for an object stored in a JavaScript array.

Scripts works fine, but I would like your opinion regarding performance.

Also  would like to know also if using [].map() could be more appropriate of [].some().

http://jsbin.com/nasiyiyavi/1/

var data = [{ id: 3 }, { id: 4 }, { id: 1 }, { id: 0 }, { id: 2 }];

function findIndexInData(optionsArg) {
    var options = {
        data: optionsArg.data,
        where: optionsArg.where,
        what: optionsArg.what
    },
    result = -1;
    options.data.some(function (item, i) {
        if (item[options.where] === options.what) {
            result = i;
            return true;
        }
    });
    return result;
}
alert(findIndexInData({ data: data, where: 'id', what: 2 }));

I think the best way of doing that would be using the new ES6 function Array.prototype.findIndex:

data.findIndex(function(obj) { return obj[where] === what; })

If you don't have that function, there are good polyfills at MDN and NPM.

(if you do have full ES6, you apparently could also do

data.findIndex(obj => obj[where] === what)

but i'm still learning how that syntax works so i may be wrong there)


Sort and display input numbers How do I decrease time, especially in sorting?

  Given a list of numbers, you are to sort them in non-decreasing order.

  Input

  t – the number of numbers in list, then t lines follow [\$t \le 10^6\$].

  Each line contains one integer: N [\$0 \le N \le 10^6\$]

  Output

  Given numbers in non-decreasing order.

  Example

  Input:

5
5
3
6
7
1

  Output:

1
3
5
6
7

struct sort_list{
int num;
struct sort_list *next;
};
typedef struct sort_list node;
void enter();
void sort();
void print();
int main()
{

        node *head;
        int tot_num;
        scanf("%d",&tot_num);  //asking for entering total numbers
        head=(node*)malloc(sizeof(node));
        enter(head,tot_num);
        sort(head,tot_num);
        print(head);
    return 0;
    }
    void enter(node *list,int tot_num)
    {
        int i=0;
        while(i!=tot_num)
        {
            scanf("%d",&list->num);
            if(i==tot_num-1)
            {
                list->next=0;
                //break;
            }
            else
            {
                list->next=(node*)malloc(sizeof(node));
                list=list->next;
            }
            i++;
        }
    }
    void print(node *list)
    {
        int i=0;
        while(list->next!=0)
        {
            printf("%d\n",list->num);
            list=list->next;
            i++;
        }
        if(list->next==0)
        {
            printf("%d\n",list->num);
        }
    }
    void sort(node *list,int tot_num)
    {
        node *new=list;
        int i,j,t;
        for(i=0;i<tot_num;i++)
        {
            for(j=i+1;j<tot_num;j++)
            {
                if(list->num > list->next->num)
                {
                    t=list->num;
                    list->num=list->next->num;
                    list->next->num=t;
                }
                list=list->next;
            }
            list=new;
        }
    }

There are a number of things you can do to improve this code.

Use const where possible

The print routine does not (and should not) alter the linked list, and so it should be declared as taking const node *list as an argument.

Check the return value of malloc before dereferencing

The primary way that the operating system uses to tell your program that it's running out of memory is to return NULL when the program requests a memory allocation.  For that reason, you must check the return value before dereferencing it to make sure it's not NULL.

Eliminate memory leak

There are calls to malloc but no calls to free so this code certainly leaks memory.

Separate I/O from core routines

It's often better to have input and output operation in a single place (or a few select places) rather than having them scattered in several places.  For this reason, I'd recommend having the enter routine simply be responsible for putting the new data into the linked list rather than having it also get the new number.

Use for loops rather than while loops where practical

Your print routine can be considerably simplified by using a for loop rather than a while loop and eliminating useless variable i:

void print(const node *list)
{
    for ( ; list; list = list->next)
        printf("%d\n",list->num);
}

Reduce memory allocations

The first number read is a count of the following numbers.  This tells you exactly how many nodes need to be allocated, so there really isn't any need to have multiple calls to malloc.  You can simply call it once, allocate an array of nodes that is large enough to hold all of the numbers and use that memory area for all of your linked list nodes.

Eliminate the need to sort

Rather than having separate enter and sort routines, you may find that peformance is better if you sort as you enter each number.

Putting it all together

Putting all of these suggestions (and more) into practice might look like this:

void enter(node *list, node *newnode)
{
    for ( ; list->next && list->next->num < newnode->num; list = list->next);
    newnode->next = list->next;
    list->next = newnode;
}

void print(const node *list)
{
    if (list == NULL)
        return;
    for ( ; list->next; list = list->next)
        printf("%d\n",list->next->num);
}

int main()
{
    int tot_num;
    scanf("%d",&tot_num);  //asking for entering total numbers
    node *head = calloc(tot_num+1, sizeof(node));
    if (head == NULL) {
        printf("ERROR: could not allocate space for %d numbers\n", tot_num);
        return 1;
    }
    for (int i=1; i <= tot_num; ++i) {
        scanf("%d",&(head[i].num));
        enter(head,&head[i]);
    }
    print(head);
    free(head);
}

Results

Even this very simple program runs approximately 3x faster on my machine (64-bit Linux machine) than the original, operating on a file of 10,000 random numbers.  It is still quite slow, however, because the enter routine only does a simple linear search.  There are better ways to do this, and I would encourage you to look into better sorting algorithms and to try to implement some to see how they work.


Given a number: find the closest value in a list of unique and sorted numbers with some twists I have a method getClosest() in an object, that does the following:

  Given a number: Find the closest number in a list of unique and sorted numeric values.

On top of that it has two additional ptions next|offset:

default: find the closest value, smaller or larger than the submitted value
next: find the next value in the list, that is larger than the submitted one
offset: like default but find the smaller value only, if the distance to it is smaller/equal than a given delta

You can also assume that:

the input value will always be smaller then or equal to the largest value in the set
all parameters have the correct type (integer|boolean)
the list will contain between 10-20 values

This is an example of the list:

this.values = [0, 35, 90, 110, 160, 175, 200];

The function returns an object, holding the position as well as the actual value:

{
    index: 1,
    value: 35
}

class Test {
  constructor() {
    this.values = [0, 35, 90, 110, 160, 175, 200];
    this.delta = 12;
  }

  getClosest(offset, next, value) {
    let closest,
        comparativeValue;

    if (offset === true) {
      for (let i = 0; i < this.values.length; ++i) {
        const current = this.values[i];

        if (value <= current) {
          closest = {
            index: i,
            value: current
          };
          break;
        }

        if (value > current) {
          comparativeValue = {
            index: i,
            value: current
          };
        }
      }

      if (comparativeValue) {
        const offsetA = Math.abs(closest.value - value);
        const offsetB = Math.abs(comparativeValue.value - value);

        if (this.delta < offsetA && this.delta > offsetB) {
          return comparativeValue;
        }
      }
    }

    if (next === true) {
      for (let i = 0; i < this.values.length; ++i) {
        const current = this.values[i];

        if (current > value) {
          closest = {
            index: i,
            value: current
          };
          break;
        }
      }
    }

    if (!offset && !next) {
      for (let i = 0, shortest = null; i < this.values.length; ++i) {
        const current = this.values[i];
        const delta = Math.abs(current - value);

        if (null === shortest || shortest > delta) {
          closest = {
            index: i,
            value: current
          };
          shortest = delta;
        }
      }
    }
    return closest;
  }
}

const test = new Test();

console.log(
  test.getClosest(false, false, 10).value,
  test.getClosest(false, false, 100).value,

  test.getClosest(false, true, 10).value,
  test.getClosest(false, true, 100).value,

  test.getClosest(true, false, 10).value,
  test.getClosest(true, false, 100).value,
);

My concerns are:

overcomplicated
this ain't DRY at all
too many loops and variable declarations
there's a call getClosest(true, true, 40), which might lead to unexpected results

You can ignore the Test-object-wrapper. It's to simplify the example and to make the code easily runnable. Here's a fiddle as well to play around with.

The given specification is incomplete and your implementation differs from the specification.

For example, according to your specification, test.getClosest(true, false, 99).value should be 90 instead of 110, since the distance from 99 to the closest value 90 is 9 which is "smaller/equal than [the] given delta" of 12.

Also, it is not clear how strong the given assumptions are and whether or not violations of those assumptions can occur and should be dealt with.

For example, your implementation fails on lists of less than 4 values. Now, one could say that this isn't a problem due to the assumption that a "list will contain between 10-20 values". But it is  generally considered bad practice and a more robust implementation would be recommended.

In addition to that, we don't know which parts of your interface or method signature are given and which parts are subject to review. You write that we "can ignore the Test-object-wrapper". But what about the method signature with its unorthodox choice of arguments, which seems to be required by the given specification?

For all these reasons, it is hard to provide a meaningful review.

Some notes:

getClosest(offset, next, value)

the get prefix usually indicates a lookup or simple computation. If more complex computations are required instead, I prefer using another verb such as findClosest.
Also, I recommend renaming offset to something more appropriate - it clearly isn't an offset.
Most developers would probably expect the value as the first argument, similar to built-in functions such as parseInt(string, radix) or Array.prototype.includes(value, offset).

if (null === shortest || shortest > delta) { ... }

putting the literal value on the left side of the comparison operator helps to detect some typos early on, when one accidentally uses the assignment operator = instead of the comparison operator == or === within a comparison expression. However, this also makes the comparison more difficult to read. I prefer the other way around.

const offsetA = Math.abs(closest.value - value)

this is actually a delta and not an offset. I suggest const deltaNext or similar.

let closest, comparativeValue

closest is not necessarily the closest value. It is the next larger value.
Also, consistency would demand either attaching the redundant Value suffix to both identifiers or none.
Putting each variable declaration on its own line improves readability, but I also prefer giving each declaration its own let as this simplifies modifications in the future.

if (offset === true) { ... }

instead of strict comparison, I'd simply check for a truthy value via if (offset) { ... }. This duck typing approach fits better with the language. You already use it when writing if (!offset && !next) { ... } or if (comparativeValue) { ... }.

shortest = delta

now you have closest (which is actually the next larger value), comparativeValue, shortest (which is actually the minimum delta), delta, this.delta, offset (which is actually a boolean flag) etc. It is hard to follow your naming scheme. I suggest more descriptive and more consistent naming.
Also, I wouldn't declare both an instance property this.delta and a local variable delta with different semantics.

Further suggestions:

It is not obvious to me why the arguments this.values and this.delta are given as instance properties and defined within the constructor function. By doing so, you create a stateful object which is more difficult to understand and test than e.g. a simple 'pure' function.
Also, by setting the next flag, the semantics of your method are no longer compatible to the meaning of getClosest. How about two methods findClosestEntry and findCeilingEntry? The Entry suffix indicates that the return value is a complex object containing index and value, comparable to e.g. Array.prototype.entries or Object.entries. Those established methods iterate or return [index, value] arrays instead of {index, value} objects, so you might want to consider following this established pattern, too.
Instead of passing an offset flag and relying on instance properties this.delta and this.values I suggest a method signature such as findClosestEntry(array, element, delta) and passing (or not passing) a delta argument.
I would replace the many for-loops with a single const nextIndex = values.findIndex(element => element > value). You would then have to lookup const prevValue = values[nextIndex - 1] and const nextValue = values[nextIndex] and return either one depending on the given flags. Don't forget to test for the corner case when nextIndex === -1 and consider handling it appropriately.
If you had to handle more than 20 values, I'd implement a binary search and - if the number of queries for a given array of values is large, built a binary search tree first. This would improve runtime complexity from linear to logarithmic. But for just up to 20 values, the built-in Array.prototype.findIndex or even an explicit for-loop is surely faster.


Javascript refactor if condition function I have this function

    const rank = (totalPoints, pointsRank) => {
    if (totalPoints <= pointsRank[0]) {
        return ({
            rank: 1,
            pointsLeftForNextRank: (pointsRank[1] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[1] && totalPoints < pointsRank[2]) {
        return ({
            rank: 2,
            pointsLeftForNextRank: (pointsRank[2] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[2] && totalPoints < pointsRank[3]) {
        return ({
            rank: 3,
            pointsLeftForNextRank: (pointsRank[3] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[3] && totalPoints < pointsRank[4]) {
        return ({
            rank: 4,
            pointsLeftForNextRank: (pointsRank[4] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[4] && totalPoints < pointsRank[5]) {
        return ({
            rank: 5,
            pointsLeftForNextRank: (pointsRank[5] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[5] && totalPoints < pointsRank[6]) {
        return ({
            rank: 6,
            pointsLeftForNextRank: (pointsRank[6] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[6]) {
        return ({
            rank: 7,
            pointsLeftForNextRank: 0
        })
    }
}
module.exports = rank

and I call it like this

            let pointsRank = [150, 500, 1000, 2000, 3500, 5000, 5500]
            let totalPoints = 1200
            rank(totalPoints, pointsRank)

output

{ rank: 3, pointsLeftForNextRank: 600 }

how can I improve this function? I feel like that I wrote a lot of code which can be refactored into something smaller
like a small amount of code that does the same functionality
also, I need to know if am violating any of the SOLID principles

Basically we search for the most close number from array where our number belongs. After we find the min value, we take the index of it and add 1, because the rank starts from 1

//rank 1 : 150 - 500
//rank 2 : 500 - 1000
//rank 3 : 1000 - 2000
//rank 4 : 2000 - 3500
//rank 5 : 3500 - 5000
//rank 6 : 5000 - 5500

let pointsRank = [150, 500, 1000, 2000, 3500, 5000, 5500]

function rank(pointsRank, score) {
  var closest = pointsRank.reduce(function(prev, curr) {
    return (Math.abs(curr - score) < Math.abs(prev - score) ? curr : prev);
  });
  var rank = pointsRank.indexOf(closest) + 1; // cuz starts from 0 and we don't have rank 0
  console.log("min range: " + closest +
    " | our score: " + score +
    " | max range: " + pointsRank[rank])

  return {
    rank: rank,
    pointsLeftForNextRank: (pointsRank[rank] - score)
  }

}

const test1 = rank(pointsRank, 1200);
const test2 = rank(pointsRank, 2000);
const test3 = rank(pointsRank, 3700);

console.log(test1);
console.log(test2);
console.log(test3);


Find a palindrome using Ruby I am preparing for an upcoming exam and have the following practice question..

  Write a method to determine if a word is a palindrome, without using
  the reverse method.

Most of you probably know what a palindrome is, but for those that don't.. a palindrome is a word which reads the same backward or forward.

Anyway, here's my answer to the question. I've written my own reverse method as directed.

How would you refactor this?

def reverse(word_arr)
  reverse = []
  index = word_arr.length
  until index == 0 do
    reverse << word_arr[index - 1]
    index -= 1
  end
  reverse
end

def is_palindrome?(word)
  word_arr = word.downcase.gsub(/ /,'').split('')
  true if word_arr == reverse(word_arr)
end

p is_palindrome?('Anna')
p is_palindrome?('Joe')
p is_palindrome?('Go dog')

What if you changed the algorithm to do the following steps?

Remove all Spaces
If String Length is Odd, delete middle character
Split string in half
Reverse one of the halves
Compare the two halves

Rationale: In your case, you reverse the entire string, even when it's very large, when you really only need to reverse the first half of the string.


Detecting the presence of multiple URL segments I have two versions of a function that performs the same task, however I'm not sure which one to use. Speed is something to take into consideration, but I also want to know what the best practice is. Below is the same function, except one uses an If statement to throw an exception where as the other uses the try catch.

private string getCampaignUrl(IEnumerable<BaseFilterDto> baseFilters)
{
    try
    {
        var campaignSegments = baseFilters.Where(x => x.SegmentType == UrlSegmentType.Campaign);
        if (campaignSegments.Any())
        {
            return campaignSegments.Single().Url;
        }
        return string.Empty;
    }
    catch (InvalidOperationException ex)
    {
        throw new InvalidDuplicateUrlSegmentException("Multiple Campaign Url Segments Found", ex);
    }
}

private string getCampaignUrl(IEnumerable<BaseFilterDto> baseFilters)
{
    var campaignSegments = baseFilters.Where(x => x.SegmentType == UrlSegmentType.Campaign);
    if (campaignSegments.Any())
    {
        if (campaignSegments.Count() != 1)
        {
            throw new InvalidDuplicateUrlSegmentException("Multiple Campaign Url Segments Found");
        }
        return baseFilters.Single(x => x.SegmentType == UrlSegmentType.Campaign).Url;
    }
    return string.Empty;
}

Throwing custom exception

I find the second version is cleaner as it clearly communicates which condition caused the exception. With the first one, you need to know it's about Single which you need to read the documentation for.

Implemention

However, as far as the implementation logic is concerned this is doing a lot of querying and the source baseFilters will be queried 3 times!

I'd be a good idea to call ToList on this to make it a one-time operation:

baseFilters.Where(x => x.SegmentType == UrlSegmentType.Campaign).ToList()

Alternative

I have an extension to deal with such cases. I call it SingleOrThrow. It lets you to define two exceptions. One for when there are no elements and one for when there are too many. Otherwise it uses default ones.

    [CanBeNull]
    public static T SingleOrThrow<T>([NotNull] this IEnumerable<T> source, Func<T, bool> predicate, Func<Exception> onEmpty = null, Func<Exception> onMultiple = null)
    {
        if (source == null) throw new ArgumentNullException(nameof(source));

        var result = default(T);
        var count = 0;

        using (var enumerator = source.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                if (predicate(enumerator.Current))
                {
                    if (++count > 1)
                    {
                        throw onMultiple?.Invoke() ?? DynamicException.Create
                              (
                                  $"{source.GetType().ToPrettyString()}ContainsMoreThanOneElement",
                                  $"There is more than one element that matches the specified predicate."
                              );
                    }

                    result = enumerator.Current;
                }
            }
        }

        if (count == 0)
        {
            throw onEmpty?.Invoke() ?? DynamicException.Create
                  (
                      $"{source.GetType().ToPrettyString()}Empty",
                      $"There is no element that matches the specified predicate."
                  );
        }

        return result;
    }

With it you could do just that:

baseFilters.SingleOrThrow(
    x => x.SegmentType == UrlSegmentType.Campaign,
    onMultiple: () => new InvalidDuplicateUrlSegmentException("Multiple Campaign Url Segments Found", ex));


Recursively generating flat XML elements from hierarchical data structure My class has a method that does some stuff, and then wants to recursively operate on some data. Specifically, I'm generating an XML report whose output includes a flat list of elements derived from a hierarchical data structure.

Example Input (a Score)

{'wrapper':True, 'sub_scores':[
  {'wrapper':True, 'sub_scores':[
    {'wrapper':False, 'name':'count-objects', 'result':'pass', 'sub_scores':[]},
    {'wrapper':False, 'name':'find-object', 'result':'pass', 'sub_scores':[
      {'wrapper':False, 'name':'measure.x', 'result':'pass', 'sub_scores':[]},
      {'wrapper':False, 'name':'measure.y', 'result':'pass', 'sub_scores':[]},
    ]},
    {'wrapper':False, 'name':'find-object', 'result':'fail', 'sub_scores':[
      {'wrapper':False, 'name':'measure.x', 'result':'skip', 'sub_scores':[]},
      {'wrapper':False, 'name':'measure.y', 'result':'skip', 'sub_scores':[]},
    ]}
  ]}
]}

Desired Output

<report user="foo" time="1234">
  <summary tests="7" pass="4" fail="1" skip="2"/>
  <results file="foo.bin" />
  <samples>
    <sample name="count-objects" result="pass" />
    <sample name="find-object" result="pass" />
    <sample name="measure.x" result="pass" />
    <sample name="measure.y" result="pass" />
    <sample name="find-object" result="fail" />
    <sample name="measure.x" result="skip" />
    <sample name="measure.y" result="skip" />
  </samples>
</report>

In JavaScript or Lua I would create a helper function within my method that does the recursion. In Ruby I would create a lambda or proc that does the recursion. Is the 'right' way to do this in Python to create a helper static function? Or is there a better way to keep the original method self-contained, perhaps allowing closures over local variables?

class Scorer:
    def generate_report(self, score):
        r = etree.Element('report', {'user': getpass.getuser(), 'time': timestamp()})
        etree.SubElement(r, 'summary', {'tests': score.total(), 'pass': score.passed(),
                                        'skip': score.passed(), 'fail': score.failed()})
        etree.SubElement(r, 'results', {'file': self.results_path})
        samples = etree.SubElement(r, 'samples')
        Scorer._add_score_to_samples(samples, score)
        return r

    @staticmethod
    def _add_score_to_samples(samples, score):
        # Some scores are wrappers that should not be included in output
        if not score.wrapper:
            etree.SubElement(samples, 'sample', score.report_attr() )
        for s in score.sub_scores:
            Scorer._add_score_to_samples(samples, s)

I dislike 'polluting' my class with a private static method just to help out a specific method. However, if this is considered Pythonic, I'll happily continue down this path.

I think the code could be made better by keeping all of the XML tree-building code together.  The recursive traversal of .sub_scores could be done using a generator function.

Additionally, you might want to reduce the punctuation noise by setting XML attributes using keyword arguments.

class Scorer:
    def generate_report(self, score):
        r = etree.Element('report', user=getpass.getuser(), time=timestamp())
        etree.SubElement(r, 'summary', tests=score.total(), …)
        etree.SubElement(r, 'results', file=self.results_path)
        samples = etree.SubElement(r, 'samples')
        for sample in self._samples(score):
            etree.SubElement(samples, 'sample', sample.report_attr())
        return r

    def _samples(data):
        # Some scores are wrappers that should not be included in output
        if not data.wrapper:
            yield data
        yield from _samples(data.sub_scores)

Alternatively, you could write _samples as a nested function.

class Scorer:
    def generate_report(self, score):
        def extract_samples(data):
            # Some scores are wrappers that should not be included in output
            if not data.wrapper:
                yield data
            yield from extract_samples(data.sub_scores)

        r = etree.Element('report', user=getpass.getuser(), time=timestamp())
        etree.SubElement(r, 'summary', tests=score.total(), …)
        etree.SubElement(r, 'results', file=self.results_path)
        samples = etree.SubElement(r, 'samples')
        for sample in extract_samples(score):
            etree.SubElement(samples, 'sample', sample.report_attr())
        return r


Look up parameters based on a numpy array of input values Aim: Write a function that looks up empirical parameters A, B and C for a  solar radiation model. Each parameter has a value for a certain interval of time, represented as the day of the year. For now, I basically translate the four-column (day_of_year-interval, A, B, C) table that I have on paper into the following look up. The function works, but I have a feeling that this is not the most Pythonic way to do it.

Current implementation:

import numpy as np

def lookup_DNI_parameters(day_of_year):
    """Sets parameters A, B, and C for the calculation of direct normal irradiance
    based on day of year-intervals.

    A is in W/m^2
    B and C are dimensionless
    """
    A = np.empty_like(day_of_year)
    B = np.empty_like(day_of_year)
    C = np.empty_like(day_of_year)

    # generate boolean indices for each day_of_year-interval
    interval_1 = np.logical_and(day_of_year >=1, day_of_year < 32)
    interval_2 = np.logical_and(day_of_year >= 32, day_of_year < 60)
    interval_3 = np.logical_and(day_of_year >= 60, day_of_year < 91)
    interval_4 = np.logical_and(day_of_year >= 91, day_of_year < 121)
    interval_5 = np.logical_and(day_of_year >= 121, day_of_year < 152)
    interval_6 = np.logical_and(day_of_year >= 152, day_of_year < 182)
    interval_7 = np.logical_and(day_of_year >= 182, day_of_year < 213)
    interval_8 = np.logical_and(day_of_year >= 213, day_of_year < 244)
    interval_9 = np.logical_and(day_of_year >= 244, day_of_year < 274)
    interval_10 = np.logical_and(day_of_year >= 274, day_of_year < 305)
    interval_11 = np.logical_and(day_of_year >= 305, day_of_year < 335)
    interval_12 = day_of_year >= 335

    # set parameter values based on the interval
    A[interval_1] = 1230.0
    A[interval_2] = 1215.0
    A[interval_3] = 1186.0
    A[interval_4] = 1136.0
    A[interval_5] = 1104.0
    A[interval_6] = 1088.0
    A[interval_7] = 1085.0
    A[interval_8] = 1107.0
    A[interval_9] = 1152.0
    A[interval_10] = 1193.0
    A[interval_11] = 1221.0
    A[interval_12] = 1234.0

    B[interval_1] = 0.142
    B[interval_2] = 0.144
    B[interval_3] = 0.156
    B[interval_4] = 0.180
    B[interval_5] = 0.196
    B[interval_6] = 0.205
    B[interval_7] = 0.207
    B[interval_8] = 0.201
    B[interval_9] = 0.177
    B[interval_10] = 0.160
    B[interval_11] = 0.149
    B[interval_12] = 0.142

    C[interval_1] = 0.058
    C[interval_2] = 0.060
    C[interval_3] = 0.071
    C[interval_4] = 0.097
    C[interval_5] = 0.121
    C[interval_6] = 0.134
    C[interval_7] = 0.136
    C[interval_8] = 0.122
    C[interval_9] = 0.092
    C[interval_10] = 0.073
    C[interval_11] = 0.063
    C[interval_12] = 0.057

    return A, B, C

# test an array of a few sample days for correctness of results
days = np.array([21., 80., 141., 202., 264., 325.])
A, B, C = lookup_DNI_parameters(days)
print A # [1230, 1186, 1104, 1085, 1152, 1221]
print B # [0.142, 0.156, 0.196, 0.207, 0.177, 0.149]
print C # [0.058, 0.060, 0.071, 0.121, 0.136, 0.092, 0.063]

So you are doing a lookup over many intervals.  A repeated pattern like that can be turned into a loop or vectorized

The repeated boilerplate suggests an iterative solution - looping over an array (or list) of dates and values.  It doesn't save on run time, and may, or may not, be more maintainable.

def lookup_DNI_parameters1(day_of_year):
    """solution based on iterating over ranges of dates
    """
    A = np.empty_like(day_of_year)
    dates = [1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
    Avalues = [1230.0, 1215.0, 1186.0, 1136.0, 1104.0, 1088.0, 1085.0, 1107.0, 1152.0, 1193.0, 1221.0, 1234.0]
    for i in range(len(dates)-1):
        interval = np.logical_and(day_of_year >= dates[i], day_of_year < dates[i+1])
        A[interval] = Avalues[i]
    # similarly for B and C
    return A

The operation can also be vectorized (in MATLAB as well as numpy), by constructing a matrix that compares the whole day_of_year array against the dates intervals array(s).  The [:,None] broadcasting may be novel to a MATLAB user.

def lookup_DNI_parameters2(day_of_year):
    """solution based on vectorized matching of days
    """
    dates = [1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
    dates1 = np.array(dates[:-1]) # interval start
    dates2 = np.array(dates[1:]) # interval stop
    Avalues = [1230.0, 1215.0, 1186.0, 1136.0, 1104.0, 1088.0, 1085.0, 1107.0, 1152.0, 1193.0, 1221.0, 1234.0]
    Avalues = np.array(Avalues)
    I = (dates1[:,None] <= day_of_year) & (day_of_year < dates2[:,None]) # boolean index array
    I = np.where(I)[0]  # convert to numeric index
    return Avalues[I]

Or this could be generalized to use a dates parameter, and a values array that has information for A, B and C:

def lookup_DNI_parameters3(day_of_year, dates, values):
    """solution based on vectorized matching of days
    """
    dates1 = np.array(dates[:-1]) # interval start
    dates2 = np.array(dates[1:]) # interval stop
    I = (dates1[:,None] <= day_of_year) & (day_of_year < dates2[:,None]) # boolean index array
    I = np.where(I)[0]  # convert to numeric index
    return values[...,I]

dates = [1, 32, 60, 91,...]
values = np.array([[1230.0, 1215.0,...], [142., 144., ...], [...]])
lookup_DNI_parameters3(day_of_years, dates, values)


Read text from stream char by char I've started learning F# and functional programming in general, but the code I wrote doesn't seems to be really functional. Could you take a look and say how to make it more as it should be in functional programming?

type internal CsvReader(source : Stream) =

    // input stream
    let stream = source

    // reader
    let mutable reader : StreamReader = new StreamReader(source)

    [<Literal>]
    let bufferSize = 1000

    // currently processed line
    let mutable buffer : char[] = Array.zeroCreate bufferSize

    // current position
    let mutable currentPosition : int = bufferSize

    // end of file
    let mutable EndOfFile : bool = false

    // loads new chunk of data from file to buffer
    let UpdateBuffer() : bool =
        match reader.ReadBlock(buffer, 0, buffer.Length) with
        | 0 -> false
        | _ -> true

    // initialization method
    let Initialize() =
        let pos = source.Seek(0L, SeekOrigin.Begin)
        if not (pos = 0L) then raise(Exception("sdf"))
        ()

    // read one char from stream
    let rec GetChar(eat : bool) : (bool * char) =
        let position = currentPosition
        match position with
        | 1000 ->
            match UpdateBuffer() with
            | false ->
                EndOfFile <- true
                (false, Char.MinValue)
            | true -> currentPosition <- 0; GetChar(eat)
        | _ ->
            let item = System.Convert.ToInt32(buffer.[position])
            match item with
            | 0 -> (false, Char.MinValue)
            | _ ->
                match eat with
                | true ->
                    currentPosition <- currentPosition + 1;
                    (true, buffer.[position])
                | false ->
                    (true, buffer.[position])

    // default constructor logic
    do
        if Utils.IsNull source then raise(ArgumentNullException("source"))
        if not source.CanRead then raise(ArgumentException("source"))
        if not source.CanSeek then raise(ArgumentException("source"))

        Initialize()

        ()

    // parameterless constructor
    // always throws ArgumentNullException
    private new() = CsvReader(null)

    // just for testing
    member x.PublicGetChar = GetChar

Right now the only think it does it stream content of Stream char by char by PublicGetChar method. I wrote UT to make sure it works:

[<TestClass>]
type CsvReaderTests() =

    let GetStringStream(input : string) : Stream =
        let stream = new MemoryStream()
        let writer = new StreamWriter(stream)
        ignore(writer.Write(input))
        writer.Flush()
        stream.Position <- 0L
        stream :> Stream

    [<TestMethod>]
    member this.TestMethod1 () =
        let input = "test"
        let reader = new CsvReader(GetStringStream(input))
        let chars = seq { while fst(reader.PublicGetChar(false)) do yield snd(reader.PublicGetChar(true)) }
        let output = (new System.String(chars |> Array.ofSeq))
        input |> should equal output

Main concerns I have about the code:

usage of match/with
a lot of mutable stuff within CsvReader type
if I had to write it in C# it would look really similar :D

That's the very first F# code I've ever written, so be polite, please :)

Your first F# code isn't too bad. I've made some small simplifications to streamline your code a bit and take advantage of some built-in F# functions:

type internal CsvReader(source : Stream) =

    // input stream
    let stream = source

    // reader
    let mutable reader : StreamReader = new StreamReader(source)

    [<Literal>]
    let bufferSize = 1000

    // currently processed line
    let mutable buffer : char[] = Array.zeroCreate bufferSize

    // current position
    let mutable currentPosition = bufferSize

    // end of file
    let mutable EndOfFile = false

    // loads new chunk of data from file to buffer
    let UpdateBuffer() : bool =
        reader.ReadBlock(buffer, 0, buffer.Length) <> 0

    // initialization method
    let Initialize() =
        let pos = source.Seek(0L, SeekOrigin.Begin)
        if not (pos = 0L) then
            invalidOp "sdf"

    // read one char from stream
    let rec GetChar(eat : bool) : (bool * char) =
        let position = currentPosition
        match position with
        | 1000 ->
            match UpdateBuffer() with
            | false ->
                EndOfFile <- true
                false, Char.MinValue
            | true ->
                currentPosition <- 0
                GetChar eat
        | _ ->
            match int buffer.[position] with
            | 0 ->
                false, Char.MinValue
            | _ ->
                match eat with
                | true ->
                    currentPosition <- currentPosition + 1
                    true, buffer.[position]
                | false ->
                    true, buffer.[position]

    // default constructor logic
    do
        if Utils.IsNull source then
            nullArg "source"
        if not source.CanRead then
            invalidArg "source" "The source stream cannot be read from."
        if not source.CanSeek then
            invalidArg "source" "The source stream does not support seeking."

        Initialize()

    // parameterless constructor
    // always throws ArgumentNullException
    private new() = CsvReader(null)

    // just for testing
    member x.PublicGetChar = GetChar

One thing you'd definitely want to add (if this were production code) -- this class would ideally implement the IDisposable interface so you can properly close and release the resources associated with the StreamReader you use internally.


Selection sort algorithm in Rust I am just trying to use Rust so I will be thankful for all remarks and corrections:

fn selection_sort(array: &mut [i32]) {

    let mut min;

    for i in 0..array.len() {

        min = i;

        for j in (i+1)..array.len() {

            if array[j] < array[min] {
                min = j;
            }
        }

        let tmp = array[i];
        array[i] = array[min];
        array[min] = tmp;
    }
}

fn main() {

    let mut values = [ 5, 8, 4, 1, 7, 2, 3, 6 ];
    println!("Hello, world! The value is {:?}", values);

    selection_sort(&mut values);
    println!("Hello, world! The value is {:?}", values);
}

You could use min_by_key to find the minimum's index and the method swap defined in slices:

fn selection_sort(array: &mut [i32]) {
    let len = array.len();
    for i in 0..len {
        let min = (i..len).min_by_key(|x| array[*x])
                          .unwrap();
        array.swap(min, i);
    }
}


Lazily combine ranges dependent on modulo with one loop I have a positive integer n. I want to lazily loop over a range of integers less than n consisting of a) integers divisible by 3 (excluding zero) in reversed sorted order and b) zero and integers not divisible by 3 in any order. Is this a very stupid solution? I couldn't think of another way of doing it without having to make use two loops.

d = divisor = 3
list(itertools.chain(
    itertools.chain(*zip(*(((i),(i-1),(i-2)) for i in range(d*((n-1)//d),0,-d)))),
    (0,),range(n-1,d*((n-1)//d),-1)))

>>> n = 18
[15, 12, 9, 6, 3, 14, 11, 8, 5, 2, 13, 10, 7, 4, 1, 0, 17, 16]

>>> n = 17
[15, 12, 9, 6, 3, 14, 11, 8, 5, 2, 13, 10, 7, 4, 1, 0, 16]

>>> n = 16
[15, 12, 9, 6, 3, 14, 11, 8, 5, 2, 13, 10, 7, 4, 1, 0]

>>> n = 4
[3, 2, 1, 0]

>>> n = 3
[0, 2, 1]

>>> n = 2
[0, 1]

>>> n = 1
[0]

Code is read far more often than written.
So I prefer to make code as readable as possible.
Clever code is very often not good code.

I find the posted code very hard to read,
and I don't see why it has to be that way.

I believe this simple, straightforward implementation meets your posted requirements and very easy to read.

def gen(n):
    for x in range(n - 1, divisor - 1, -1):
        if x % divisor == 0:
            yield x
    yield 0
    for x in range(n):
        if x % divisor:
            yield x


Match a simple balanced language I apologise if the title is not very descriptive. If someone can recommend a clearer one I'll edit it. I have an exercise question as:

  The language L={anbn} where n ≥ 1, is a language of all words with
  the following properties:

  The words consist of strings of a’s followed by b’s.
  The number of b’s is equal the number of a’s.
  Examples of words that belong to L are:

  ab, where n=1;

  aabb, where n=2;

  aaabbb, where n=3;

  aaaabbbb, where n=4.

  One way to test if a word w belong to this language L is to use a
  stack to check if the number of a’s balances the number of b’s. Use
  the following header and write a function isInLanguageL2 that
  uses a stack to test if any word belongs to L. If w belongs to L
  then the isInLanguageL2 should return true otherwise
  isInLanguageL2 should return false.

  bool isInLanguageL(string w);

  Note the following:

  Only words belonging to L should be accepted.
  The word bbaa does not belong to L.
  Do not count the number of a’s or b’s.

I've written the following code which solves the problem.

bool isInLanguageL2(string w){

    linkedStackType<string> wordStack;

    int size = w.length();
    int a = 0;
    int b = 0;

    if(size % 2 != 0)   //word length must be an equal number
        return false;
    else{
        //read first half of word
        for(int i = 0; i < size/2; i++){    //check if the first half consists of A's
            if(w[i] != 'a' && w[i] != 'A')
                return false;
            else
                wordStack.push(string(1, w[i])); //convert char to string and push to stack if the letter is valid
        }

        //read second half of word
        for(int i = size/2; i < size; i++){     //check if the second half consists of B's
            if(w[i] != 'b' && w[i] != 'B')
                return false;
            else
                wordStack.push(string(1, w[i]));    //convert char to string and push to stack if the letter is valid
        }
    }

    //check number of A's and B's in the stack
    while(!wordStack.isEmptyStack()){
        if(wordStack.top() == "b" || wordStack.top() == "B"){
            b++;
            wordStack.pop();
        }
        else{
            a++;
            wordStack.pop();
        }
    }

    //check if number of B's is equal to number of A's
    if(b==a)
        return true;

}

However, since the question says "Do not count the number of a’s or b’s.", I've instead created two stacks and just compared their lengths. Is there a way to do this using a single stack since the question mentions using a stack without explicitly counting the A's and B's to test the word.

bool isInLanguageL2(string w){

    linkedStackType<string> wordStackA, wordStackB;

    int size = w.length();
    int a = 0;
    int b = 0;

    if(size % 2 != 0)   //word length must be an equal number
        return false;
    else{
        //read first half of word
        for(int i = 0; i < size/2; i++){    //check if the first half consists of A's
            if(w[i] != 'a' && w[i] != 'A')
                return false;
            else
                wordStackA.push(string(1, w[i])); //convert char to string and push to stack if the letter is valid
        }

        //read second half of word
        for(int i = size/2; i < size; i++){     //check if the second half consists of B's
            if(w[i] != 'b' && w[i] != 'B')
                return false;
            else
                wordStackB.push(string(1, w[i]));    //convert char to string and push to stack if the letter is valid
        }
    }

    //check if number of B's is equal to number of A's
    if(wordStackA.length() == wordStackB.length());
        return true;

}

Also, I have a follow up to this question. A sort of extension. Should I add it here or create a new question for it as it might make this question rather long.

This exercise is somewhat unsettling. On the one hand, a stack, as part of a pushdown automaton, is the canonical way to decide balanced languages such as this one; on the other hand, there are much more efficient, idiomatic and practical ways to solve that particular exercise. It is unclear whether it's a computer science exercise or a language learning exercise, one to make concepts sink in or one to discover C++'s expressiveness.

A stack would have been more easily justified if the function argument had been a std::istream& for instance, since it can be traversed only once; or if starting / ending tags had come of different kinds (if they're all the same an integer makes for a perfect stack and counting shouldn't be discriminated).

As @Mike Borland said, the trick to answer that question is to avoid explicit counting by popping the stack filled with as while you iterate over the rest of the string. Something along the lines:

#include <stack>
#include <string>

bool is_ab_balanced(const std::string& str) {
    if (!str.size()) return false;
    auto it = str.begin();
    std::stack<char> as;
    while (it != str.end() && *it == 'a') as.push(*it++);
    while (!as.empty()) {
        if (it == str.end() || *it != 'b') return false;
        as.pop(); ++it;
    }
    return it == str.end();
}

By the way, you'll notice that:

it always is better to use standardized containers unless you need customized behavior: std::stack is certainly better optimized and tested than linkedStackType<>
you shouldn't take a string by value as an argument, unless you intend to modify it while keeping the original string unchanged. Here, there's no modification, so use a const reference instead.
you should get rid of unused variables (see a and b in your second version). Those superfluous variables probably are a by-product of bad habits: declaring variables too far ahead of their use, and not enabling all warnings when you compile your code.
iterators are a better way to iterate over a range: it's more idiomatic, it's necessary to leverage the power of the STL, and it also avoids that extra size variable.
A few more key-strokes are better than using namespace std, which is is a bad idea

But, as I said, a good exercise should look more like real life. In real life, you use a stack only if it is the best way to go. So how would you check if a string belongs to the language if you could choose without restriction?

My take on that would be:

#include <string>
#include <algorithm>

using Iterator = std::string::iterator;
bool is_balanced(Iterator first, Iterator last) {
    auto middle = std::next(first, std::distance(first, last) / 2);
    return std::equal(first, middle, middle, last, [](auto a, auto b) {
        return a == 'a' && b == 'b';
    });
}

Or, other more meaningful exercises would have been:

how would you check if parenthesis are balanced in an expression (I wouldn't use a stack here either)?
how would you check if html tags are correctly balanced (here using a stack is meaningful)?


Merging Digital River I am solving this question:

  It's not the rivers that you might be thinking about. The question
  revolves around the concept of digital rivers. A digital river is a
  sequence of numbers where the number following n is n plus the sum of
  its digits.

  FOR EXAMPLE

  12345 is followed by 12360 since 1+2+3+4+5=15 and so 12345 + 15 gives
  12360. similarly 145 is followed by 155. If the unit's digit of a digital river is 'M' we will call it river 'M'. For example, 231 would
  be called river 1.

  river 480 is the sequence beginning {480,492,507,519....} river 483 is
  the sequence beginning {483,498,519,....}. normal streams and rivers
  can meet, and the same is true for digital rivers. This happens when
  two digital rivers share some of the same values.

  FOR EXAMPLE:

  River 480 meets river 483 at 519. river 480 meets river 507 at 507 and
  never meets river 481. Every digital river will eventually meet river
  1, river 3 or river 9.

  Write a program that can determine for a given integer n the value
  where river n first meets one of these three rivers.

  Input

  The input may contain multiple test cases. Each test case occupies a
  separate line and contains an integer \$n\$ (\$1 \le n \le 16384\$). A test case with value of 0 for n terminates the input and this test case must not
  be processed.

  Output

  For each test case in the input first output the test case
  number (starting from 1) as shown in the sample output. Then on a
  separate line output the line "first meets river x at y". Here y is the
  lowest value where river n first meets river x (x = 1 or 3 or 9).If
  river n meets river x at y for more than one value of x, output the
  lowest value. Print a blank line between two consecutive test cases.

  Input:

    86

    12345

    0

  Output:

    Case #1

    first meets river 1 at 101

    Case #2

    first meets river 3 at 12423

Here is the code to solve it:

#include<iostream>
using namespace std;
int sum_of_digits(int);
int connect(int start_number, int chk_number)
{
    while (true)
    {
        if (start_number>chk_number) break;
        else if (start_number == chk_number) return chk_number;
        else start_number += sum_of_digits(start_number);
    }
    return -1;
}
int sum_of_digits(int number)
{
    int sum_of_digit = 0;
    while (number>0)
    {
        sum_of_digit += number % 10;
        number /= 10;
    }
    return sum_of_digit;
}

int main()
{
    int x, temp;
    int m = 1;
    while (x != 0)
    {
        cin >> x;
        temp = x;
        bool flag = false;
        while (true)
        {
            for (int i = 1; i < 10;)
            {
                if (connect(i, temp) != -1)
                {
                    cout << "Case #" << m << endl;
                    cout << "first meets river of " << i << " at " << temp;
                    flag = true;
                    break;
                }
                if (i == 1) i = 3;
                else if (i == 3) i = 9;
                else break;
            }
            if (flag) break;
            temp += sum_of_digits(temp);

        }
    }
    return 0;
}

And I'm stuck because it takes more than 1 sec on some inputs. Please help me optimize it to below 1 second on any inputs.

Don't tell anything on using namespace std; and look at it as C code not C++ code. As it was in a competition I was in a hurry. It worked in the competition but now I want to make it fast.

Your code is disappointing.... as C++. Really, it is a C program written in C++. There's no classes, objects, instances, etc. In part, this is one of the reasons your code is slow.

A natural consequence of the way you compute your answers is that you have to re-build the entire stream 1, 3, and 9 sequences each time the code encounters a new test. If you had a "stream" class for each of the three base classes, and you "remembered" the stream, and made it searchable, then you would have a way to look up whether a test stream value joins. Using an iterator would make sense for the process too.

Iterate the stream, find if there is an intersection, move on.

your code is actually far worse than I realized when it comes to calculating the base 1,3, and 9 streams.... it rebuilds each stream each time you test a new value, for each new value in each test case... thus, for example, you could be computing millions, and millions of values unnecessarily.

You need to "remember" and "index" the base streams, and you'll fare much better.

Also, use the language to your advantage: classes, iterators, vectors, etc.


Backup files at the end of the day This is my first attempt at writing code that moves files at the end of the day, from my local work folder to an network archive.

The program works but, any tips, tricks, or ideas to make this code better would be most appreciated.

import shutil, os, datetime, time, sys

os.system('TASKKILL /F /IM FlashRen.exe')

newFolderName = datetime.datetime.now()
newFolder = newFolderName.strftime('%m%d%Y')

src = ('C:\\AEC Work\\' + newFolder)
dst = ('\\\qnap01\\Data Service\\AARON\\' +
           newFolderName.strftime('%Y\\') +
           newFolderName.strftime('%m. %B\\').upper() + newFolder)

for file in os.listdir(src):
    src_file = os.path.join(src, file)
    dst_file = os.path.join(dst, file)
    shutil.move(src, dst)

Doing multiple imports on the same line from different modules is frowned upon by PEP8, Python's official style-guide.

It also recommends using lower_case for variable names and not camelCase.

You don't need () around variables when assigning, src = 'C:\AEC Work\' + newFolder is enough.

Since you are already using os.path.join, which is a good thing, you should use it throughout.

You can use str.format to get "{:%m%d%Y}".format(datetime.datetime.now()) for the new folder name to make this slightly more compact.

import shutil
import os
import datetime
import time
import sys

os.system('TASKKILL /F /IM FlashRen.exe')

now = datetime.datetime.now()
directory = "{:%m%d%Y}".format(now)

src = os.path.join('C:','AEC Work', directory)
backup_base = os.path.join('\qnap01', 'Data Service', 'AARON')
dst = os.path.join(backup_base, "{:%Y}".format(now),
                   "{:%m. %B}".format(now).upper(), directory)

for file in os.listdir(src):
    src_file = os.path.join(src, file)
    dst_file = os.path.join(dst, file)
    shutil.move(src, dst)


Python maintain precision for currency Working with currencies I am aware it is not good to work with floating point values due to rounding and maintaining precision. Better is to work with integers. Would the following Currency class make sense, where an amount is defined as an instance of Currency and converted to cents.

class Currency():

    def __init__(self, value):
        self._cents = int(round(value*100,0))

    def __add__(self, other):
        return self.__class__((self._cents + other._cents)/100)

    def __sub__(self, other):
        return self.__class__((self._cents - other._cents)/100)

    def __mul__(self, factor):
        if type(factor) not in [int, float]:
            raise ValueError('factor must be a scalar')

        return self.__class__(factor * self._cents / 100)

    def __rmul__(self, factor):
        if type(factor) not in [int, float]:
            raise ValueError('factor must be a scalar')

        return self.__class__(factor * self._cents / 100)

    def __truediv__(self, divisor):
        if type(divisor) not in [int, float]:
            raise ValueError('divisor must be a scalar')

        if divisor != 0:
            return self.__class__(self._cents / divisor / 100)
        else:
            raise ValueError('Cannot divide by zero')

    def __repr__(self):
        return str(f'{self._cents/100:,.2f}')

    def __str__(self):
        return str(f'{self._cents/100:,.2f}')

    @property
    def dollars(self):
        return self._cents / 100

    @property
    def cents(self):
        return self._cents

Some results

>>> from money import Currency
>>> a = Currency(100)
>>> b = Currency(0.01)
>>> a+b
100.01
>>> a*2
200.00
>>> a/2
50.00
>>> 2*a
200.00
>>> total = Currency(0)
>>> for i in range(10_000_000):
...     total += b
...
>>> total
100,000.00
>>> a.dollars
100.0
>>> b.cents
1
>>>
```

Since you are using f strings I will presume you are using python 3.6 or later.

def __init__(self, value):
    self._cents = int(round(value * 100, 0))

Good job prefixing cents with an underscore. I think it is a good choice to make the variable "private".

By leaving out the second parameter from round, or by passing None, the returned value will be rounded to an integer. You could instead write

def __init__(self, value):
    self._cents = round(value * 100)

Note that round may not behave as you expect. Depending on the value given it may round the opposite way to what you'd expect.

def __add__(self, other):
    return self.__class__((self._cents + other._cents) / 100)

It is good that you've accounted for subclassing. Since you've had to do some work to make a new class to return, maybe that indicates you could use an alternative constructor that takes cents directly?

Unfortunately you don't do any type checking here, so the error message a user receives is not very helpful.

a = Currency(2.345)
print(a)  # 2.35
a + 2.03  # AttributeError: 'float' object has no attribute '_cents'

I would suggest type checking as you've done in mul, making sure only currency can be added to currency

def __add__(self, other):
    if not isinstance(other, Currency):
        raise TypeError(f"Unsupported type, cannot add {self.__class__} and {other.__class__}")
    ...

def __mul__(self, factor):
    if type(factor) not in [int, float]:
        raise ValueError('factor must be a scalar')

From this stackoverflow answer, isinstance is preferred over type. Also from the same answer, duck typing is preferred over isinstance. Since we don't want to have to update this list every time we find a new type that is acceptable to multiply by, lets just try it and see if it works. Multiplying a currency will then just work unless there is a reason it shouldn't. One exception might be multiplying currency by currency. Should that be allowed?

def __mul__(self, factor):
    try:
        return self.__class__(factor * self._cents / 100)
    except TypeError:
        raise TypeError(f"...")

This isn't perfect, as we may lose useful information about what doesn't work (Did the constructor fail? Did the multiplication fail? etc) but it is good enough.

# Example of currency just working with fractions
a = Currency(8.08)
a * fraction.Fraction(1, 4)   # 2.02

def __truediv__(self, divisor):
    if type(divisor) not in [int, float]:
        raise ValueError('divisor must be a scalar')

    if divisor != 0:
        return self.__class__(self._cents / divisor / 100)
    else:
        raise ValueError('Cannot divide by zero')

Since an exception is raised if you try to divide a currency by 0, I don't see an advantage of making it a ValueError over a ZeroDivisionError. It wold actually remove the error handling since it doesn't add much, and let the user catch it if they want to.

If there is a usecase for it, it may be worth defining div too. It could be as simple as

__div__ = __truediv__

def __repr__(self):
    return str(f'{self._cents/100:,.2f}')

def __str__(self):
    return str(f'{self._cents/100:,.2f}')

This is repeated code. You can deduplicate with either

def __repr__(self):
    return str(self)

or

__repr__ = __str__

@property
def dollars(self):
    return self._cents / 100

@property
def cents(self):
    return self._cents

These do not make sense to me. I would expect dollars to return the number of dollars present, and cents to just return the number of cents

c = Currency(7.89)
c.dollars  # 7.89, I expected 7
c.cents  # 789, I expected 89

You also could implement dollars.setter and cents.setter so you can change just one of them.

Here I will list things I would do differently. That doesn't mean I'm right and you are wrong, it means food for thought, but reject ideas away if they don't suit.

Use decimal. It was made for arithmetic on numbers where precision matters. It also has the work on dealing with other python numbers pretty much done for you. It also lets you choose how to round which may be important if you need banker's rounding.
Add a constructor for making an amount from dollars and cents. Something like Currency(dollars=7, cents=89) would be nice to use. The implementation is a little trickier (what if cents >= 100, what if dollars is negative).
Due to the rounding, working with this class may look unfair to whoever owns the money. Currency(5.05) / 2 * 2 == Currency(5.04) != Currency(5.05). By doing what should be nothing, they've lost a cent! To exaggerate the problem, lets say you have Currency(74.49) to divide amongst 12 people. Currency(74.49) / 12 outputs Currency(6.21). You give each person that amount Currency(6.21) * 12 == Currency(74.52), and you find you are 3 cent out of pocket. This is when auditors come in and start asking questions.


Factor script to change case of all filenames in a directory In the absence of a full-fledged tutorial, I am teaching myself to program in the Factor language by writing a bunch of functions that I will eventually use in command-line scripts.

One common operation I like to perform is to change the case of names of files contained in a given directory to uppercase or lowercase.  I wrote the following code to perform this operation in Factor:

USING: fry kernel io.directories sequences unicode.case ;
IN: util.directories

: move-each-directory-file>lower ( pathname -- )
    [ dup >lower ] move-each-directory-file ;

: move-each-directory-file>upper ( pathname -- )
    [ dup >upper ] move-each-directory-file ;

: each-directory-file ( pathname quot -- )
    '[ [ @ ] each ] with-directory-files ; inline

: move-each-directory-file ( pathname quot -- )
    '[ @ move-file ] each-directory-file ; inline

I have tried to factor as much code as possible into a reusable vocabulary.  I look forward to suggestions for improvement.

Comments! Comments are good, especially to people who are just learning Factor right now. Admittedly, for Factor, it's pretty readable -- I finally got it, after staring a while and doing lots of Googling -- but comments are always nice.

I can't find anything about the : name>something ( etc -- etc ) word syntax online -- namely, the >something part. Because of that, I'm just gonna assume that it's good syntax and move on. Alright, I finally found it! And yes, that's good syntax -- you're supposed to use a>b for functions converting a to b, and that's exactly what you do. It might be better called directory-file-names>upper/>lower, but that's just personal preference.

It looks good, though. After figuring out how Factor works, it's pretty readable (for Factor), and actually makes me want to use the language more. Plus, as far as I can tell, you're following the official coding style to the letter. Well done.


Handling external API calls status code in my application I have a Web API application in .NET Core 3.1. In a controller I have a GET action that must return a JSON object with a name and a description. In order to retrieve the correct description I need to call an external API (not implemented by myself and outside of my control). This is the code in the controller:

public async Task<ActionResult<Models.Result>> Get(string name)
{
    try
    {
        var objectWrapper = await _clientService.GetObjectAsync(name.ToLowerInvariant());

        //Other logic here....

        return Ok(new Models.Result { Name = name, Description = objectWrapper.Description} );
    }
    catch (Exception ex)
    {
        _logger.LogError($"Failed to get object {name}: {ex}");
        if (ex is ApiCallFailedException apiCallEx)
            return StatusCode((int)apiCallEx.HttpStatusCode);

        return BadRequest($"Failed to get object {name}");
     }
}

The _clientService is the service responsible for the call to the external API:

public async Task<ObjectDto> GetObjectAsync(string name)
{
    var objectWrapper = new ObjectDto();

    var request = new HttpRequestMessage(HttpMethod.Get, $"object/{name}/");
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    using (var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
    {
        if (response.IsSuccessStatusCode)
        {
            objectWrapper = await response.Content.ReadAsAsync<ObjectDto>();
        }
        else
        {
            throw new ApiCallFailedException(response.StatusCode);
        }
    }

    return objectWrapper;
}

Therefore, I created a custom exception class ApiCallFailedException to handle not successful status codes returned by the external API in order to be able to catch it in my controller action.
In the controller action, in caso of not successful status codes from the external API, I decided to return the same status code.

My question is: is this approach correct to handle external API call failure?

Thank you!

I have only 2 things to note.

Returning the same status code as the remote server could lead to confused clients of your API due to incorrect status codes. What if the remote server has returns a 5xx status code? Your server didn't have an internal server error, the remote did, but then why is your server returning a 5xx status code?

Instead, I recommend replacing it with returning a fixed status code (or something depending on the status code the remote API returned). The method name is Get, so I'd go with a 404 Not Found.
Use attributes. In ASP.NET and ASP.NET Core the runtime can figure out which method to call by the http method and the name of it (call Get when an http get request comes, Post when a post comes etc), but it would be a lot more obvious not only for the runtime but also for developers if you named your methods a good name (e.g GetName) and decorate it with attributes specifying the route and the http request method to respond to.

Plus, you could also do yourself and any future developer a favor by specifying where the parameter to the method comes from. Right now it's part of the URI string (also called query parameters), but other methods might accept JSON to deserialize, you can do this by adding an attribute to the parameter. More about it here.

Putting number 2 into code:

[Route("Result/GetName")]
[HttpGet]
public async Task<ActionResult<Models.Result>> GetName([FromUri] string name)
{
    // ...
}


Generate a nested structure based on a list of file paths I'm currently working on a small application, as a learning exercise for a Javascript novice. I need to generate an object based on a folder structure. Here is an example of the folder structure:

  RootFolder/FolderA/FolderB/FileA

  RootFolder/FolderA/FolderB/FileB

  RootFolder/FolderA/FolderB/FolderC/FileA

  RootFolder/FolderA/FolderB/FolderC/FileB

The desired resulting object should have the following structure:

{
    RootFolder: {
        FolderA: {
            FolderB: {
                FileA: {},
                FileB: {},
                FolderC: {
                    FileA: {},
                    FileB: {}
                }
            }
        }
    }
};

So far I came up with the following code and it seems to be doing the job, but I'm concerned with 'eval' use and generally believe there is a more elegant way of doing it.

module.exports = {
  structure: function(structureArray) {
    var generatedObject = {};
    for (var i = 0; i < structureArray.length; i++) {
      var objectElements = '';
      var path = (structureArray[i].split('/')).filter(Boolean);
      for (var l = 0; l < path.length; l++) {
        if (objectElements.indexOf(path[l]) == -1 || path[l].length == 1) {
          objectElements += '["' + path[l] + '"]';
        }
        if (!(eval('generatedObject' + objectElements))) {
          eval('generatedObject' + objectElements + '= {}')
        }
      }
    }
    return generatedObject;
  }
};

structureArray contains full path strings as in the folder structure example above (e.g. 'RootFolder/FolderA/FolderB/FileA')

You can split each path at / using split and then use reduce() to build that object.

var paths = [
  'RootFolder/FolderA/FolderB/FileA',
  'RootFolder/FolderA/FolderB/FileB',
  'RootFolder/FolderA/FolderB/FolderC/FileA',
  'RootFolder/FolderA/FolderB/FolderC/FileB'
]

var obj = {}
paths.forEach(function(path) {
  path.split('/').reduce(function(r, e) {
    return r[e] || (r[e] = {})
  }, obj)
})

console.log(obj)

Here is how you can use this approach to read some directory and all of its nested content and create object from that. This approach is synchronous.

var fs = require('fs');
var path = require('path');

var p = path.resolve('C:\\your\\path\\here')
var result = {}

function buildObject(startPath) {
  var dir = fs.readdirSync(startPath)
  dir.forEach(function(e) {
    var newPath = path.join(startPath, e)

    var stat = fs.statSync(newPath);
    if (stat && stat.isDirectory()) buildObject(newPath)
    if (stat.isFile()) {
      newPath.split('\\').reduce(function(r, a) {
        return r[a] || (r[a] = {})
      }, result)
    }
  })
}

buildObject(p)
console.log(result)


A one change boolean value I have the case of repeated very similar logic that is used to check if a boolean value was changed from the initial value and prevent it from changing back, or to summarize multiple boolean return values like:

bool SomeMethod()
{
    bool endResult = true;
    foreach(var obj in objs)
    {
        bool result = obj.Method();
        if(!result)
            endResult = false;
    }
    return endResult;
}

I reworked the logic into a class where a boolean can only be changed from the initial value, so that the boolean logic is all in one place. The IsChanged property is for LINQ queries.

public class OneUseBool
{
    private readonly bool _initValue;

    public OneUseBool(bool init)
    {
        _initValue = init;
        _currentValue = init;
        _isChanged = false;
    }

    private bool _currentValue;
    public bool CurrentValue
    {
        get { return _currentValue; }
        set
        {
            if (_initValue != value)
            {
                _currentValue = value;
                IsChanged = true;
            }
        }
    }

    private bool _isChanged;
    public bool IsChanged
    {
        get { return _isChanged; }
        private set
        {
            if(!_isChanged)
                _isChanged = value;
        }
    }
}

So the original code gets changed to:

bool SomeMethod()
{
    OneUseBool endResult = new OneUseBool(true);
    foreach(var obj in objs)
    {
        endResult.CurrentValue = obj.Method();
    }
    return endResult.CurrentValue;
}

Is this a good way to do this sort of logic with bools, or am I just overcomplicating a simple problem?

If you can only change a bool once, and the entire purpose of a loop is to set the bool, then you should just exit the loop after the bool gets changed.  There's no point in looping more than you need to, and you also don't have to worry about the bool getting switched back.  So you can write your example like this:

bool SomeMethod()
{
    foreach(var obj in objs)
    {
        if(!obj.Method())
        {
            return false;
        }
    }
    return true;
}

You can use Enumerable.All() for this logic:

bool SomeMethod()
{
    return objs.All(x => x.Method());
}

An alternative to if(!x) y = x; in your situation is y = y && x;