Return early with Error from Sequence mapping

I can't say, I have the full understanding of computation expressions, so here are some comments that may go in another direction than your purpose with the post:

sq |> Seq.skip 1

can be replaced with
sq |> Seq.tail

I'm not sure, I like that the function returns [ Error null ] for an empty sequence, but that again may be needed in the context? I would expect an empty sequence to return - an empty sequence.

I don't understand the Projection layer, but that may be dictated by the original context.
You could define the type at the function level:
type MaybeFunction<'a, 'b, 'c> =
    | OptionFunction of ('a -> 'b option)
    | ResultFunction of ('a -> Result<'b, 'c>)

and then create the functions as:
let mbopFunction = OptionFunction (fun x -> if x < 5 then Some x else None)
let mbrsFunction = ResultFunction (fun x -> if x < 5 then Ok x else Error "if >= 5")

Your main function will then looks like:
let mapTillFail mapper s =
    let rec inner sq =
        seq {
            let mapped = orb {
                let! head = Seq.tryHead sq
                match mapper with
                | OptionFunction a ->
                  let! m = a head
                  return m
                | ResultFunction a ->
                    let! m = a head
                    return m
                }

            match mapped with
                | Error _ as err-> yield err
                | Ok _ ->
                    yield mapped
                    yield! sq |> Seq.tail |> inner
        }
    inner s

which tells that your monad can handle that level without modifications.
Maybe it would be fair to call these function Projections as well as that is what they do?

That said, you can go without the computation expression:
let mapTillFail projection data =

    let test x =
        let result =
            match projection with
            | OptionProjection a ->
                match a x with
                | Some d -> Ok d
                | None -> Error Unchecked.defaultof<'c>
            | ResultProjection a -> a x
        result

    let rec inner lst =
        seq {
            match lst |> Seq.isEmpty with
            | true -> yield Error Unchecked.defaultof<'c>
            | _ ->
                match test (lst |> Seq.head) with
                | Error e -> yield Error e
                | Ok o ->
                    yield Ok o
                    yield! inner (lst |> Seq.tail)
        }

    inner data

Another alternative is to extent the MaybeProjection or MaybeFunction with a member called calculate:
type MaybeFunction<'a, 'b, 'c> =
    | OptionFunction of ('a -> 'b option)
    | ResultFunction of ('a -> Result<'b, 'c>)
with
member this.Calculate (a) =
    match this with
    | OptionFunction f ->
        match f a with
        | Some d -> Ok d
        | None -> Error Unchecked.defaultof<'c>
    | ResultFunction f -> f a

used as:
module Seq =
    let mapTillFail (func: MaybeFunction<'a, 'b, 'c>) data =

        let rec inner lst =
            seq {
                match lst |> Seq.isEmpty with
                | true -> ()
                | _ ->
                    match func.Calculate (lst |> Seq.head) with
                    | Error e -> yield Error e
                    | Ok o ->
                        yield Ok o
                        yield! inner (lst |> Seq.tail)
            }

        inner data

Here I've made an extension to Seq so you can call it like any other Seq functions:
printfn "%A" ((r |> Seq.mapTillFail mbopFunction) |> Seq.toList)
printfn "%A" ((s |> Seq.mapTillFail mbopFunction) |> Seq.toList)
printfn "%A" ((r |> Seq.mapTillFail mbrsFunction) |> Seq.toList)
printfn "%A" ((s |> Seq.mapTillFail mbrsFunction) |> Seq.toList)


Click and/or focus outside & -webkit-tap-highlight-color

After several days of hard work, I think that I've found the answers to my questions.

The best element I've found to check for outside click/focus is $(document).

Caveat: When on iPad, the event needs to be touchstart, not click.

I've got a question going here, but here's the "trick" I'm using currently:

var foo = (('ontouchstart' in window) || (window.DocumentTouch && document instanceof DocumentTouch)) ? 'touchstart' : 'click';

I'm using this technique here to handle focus/click. Essentially, when there's keyboard tab focus, I call click and within that event handler, I call my code to check for outside focus/click/touch.
The idea I had to add a CSS class to <html> works pretty good. When the event handlers are setup to listen for focus/click/touch outside, I add the class. Once there's been focus/click/touch on the outside, I remove the class.

My CSS looks like so:

html.mw-outside * { -webkit-tap-highlight-color: rgba(0, 0, 0, 0); }

It kinda feels a little hacky, though.


Don't activate the virtualenv inside the script. If you do, the script won't be portable, it won't run on other computers, as that absolute path is specific to your computer. The virtualenv is part of the runtime execution environment, should not be part of the source code. Add a wrapper script that will activate the virtualenv and then run your app.

@route('/:anything')
def something(anything = ''):
    return template(index_html, author = anything)

I don't know bottle, but it seems to me that the default value setting anything = '' is pointless, because the path / should not match this route.

PEP8 dictates to put 2 empty lines before every global function declaration. So put 2 empty lines right before this code:

@route('/')
def index():
    return template(index_html, author = 'your name here')

This looks like a typo:

run(host = '0.0.0.0', port = port, debut = True)

You probably meant debug instead of "debut".


Random value generation for uncertainty analysis

You've clearly spent some time looking into best practices; your code is well separated, readable, logical. Keep up the formatting, and people will be happy to read over your code.

This did jump out at me though: you have two specific string literals "Normal Distribution" and "Triangular Distribution" that are repeated in separate files.. Advisable to avoid multiple instances of a string literal in future, especially in separate files; when code gets large, approaches like that can be time consuming and erroneous.

Think: constants and enums. Your compiler won't pick up on string literal typos like that, which could lead to irritating runtime errors or unexpected behaviour. On the other hand, it will of course alert you to undeclared (mistyped) handles in your code. Much more efficient bug removal.


I would not cram in the if statement like that:

auto intercalate(Fwd_It first, Fwd_It last, Out_It destFirst,
                 Fwd_It whatFirst, Fwd_It whatLast) {
    if (first == last) return destFirst;
    *destFirst = *first;
    // ...

While this style is okay at times, it may not be too readable in all situations.  Single-line statements can still use curly braces, especially if it may need to be maintained.  You could also add a new line before the line that follows it.

auto intercalate(Fwd_It first, Fwd_It last, Out_It destFirst,
                 Fwd_It whatFirst, Fwd_It whatLast) {
    if (first == last) {
        return destFirst;
    }

    *destFirst = *first;
    // ...


Handle concurrent request by waiting the result of an already running operation

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


I think I'm not using Try Except properly in this Python code

A couple things:

Instead of if job:, try if not job: ... continue .  This will allow the entire (large) content of that if-block to be outdented a level, making it a little more readable.
Instead of job_list = [ j for j in ... ]; use job_list = list( ... ).

Also, the logic in your failure code looks a bit suspect - you set subsequent jobs as 'failed' but nothing keeps them from being attempted again by the enclosing for loop.  I think you basically want a break at the end of the except block to exit the loop there, though that leaves the for loop still setting some potentially passed jobs as failed (consider the case when the first job passes but the second fails - the loop will set them all as failed).  So you might instead add a fail_the_rest = False flag just before the for job in joblist loop and then as the first line of the loop do if fail_the_rest: <set failed> continue and then change the except block to just set failure on that one job and then set fail_the_rest = True.  But that's all speculative due to a lack of understanding about how your job submission and pass/fails work.


antiRunningSums

You should use a pairwise helper to raise abstraction:

def antiRunningSums(lst):
    return [b - a for a, b in pairwise(lst)]

pairwise can easily be found in the itertools documentation.

runningSums

I think that referencing the list while you are building it is overcomplicated, I would use a variable to be incremented:

def runningSums(lst):
    s = 0
    for addend in lst:
        s += addend
        yield s

To obtain a list call list on the result of this function.


You don't need a class here, a simple function will do:

import ssl
from socket import socket

def testsock(tls=True):
    sock = socket()
    sock.connect(('192.168.0.1', 443))
    if tls:
        sock = ssl.wrap_socket(sock)
    return sock

testsock(tls=True)

Returned objects are either plain sockets or ssl sockets but they share some common behaviour (like send or recv). If you need to add attributes, you can do that before the return statement.

In case you wish to be able to extend it better, you can still use the socket as an attribute on a custom class and expose the socket API through __getattr__:

class TestSock(object):
    def __init__(self, tls=True):
        sock = socket()
        sock.connect(('192.168.0.1', 443))
        if tls:
            sock = ssl.wrap_socket(sock)
        self.socket = sock
        # other attributes

    def __getattr__(self, attribute_name):
        """Defer unknown behaviour to the socket"""
        return getattr(self.socket, attribute_name)

    # other methods

But you don't need it for now.


Relaying stdin data from one thread to another

Right away I can see a potential problem. It appears that it is possible for the consumer thread to access "myqueue" outside of any lock.

void consume () {
while (running || !myqueue.empty()) {

This will probably still function just fine, but it is only as thread-safe as the queue's implementation for 'empty'. Unless the queue itself can guarantee that such an operation is safe, then the code is not thread safe. It is up to the specifics of the queues implementation, and the optimizations done by the compiler / processor, weather or not this would work as expected.

One other minor thing I notice is that the queue is being checked for empty twice. Once in the consumer before the global function pop() is called, and again in the pop function itself. This is a bit confusing to read, and should not be necessary. It may be better to lock the queue first, and then process items later, like so.

void consume()
{
bool hasWork = true;
while (running && hasWork)
{
    std::string item = "";
    mutex.lock();
    if (!myqueue.empty())
    {
        item = myqueue.pop();
    }
    else
    {
        hasWork = false;
    }
    mutex.unlock();

    // Do something with "item"
}
}

The idea here is that you are locking the queue only when you are performing operations on it, and leaving it unlocked while actually doing work on whatever was pulled form the queue. This is especially important when the individual work items may take significant time.

Other than that, it looks like you've got the right idea about needing to protect access to the queue's push and pop methods, it's just that you've got to protect all the other methods that touch 'myqueue' also.

Again, this would probably still work just fine on most implementations, but it's better to know you're safe.


Should I always be suspicious about the solutions that require to use mutable and use it only when its problematic to implement it with immutable types?

I'm new to Scala myself, but I would say yes.
Try to use immutable and elegant solutions when possible, but it's OK to resort to mutable alternatives as a second choice.

  Is that fine to use mutable in this case?

I would use an immutable algorithm in this case:

use .groupBy to create groupings
use .map to convert the groupings to a list of word-count pairs
a final .toMap call and the map is ready

  I'm doing an extra loop to filter words longer than 3 chars. In my mind this way it looks a bit cleaner than to have a condition in foreach. Should I care more about the performance or readability in my code?

If the complexity is on the same order, then prefer readability, even if slightly slower. For example, it's OK to choose an \$O(3n)\$ algorithm instead of an \$O(2n)\$ algorithm. When code is more readable, it tends to be also easier to optimize at a higher level of logic, which can lead to far faster solutions than the original alternatives.

Suggested implementation using immutable logic:

  def wordCounter(text: String) = {
    {
      for {
        word <- text.toLowerCase.replaceAll("[^a-z ]", "").split(" ")
        if word.length > 3
      } yield word
    }.groupBy(identity).map { case (word, list) => (word, list.length) }
  }


Speed Up Excel Macro - Autofilter Copying

Turn on Option Explicit from the menu via Tools>Options>Editor tab>Require Variable Declaration. This mandates you Dim lastRow as long before using it anywhere. Doing this will save you needless frustration later down the line when you transpose a variable name raom instead of roam and time's wasted till you find it.

If you have two Ranges that are same size and you want to copy the values over you can do Foo.Value2 = Bar.Value2 to achieve this without any copying. If you have a Range that is the same size as an array you get the same with Foo.Value2 = inMemoryArray`.

Use descriptive variable names. x_bf1 doesn't have any meaning, at least to me. If future-you comes back to this code and doesn't know what it means you'll be wishing past-you had used a descriptive name. An example of this being useful is the comments 'Date in two locations. Renaming copyrange1 to dateArea will cause these comments to become redundant and removable as your code is self documenting already describing what it is doing, save comments for why.

Set copyrange1 = x_bf1.Range("D8:D" & lastrow_s) 'Date
...
copyrange1.SpecialCells(xlCellTypeVisible).Copy 'Date
pasterange1.Offset(0, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

becomes

destinationArea.Offset(0, 1).Value2 = dateArea.Value2

Tied to naming is the use of _ underscore. If you end up using interfaces be aware that this is how interface implementation is done. Double click on your first worksheet then at the dropdowns at the top select Worksheet from the left dropdown, and SelectionChange from the right dropdown. You get Private Sub Worksheet_SelectionChange(ByVal Target As Range)  which is an example of the underscore used this way.

You turn off ScreetUpdating and the rest, but it's never turned back on in your provided code. Make sure that is restored.

With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
    .DisplayAlerts = False
    .EnableEvents = False
End With

You're using a named range from a workbook. Every usage of them includes RefersToRange(1, 1). If your names are single cell Ranges this is redundant.

Refactored Code.

Public Sub Refactor()
    Dim x_bf1 As Worksheet
    Dim lo_b1 As ListObject
    Set lo_b1 = x_bf1.ListObjects(1)
    Dim s_date As Long
    s_date = CLng(ThisWorkbook.Names("in_fre_m").RefersToRange(1, 1))
    Dim s_des As Range
    s_des = ThisWorkbook.Names("dr_no").RefersToRange(1, 1)
    Dim s_code As Range
    s_code = ThisWorkbook.Names("dr_co").RefersToRange(1, 1)
    Dim lastrow_d As Long
    Dim lo_dr As ListObject
    lastrow_d = lo_dr.Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1

    With lo_b1.Range
        .AutoFilter Field:=13, Criteria1:=s_code
        .AutoFilter Field:=1, Criteria1:="<=" & s_date
    End With

    Dim lastrow_s As Long
    lastrow_s = lo_b1.Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

    If lastrow_s > 7 Then
        Dim dateArea As Range
        Set dateArea = x_bf1.Range("D8:D" & lastrow_s)
        Dim description As Range
        Set description = dateArea.Offset(0, 1)
        Dim calculationArea As Range
        Set calculationArea = dateArea.Offset(0, 16)
        Dim classification As Range
        Set classification = dateArea.Offset(0, 5)
        Dim notes As Range
        Set notes = dateArea.Offset(0, 6)
        Dim parragraph As Range
        Set parragraph = dateArea.Offset(0, 11)
        Dim code As Range
        Set code = dateArea.Offset(0, 12)
        Dim statutory As Range
        Set statutory = dateArea.Offset(0, 20)
        Dim reference As Range
        Set reference = dateArea.Offset(0, 14)

        Dim x_drill As Worksheet
        Dim destinationArea As Range
        Set destinationArea = x_drill.Range("C" & lastrow_d).Resize(dateArea.Rows.Count, 9)

        Dim singlePopulationHelper() As String
        singlePopulationHelper = LoadHelperArraywWithValues(reference, _
                                                            dateArea, _
                                                            classification, _
                                                            description, _
                                                            code, _
                                                            parragraph, _
                                                            calculationArea, _
                                                            statutory, _
                                                            notes)
        destinationArea.Value2 = singlePopulationHelper
    End If
End Sub

Private Function LoadHelperArraywWithValues(ParamArray values()) As String()
    Dim rowCount As Long
    rowCount = values(0).SpecialCells(xlCellTypeVisible).Cells.Count
    Dim columnCount As Long
    columnCount = UBound(values)
    Dim helperArray() As String
    ReDim helperArray(rowCount, columnCount)

    Dim populationColumn As Long
    For populationColumn = 0 To columnCount
        Dim workingColumn As Range
        Set workingColumn = values(populationColumn)
        Dim populationRow As Long
        populationRow = 0
        Dim subArea As Range
        For Each subArea In workingColumn.SpecialCells(xlCellTypeVisible).Areas
            Dim cell As Range
            For Each cell In subArea
                helperArray(populationRow, populationColumn) = cell.Value2
                populationRow = populationRow + 1
            Next
        Next
    Next
    LoadHelperArraywWithValues = helperArray
End Function

Alternate copying to temporary worksheet.

Private Function CopyToTempSheetBeforeLoading(ParamArray values()) As Variant
    Dim populatedColumns As Long

    Dim tempSheet As Worksheet
    Set tempSheet = ThisWorkbook.Worksheets.Add

    For populatedColumns = 0 To UBound(values)
        values(populatedColumns).SpecialCells(xlCellTypeVisible).Copy
        tempSheet.Range("B2").Offset(ColumnOffset:=populatedColumns).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
    Next
    CopyToTempSheetBeforeLoading = tempSheet.Range("B2").CurrentRegion
    tempSheet.Delete
End Function
```


using namespace std; is considered a bad practice.

Don't do this:

int gameRunning = true;

If you want to use a boolean variable, use a bool instead of int.

You can use boolean values directly in conditions,
no need to compare them to true / false.
So instead of this:

while (gameRunning == true)

You can write simply:

while (gameRunning)

Still about that while loop earlier,
since gameRunning is initialized to true,
the loop condition will be inevitable true for the first time.
That's kind of a waste to re-evaluate.
In situations like this,
considering rewriting it as a do { ... } while (...) loop.


A couple of things jump out:

Use size_t for the all allocation sizes/indices. I have had real-world bugs because of this in third-party libraries.

Use exponential, not linear, reallocations. Doubling each time is the best way. This allows .newValue to append in \$O(1)\$ amortized time, as opposed to the current \$O(n)\$.


Wrapping a non-unique handle with additional information

Because I also had to deal with a lot of handles, used by for example the Win32 API, I really can understand your use case.

  Is it safe to do this? (i.e. have I missed an operator or something?)

I don't think so, for a lot of reasons: Let's assume the handle your library defines is an opaque type, usually a void*. So the first problem is that the C-library has no idea of C++ concepts like operator overloading. So it will not call your operator= i.e. nor will the compiler disallow to assign named instances. Furthermore the library will deference your handle, assuming it points to it's internal data structure of some kind. Also the compiler has no idea that you have given the library a instance different from handle, while translating the library code. So even compiling the library with a C++ compiler won't make a difference.

  Is there another way to do this?

Although you're desire to design a nice C++ wrapper is a good idea, I would drop the idea to slip the C-library your type. I recommend to just define a .native_handle() member function or overload the operator* but then I would suggest that the name of your type does stress the wrapper nature more.

  Is there any good reason not to do this?

Despite from the reasons above, the size would already change if someone would sub or base class it.


Daily, Weekly, Monthly Individual Tech time in task Repoert

Somewhat hard to judge without any idea of the schema, but here are a few observations:

Join condition on billableType table is questionable: why comparing an ID to a rank in INNER JOIN billableType ON billingsTimes.billableTypeID = billableType.rank?
Try to limit GROUP BY to the columns that will become sort of 'logical key' of your result set. E.g. it seems the query is limited to a single task at a time (billingTimes.taskID = ###). Use max(taskName) as taskName in your select list and exclude taskName from the group by clause.
There's no need for datepart(D, dateOfService) in GROUP BY: the query is already restricted to a single day.


Remove duplicates from string without using additional buffer

Thats not working. Try the input: abaa (result: aa)

I do not know what you mean with "without using additional buffer", because finalValue is at least an additional buffer (which is kind of necessary. You could create a view, but this will be a bit complex).

An easier approach would be to create a LinkedHastSet. Insert all characters, output the set, done:

public static void removeDuplicateString2(final String input) {
    final Set<Character> set = new LinkedHashSet<>();
    for (int i = 0; i < input.length(); i++)
        set.add(input.charAt(i));
    final StringBuilder stringBuilder = new StringBuilder(set.size());
    for (final Character character : set)
        stringBuilder.append(character);
    System.out.println(stringBuilder);
}

About your code:

removeDuplicateString

I would call it something like removeMultipleOccurrence

String finalValue = "";

You may use a StringBuilder to reduce string concatenations.

    String value1 = input;
    String value2 = input;

You do not need these variables, just use input instead of value1/2

    int count = 0;
    char char1;
    char char2 = 0;

You do not need char2, and you can put the rest inside the loop to the initializing place.

        flag = 0;

This variable is not defined.

        if (count > 1) {
            finalValue=finalValue+char1;
            i=i+(count-1);
        } else {
            finalValue = finalValue + char1;
        }

You may move the finalValue line from the if/else. Then you can skip the else part, because it is empty.

If you combine everything, you could have:

public static void removeMultipleOccurrence(final String input) {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        int count = 0;
        final char char1 = input.charAt(i);
        for (int j = 0; j < input.length(); j++) {
            if (char1 == input.charAt(j)) {
                count++;
            }
        }

        if (count > 1)
            i = i + (count - 1);
        result.append(char1);
    }
    System.out.println(result);
}

Hint: This is still not working, just doing the same in a more clear way.
If you want to do it in your way, you have to search the string before the current position if you have already the current char.

This could be done in this way:

public static void removeMultipleOccurrence(final String input) {
    String finalValue = "";
    for (int i = 0; i < input.length(); i++) {
        int count = 0;
        final char currentChar = input.charAt(i);
        for (int j = 0; j < i; j++) {
            if (currentChar == input.charAt(j)) {
                ++count;
            }
        }

        if (!(count > 0))
            finalValue = finalValue + currentChar;
    }
    System.out.println(finalValue);
}

If we look at the count, it is just a boolean, so we end up with:

public static void removeMultipleOccurrence(final String input) {
    final StringBuilder result = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        boolean alreadySeen = false;
        final char currentChar = input.charAt(i);
        for (int j = 0; j < i; j++) {
            if (currentChar == input.charAt(j)) {
                alreadySeen = true;
                break;
            }
        }

        if (!alreadySeen)
            result.append(currentChar);
    }
    System.out.println(result);
}

We could get rid of the boolean now:

public static void removeMultipleOccurrence(final String input) {
    final StringBuilder result = new StringBuilder();
    withNextChar: for (int i = 0; i < input.length(); i++) {
        final char currentChar = input.charAt(i);
        for (int j = 0; j < i; j++) {
            if (currentChar == input.charAt(j))
                continue withNextChar;
        }
        result.append(currentChar);
    }
    System.out.println(result);
}

Or, we could look in the result, if we have it already:

public static void removeMultipleOccurrence(final String input) {
    final StringBuilder result = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        String currentChar = input.substring(i, i + 1);
        if (result.indexOf(currentChar) < 0) //if not contained
            result.append(currentChar);
    }
    System.out.println(result);
}


Menu selector that changes the background of a selected div

im not sure why you would want the length or count of the class..
You could simply use this to highlight the divs:

    $(".ProjectMainLink").click(function() {
          $(".ProjectMainLink").css("background-color","");
          $(this).css("background-color","#000");

    });

JS FIDDLE: http://jsfiddle.net/p3m2p/

EDIT:

Don't forget to wrap your functions in <script type="text/javascript"></script>

It could also be done like this:

<script type="text/javascript">
$(document).on("click",".ProjectMainLink",function() {
          $(".ProjectMainLink").css("background-color","");
          $(this).css("background-color","#000");
    });
</script>


Returning the length of a 'hidden' string within each of the sentences of another string

Some generals comments:

Define functions in reverse order to avoid prototypes, make local functions static, add void to empty parameter lists, use braces even when unnecessary, use spaces consistently around operators, define a single variable per line, return statements don't need brackets (you are inconsistent in this).

In function readLine

This function has many issues, some minor, such as casting malloc, using
sizeof(char) (sizeof char is 1 by definition) and the arbitrary limit on a
new line of 100 chars. In your variable name, str1, the '1' is unnecessary,
as you only use one string. And your default sentence allocation of 1 char is
silly - start with something reasonable, say 64 (arbitrary value).

More seriously, getchar returns an int not char.  This allows it to hold the value for EOF, the end-of-file marker.  Your for-loop should test for EOF.  If you fail to do this then if you input from a redirected file, the program will fail if EOF is reached without finding a \n.  A better loop would be, for example:

int ch;
while((ch = getchar()) != EOF) {
    if (ch == '\n') {
        break;
    }
    // do the necessary stuff
}

Your reallocation should compute the new capacity then use that in the realloc
call rather than computing it twice.  And your realloc call as it currently
stands leaks memory on failure - the original string str1 is not freed by
realloc on failure.

In function divideStringIntoSentences

You need to pass the size of sentences[] into the function to allow for overflow
detection.

In function getHiddenString

Parameter names of sentence and hidden might be more understandable than
str1, str2.  More seriously, I don't know what it is supposed to
do.  If it is supposed to find the hidden string in the sentence, then it
doesn't work.  Library function strstr would do the job for you.

In main

Although the functions handle malloc failures, main does not check for
str1 in the returned values.  Again str1 and str2 are badly named, as is
ptrarr.  The for-loop should define the loop variable and should loop up to
but not including j: for (int i = 0; i < j; ++i).  And the printout
"Sentence # contains hidden string prefix length #" is printed even if the
sentence doesn't contain the hidden string.  This make me think that the
getHiddenString function is telling us the number of consecutive chars from
the hidden string contained in the sentence, or some such.  In that case it
still doesn't work and is badly named (eg if I give it "two twa twe" and the
hidden string "twe" it says, "Sentence 0 contains hidden string prefix length 4"


Is there a more dynamic way to target siblings in CSS / SCSS?

There is! You can use :nth-child() with plenty of ways to select children elements of particular wrapper, for example odd or even elements, a range of elements, 3 elements after 4 other elements and repeat.
Check this generator to create a rule and help you visualize what elements will be selected:
https://css-tricks.com/examples/nth-child-tester/
Docs:
https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child


<bits/stdc++.h> is non-standard and likely far more than you actually need. Unless coupled with use of precompiled headers, it will slow down compilation at least. Replace it with the standard includes. See "How does #include <bits/stdc++.h> work in C++?".
Never import wholesale any namespace which isn't designed for it. Doing so leads to conflicts, silent changes of behaviour, and generally brittle code. See "Why is “using namespace std” considered bad practice?".
Crank up the warning-level for your compiler. You will see it complain that size in retPrime() is unused.
There are only two good reason to give a variable a bigger scope than needed: Restricting the scope would be more verbose, or constructing it anew repeatedly would be more expensive. Otherwise, it's needless extra-stress put on each reader to understand things.
Avoid magic numbers. Instead, use some well-named constant, or simply eliminate them.
std::sqrt() may be required by the IEEE Standard to be exact. But does your implementation guarantee IEEE-conformance? Anyway, why not start with the square-roots?
Try to use fewer variables. Instead of incrementing a new variable up to a target, decrement the target if you don't need it any longer.
If you detect an error, like running beyond the bounds of your sieve, throw an exception, return an obviously impossible value (0 is a good candidate), or abort the program. But don't return a value which looks legitimate but is wrong.
Take a bit more care with formatting. An empty line before each function is a good idea, but please neither more (before the first) nor less (before the last).
retFib() and retPrime() are curious names. getFibonacci() and getPrime() seem better.
You really should add a function for your own series, abstracting the details away.
Comparing booleans against true or false is just pointless verbosity. Use the value directly, or after Negation with !.
There is no guarantee that a bool is a byte big. Nor that memsetting every byte to 1 will result in a valid bool, let alone that it's true. Use std::fill, or reverse the logic and use aggregate-initialization to start with all-false instead.

Even better, consider that the only even prime is 2, and change the code accordingly.
Calculating fibonacci naively needs \$O(n)\$ space and \$O(2^n)\$ time. Consider being slightly more clever and calculate it iteratively in \$O(1)\$ space and \$O(n)\$ time.
The conditional operator condition ? true_exp : false_exp is excellent for selecting one of two expressions. Use it where appropriate.
You should end each line of output with \n, it's expected. A single space instead is surprising.
If you want to stream a single character, use a character-literal, not a length-one string-literal. It might be slightly more efficient.
return 0; is implicit for main().
Use noexcept where appropriate.
Don't make things external for no reason. It increases the chance for collisions, and decreases the chance for inlining.
Input can fail. Deal with it.
As a final point, it might be better to just pre-compute the full sequence and be done with it. That might even save space.

Modified code:

#include <iostream>

static int getPrime(int n) noexcept {
    //Using sieve of Eratosthenes to generate primes
    constexpr auto sqrt_size = 10;
    constexpr auto size = sqrt_size * sqrt_size;
    if (!n) return 2;
    bool prime[size] = {false, false, true};
    for (int i = 3; i < size; i += 2)
        prime[i] = true;
    for (int i = 3; i < sqrt_size; i += 2) {
        if (!prime[i])
            continue;
        if (!--n)
            return i;
        for (int j = i + i; j < size; j += i)
            prime[i] = false;
    }
    for (int i = (sqrt_size & ~1) + 1; i < size; i += 2)
        if (prime[i] && !--n)
            return i;
    return 0;
}

static int getFibonacci(int n) noexcept {
    int last = 0, r = 1;
    while (n-- > 0) {
        int temp = last + r;
        last = r;
        r = temp;
    }
    return r;
}

static int mySeries(int n) noexcept {
    return n % 2 ? getFibonacci(n / 2 + 1) : getPrime(n / 2);
}

int main() {
    int n;
    if (std::cin >> n)
        std::cout << mySeries(n) << '\n';
    else
        std::cerr << "Could not understand your input. Expected a number.\n";
}


You could use try-with-resources  to efficiently close the streams, this also reduces line count and readability.

IOUtils provides a tested utility to copy between input and output streams, add commons-compress to you classpath, for example using gradle

 compile group: 'org.apache.commons', name: 'commons-compress',version: '1.14'

I simply extended the code you provided. I believe you will get the idea for reading back the zip file.

  try {

            File file = new File("C:/temp/tempExport.bef");
            file.createNewFile();

//Use try with resources to handle closing streams

            try (ZipOutputStream zipStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)))) {
                zipStream.putNextEntry(new ZipEntry("bef"));
                ObjectOutputStream objectStream = new ObjectOutputStream(zipStream);
                objectStream.writeObject(extendedFormat);
            }

         //to read the file you need a temp buffer or file to decompress the archive
            File temp = Files.createTempFile("", "").toFile();

            try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)));
                 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(temp));
                 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(temp))) {
                zis.getNextEntry();
                IOUtils.copy(zis, bos);
                bos.close();
                ObjectInputStream ois = new ObjectInputStream(bis);
                ExtendedFormat extendedFormat= (ExtendedFormat) ois.readObject();
            }

            temp.delete();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


Construct intervals from a sequence of numbers and vice versa

For the first part of making sequence to intervals, you could do this instead (prob. more Pythonic?)  (This can be converted to a function easier - leave for the exercise)
>>> # if x-1 not in seq:  x becomes start point
>>> # if y+1 not in seq:  y becomes end point
>>> starts = [x for x in seq if x-1 not in seq]
>>> ends =  [y for y in seq if y+1 not in seq]
>>> ends
[3, 7, 9]
>>> intervals = [str(a)+'-'+str(b) for a, b in zip(starts, ends)]
>>> intervals
['1-3', '6-7', '9-9']
>>>

[Note - last interval could be 'fixed' too  - if we see start_point == end_point. Leave as an exercise.]
Then for the second part, it would be quite similar:
>>> seq = []
>>> for inter in intervals:
    s, e = inter.split('-')
    seq += list(range(int(s), int(e)+1))
>>> seq
[1, 2, 3, 6, 7, 9]


Is this a good way to catch all 404s in .NET without playing with IIS configuration?

404 is an error and normally should be captured with a relative event. Since you have a custom module you can do the following in the module:

public void Init(HttpApplication context)
{
    // your code
    context.Error +=new EventHandler(OnError);
}

private void OnError(object sender, EventArgs e)
{
    int ec = ((HttpException)HttpContext.Current.Error).GetHttpCode();
    if (ec == 404)
    {
        // do whatever you want
    }
}

If you follow this path you will have the advantage to control all error codes your way and avoid early 404 drops in case you change your rewriting policy or logic.


Getting employee details according to the role

You can  use linq GroupBy and Select to reduce your list to distinct RoleTitle's in your foreach loop:

foreach(Role role in emp.Roles.GroupBy(r=> r.RoleTitle).Select(g => g.First()))
{
    //...
}


Looks okay if a bit sloppy with different formatting for some print x
vs. print(x) calls (the latter being preferred really); you probably
should also use
new-style classes,
i.e. class Loader(object):.

Other than that the main concern I'd have is that the semaphore should
be protected against exceptions.  This is mostly a concern for bigger
scripts, but it's a good habit regardless.  Thus, the release method
should be called regardless of whether an exception was raised by
anything else in the thread - otherwise the program could just get stuck
there, which is fine for a one-off script probably.

You should probably also check whether the threading actually does
improve the throughput, considering Pythons global interpreter lock.


Getting display size compact class in Android

First of all, this line:

if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 13) {

Should be replaced with this:

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {

Because a) There's no need to use Integer.valueOf for something that is already an int. b) Build.VERSION_CODES.HONEYCOMB_MR2 is a constant (or as we call it in Java, public static final) with the value 13. Avoid using "magic numbers" in your code like that, instead refer to existing constants or create new constants when necessary.

Secondly, I really doubt that the size of your screen will change while your object exists. Which means that this code need only to be run once and can therefore be placed in the constructor:

Point size = new Point();
mDisplay.getSize(size);

Now to the last point I want to make. Your mWindowManager variable is only used within the constructor. I see no need at all for that to be a field in your class. Change that to a local variable instead.

It is also a good practice to make your class fields final when possible (which is both possible for the mDisplay and also your newly created Point size field). The final keyword makes sure that you get a compiler error if you try to change the value of the variable after it has been initialized. Note that mDisplay.getSize(size) doesn't change the variable itself, it changes the values within the variable, i.e. the object size remains the same.

Besides this, I have to say that your code looks excellent. You have good variable names. I don't even see any indentation problems (except those that StackExchange create, but they're not your fault).


Before I begin, let me say, it looks like a well engineered project.  You've separated the work into a tokenizer, parser, and calculator, which is excellent.  The unit tests were helpful as well.  Congratulations.

Before you begin to write a parser, you should define the grammar, which you should state as a long comment in your parser's JavaDoc.  From my interpretation of your code, I see the following productions:

EXPRESSION = BINARY_EXPRESSION |
             TERM

BINARY_EXPRESSION = EXPRESSION BINARY_OPERATOR TERM

BINARY_OPERATOR = "+" | "-"

TERM = VALUE_EXPRESSION |
       PARENTHESIZED_EXPRESSION

VALUE_EXPRESSION = number

PARENTHESIZED_EXPRESSION = "(" EXPRESSION ")"

You don't support unary minus (negative numbers).  That's OK; we'll keep it simple for now.

It would be a good idea to add the following unit test:

@Test
public void evaluateThreeOperatorWithNoParens(){
        int result = c.evaluate("5-2+1");
        Assert.assertEquals(4,result);
}

If you had defined the grammar carelessly, such as the following…

EXPRESSION = VALUE_EXPRESSION |
             BINARY_EXPRESSION |
             PARENTHESIZED_EXPRESSION

VALUE_EXPRESSION = number

BINARY_EXPRESSION = EXPRESSION BINARY_OPERATOR EXPRESSION

BINARY_OPERATOR = "+" | "-"

PARENTHESIZED_EXPRESSION = "(" EXPRESSION ")"

… then it would be ambiguous whether "5-2+1" should be interpreted as (5-2)+1 or 5-(2+1).  The evaluateThreeOperatorWithNoParens() test enforces the former interpretation.

The main problem is your handling of parentheses.  Scanning the entire token list in advance to check for matching parentheses is inelegant; you should be able to detect such syntax errors as part of your parsing routine.  Also, having four if-statements checking for opening/closing parentheses is a sign of confusion.

To enforce some structure to your parser, you should have a helper function for each production listed above.

Instead of taking .subList()s, I think it would be more elegant to use a ListIterator<Token> to keep track of your position.  Also, there's no reason why your parser has to take an ArrayList, when any List<Token> would be acceptable.

Parsable is an odd name for the interface.  I'd consider a string to be parsable.  Therefore, I suggest breaking with the "-able" suffix convention and just call it a Parser.  (Plenty of interfaces in the standard Java API aren't named with an "-able" suffix either.)

/**
 * (JavaDoc describing the grammar goes here.)
 */
public class SimpleParser implements Parser {

    public Expression parse(List<Token> tokens) {
        ListIterator<Token> tokenIter = tokens.listIterator();
        Expression expr = parseExpression(tokenIter);
        if (tokenIter.hasNext()) {
            throw new ParseException("Extra text after expression: " + tokenIter.next().getValue());
        }
        return expr;
    }

    private static Expression parseExpression(ListIterator<Token> tokenIter) {
        if (!tokenIter.hasNext()) {
            throw new ParseException("Premature end of expression");
        }

        Expression expr = parseTerm(tokenIter);
        while (tokenIter.hasNext()) {
            Token op = tokenIter.next();
            if (op instanceof OpToken) {
                expr = parseBinaryExpression(expr, (OpToken)op, tokenIter);
            } else {
                tokenIter.previous();
                break;
            }
        }
        return expr;
    }

    private static Expression parseBinaryExpression(Expression leftExpr, OpToken op, ListIterator<Token> tokenIter) {
        return op.toExpression(leftExpr, parseTerm(tokenIter));
    }

    private static Expression parseTerm(ListIterator<Token> tokenIter) {
        Token t = tokenIter.next();
        if ("(".equals(t.getValue())) {
            return parseParenthesizedExpression(tokenIter);
        } else {
            return parseValueExpression(t);
        }
    }

    private static Expression parseValueExpression(Token t) {
        try {
            int intVal = Integer.parseInt(t.getValue());
            return new ValueExpression(intVal);
        } catch (NumberFormatException nfe) {
            throw new ParseException("expected int but found: " + t.getValue());
        }
    }

    private static Expression parseParenthesizedExpression(ListIterator<Token> tokenIter) {
        Expression innerExpr = parseExpression(tokenIter);
        if (!tokenIter.hasNext() || !")".equals(tokenIter.next().getValue())) {
            throw new ParseException("Missing right parenthesis");
        }
        return innerExpr;
    }
}


Just a few notes so you can improve your code:

int sum1 = draw1 + draw2;

if (sum1 == 21) //Blackjack Ending
{
  Console.WriteLine("Congratulations! You got " + sum1 + "!");
}

This won't ever be true, because

you have nowhere in the cards an ace meaning having a possible value of eleven.
the maxValue in Random.Next(int minValue, int maxValue) is the exclusive upper bound of the random number returned.

In void drawChoice(bool contChoice) the method argument contChoice is a value type. You can't modify it like you think. After leaving the method regardless wether the user typed y or n the value of cont1 is still false. You should change the method signature to have no arguments but to return a bool.

if (cont1 == true)

because cont1 already is a bool you won't need to compare it with a bool. You can simply use it as condition like if (cont1) and if  you would need to check wether a bool variable is false you would use if (!cont1).


Counting the number of 1 bits in a sorted bit array

I agree with your assessment of the code being unnecessarily long and awkward. It looks like the root cause is an opportunistic optimization.

The bad news is that most of the secondary tests (like arr[mid - 1] == 0 and arr[mid - 1] == 1) are bound to fail, so not only they contribute to awkwardness of the code - they also hurt the performance (by about a factor of 2, if I am not mistaken).

I recommend to keep it simple, and test only what is necessary:

    l, r = 0, len(arr)
    while l < r:
        mid = l + (r - l) // 2
        if arr[mid] == 1:
            r = mid
        else:
            l = mid + 1
    return len(arr) - l

Notice that working on a semi-open range (that is, mid is beyond the range) also makes it cleaner.


Input checking

The most obvious issue that I see is that you are not verifying that the correct input is being entered. For example, if you enter a String instead of an int:

> hello
Exception in thread "main" java.util.InputMismatchException
  at java.util.Scanner.throwFor(Scanner.java:864)
  at java.util.Scanner.next(Scanner.java:1485)
  at java.util.Scanner.nextInt(Scanner.java:2117)
  at java.util.Scanner.nextInt(Scanner.java:2076)
  at Main.main(Main.java:8)

A natural way to do this is with Scanner.hasNextInt(). Also, consider adding a little bit of feedback so it is less confusing for the user. Something like this, for example:

    Scanner scan = new Scanner(System.in);
    int start;
    int end;

    System.out.println("Enter 1st whole number: ");
    while (!scan.hasNextInt()) {
        System.out.println("Input must be a whole number. Try again:");
        scan.next();
    }
    start = scan.nextInt();

    System.out.println("Enter 2nd whole number: ");
    while (!scan.hasNextInt()) {
        System.out.println("Input must be a whole number. Try again:");
        scan.next();
    }
    end = scan.nextInt();

Result:

Enter 1st whole number:
> hello
Input must be a whole number. Try again:
> 5
Enter 2nd whole number:
> world
Input must be a whole number. Try again:
> 20
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

One other (more general) method (though it is more of an anti-pattern in this particular case) to validate things is with a try/catch block. See this answer on Stack Overflow for an example on how to do this.

    Scanner scan = new Scanner(System.in);
    int start;
    int end;

    try {
        System.out.println("Enter 1st number:");
        start = scan.nextInt();
        System.out.println("Enter 2nd number:");
        end = scan.nextInt();

    } catch (java.util.InputMismatchException e) {
        System.out.println("Input must be an integer.");
        System.out.println("Exiting program.");
        return;
    }

Enter 1st number:
> hello
Input must be an integer.
Exiting program.

Formatting

One other remark, although it is more stylistic, it is often considered a good habit in general to include braces in Java even when they are not needed. So this bit:

if(start < end)
    for(int i = start; i <= end; i++)
        System.out.print(i + " ");

else if(start > end)
    for(int i = start; i >= end; i--)
        System.out.print(i + " ");

Would look like this:

    if(start < end) {
        for(int i = start; i <= end; i++) {
            System.out.print(i + " ");
        }
    }
    else if(start > end) {
        for(int i = start; i >= end; i--) {
            System.out.print(i + " ");
        }
    }


Determine the third octet of an IP address based on user entered site number

Let's start with a table of inputs and outputs, because it may not be exactly the same as what you expect from your script.  The first column is the input range, the other column is the transformation applied for those inputs.

0000-0255       self
0256-0399       last2
0400            undefined
0401-0499       -300
0500            undefined
0501-0799       last2
0800-1201       undefined
1202            last3
1203-4999       undefined
5000-5255       last3
5256-5399       last2
5400-5500       undefined
5501-5999       last2
6000+           same as 5000-5999

The best way to manage these cases is with a data structure.  A switch statement can work too but there's going to be a lot of repetition, and you really want something that lets you focus on the data.

In this version, the ranges are an array of arrays.  Each inner array is a lower bound, an upper bound, and a script block that transforms input to output.  As a special case, a negative result from the script block means "restart the conversion with this new value (after making it positive)"—this lets us reuse the low patterns for most of 5000-5999, and then reuse the 5000-5999 pattern for 6000-9999.

We simply traverse the array looking matches, and apply the transforms from matching rows. (There's only ever one matching row per call to convert, in this example, but the code allows overlapping ranges; matching transforms will apply in order).

$ranges = @(
    @(    0,  255, { $_ }                  ),
    @(  256,  399, { $_ % 100 }            ),
    @(  401,  499, { $_ - 300 }            ),
    @(  501,  799, { $_ % 100 }            ),
    @( 1202, 1202, { $_ % 1000 }           ),
    @( 5000, 5399, { -($_ % 1000) }        ), # redo using last 3 digits
    @( 5501, 5999, { -($_ % 1000) }        ),
    @( 6000, 9999, { -($_ % 1000 + 5000) } )  # redo using 5000 + last 3
)

$convert = {
    $_ = [int]$args[0]
    $out = -1
    foreach ($range in $ranges) {
        if ($_ -ge $range[0] -and $_ -le $range[1]) {
            $out = & $range[2]
            # negative result means re-do the conversion with a new value
            if ($out -lt 0) { $out = & $convert ($out * -1) }
        }
    }
    return $out
}

$site = Read-Host 'enter the site code: '
$octet = & $convert $site
if ($octet -ge 0) {
    echo $octet
} else {
    echo "error - $site has no defined octet"
}


Moving method from derived class to base

The use of doSomeSpecific inside of handleTimer is remarkably similar to the Template Pattern.

If there is no base implementation of doSomeSpecific you might consider making it private (still virtual so it can be overridden). Unless of course you really want further derived classes to be able to call the doSomeSpecific implementations of their parent classes.

Also, you can consider making handleTimer non-virtual if all derived classes must have the same behavior.

By making doSomeSpecific private, and handleTimer non-virtual, the only point of customization becomes doSomeSpecific, and it becomes an all or nothing point of customization. This can simplify your implementations of your derived classes, because you can trust that they only customize one specific part of your base class.


Solution to a simple Hackerrank problem: Compare the Triplets

You don't have to traverse the competitions array twice. The results can be collected in a tuple result after a single traversal.

val results = competitions.foldLeft((0,0)){
                             case ((aw,bw),(a,b)) =>
                               if (a>b)      (aw+1,bw) //a won
                               else if (b>a) (aw,bw+1) //b won
                               else          (aw,bw)   //tie
                           }

The tuple's elements can be accessed via indexing, results._1 and results._2, but it can be more convenient to unpack it via pattern matching.

val (scoreA, scoreB) = results

So, putting it all together, and removing the competitions step (just because you can).

val (aWins
    ,bWins) = alice.zip(bob)
                   .foldLeft((0,0)){
                      case ((aw,bw),(a,b)) =>
                        if (a>b)      (aw+1,bw)
                        else if (b>a) (aw,bw+1)
                        else          (aw,bw)
                   }

Sending the results to STDOUT is usually done via println(),  either with string catenation...

println(aWins + " " + bWins)

...or with string interpolation.

println(s"$aWins $bWins")


Replacing Connect Four code with a for loop

I think like this:
print("   0   1   2   3   4   5   6")
for row in board:
    print(" " + " | ".join(row))
    print("  ---+---+---+---+---+---+---")
print()

You could put the whole thing into a single call to print by using "\n".join and more string concatenation, but that would most likely make it a lot less readable.


If you're aiming for readability rather than efficiency or maintainability — and that is a reasonable tradeoff for FizzBuzz — then I would say "Well done." (You could test for divisibility by 15 for efficiency and avoid monkey-patching for maintainability.)

Conventionally, the output should be one entry per line, rather than an array.

If you're going to take an upper bound as a parameter, you may as well take a range, and the parameter should default to 1..100.

Therefore, a better way to call the code would be

fizzbuzz(1..100).each { |output| puts output }

or, using the default,

fizzbuzz.each { |output| puts output }


Clean Code attempt of HOLES problem on codechef.com

LetterEvaluator

Since this is a C++11 solution, you no longer need something like createMap():

std::map<char,int> createMap() const {
        std::map<char,int> initializedMap;
        initializedMap['A'] = 1;
        initializedMap['B'] = 2;
        initializedMap['D'] = 1;
        initializedMap['O'] = 1;
        initializedMap['P'] = 1;
        initializedMap['Q'] = 1;
        initializedMap['R'] = 1;
        return initializedMap;
    }

Use C++11's list initialization to have it initialized in place:

const std::map<char, int> letterMap {
    {'A', 1},
    {'B', 2},
    {'D', 1},
    {'O', 1},
    {'P', 1},
    {'Q', 1},
    {'R', 1}
};

If you have C++14, you can avoid providing an explicit return type:

std::map<char,int>::const_iterator retrieveValueOfLetter(const char letter) const {
        return letterValues.find(letter);
    }

You can use automatic return type deduction via auto:

auto retrieveValueOfLetter(const char letter) const {
    return letterValues.find(letter);
}

This does also shorten the line, which could help add more readability.
You have two redundant calls to retrieveValueOfLetter():

int getValueOf(const char letter) const {
        if(retrieveValueOfLetter(letter) == letterValues.end())
            return 0;
        else{
            return retrieveValueOfLetter(letter)->second;
        }
    }

Just retrieve the value from one call and then return the appropriate value:

int getValueOf(const char letter) const {
    const auto retrievedLetter = retrieveValueOfLetter(letter);
    return (retrievedLetter == letterValues.end()) ? 0 : retrievedLetter->second;
}

I've used a ternary here to shorten the expression to just one line.  If it looks less-readable, or if you may need to expand on it later, you may still use if/else instead.

HolesInCapitalizedWordFinder

It looks like readWord() should be a free function (non-member function).  However, if you're trying to read in a word, then you can just overload operator>> for this class.
Do you really need isNotAnUpperCaseLetter()?  There's already std::isupper() provided in the standard library, which should be safer to use.  You may encounter some issues with your own, depending on how it's implemented.


Select items between two dates that are available

I will say that you are probably always going to get into really convoluted queries like these until you begin to treat your caring data at its most granular level (a day in this case), rather than as a range of days, and  introduce the concept of a calendar/date "dimension" table that can be joined against to give all dates in a given time range, as is frequently used in scheduling applications like this.

Take for example a case where tables look like:

CREATE TABLE calendar
    (`date_idx` date NOT NULL, PRIMARY KEY `date_idx`)

/* Add all dates you might be interested in from past dates well into the future */
INSERT INTO calendar (`date_idx`) VALUES
('2017-01-01'), ('2017-01-02'), ...

/* This table now only has a single date field */
CREATE TABLE caring
    (`id` int, `careDate` date, `clientId` int, `attendantId` int);

Using these two tables, you can use the following derived table in any query to join against (or use as subselect) to compare dates in caring against the full list of available dates on calendar.

SELECT
    calendar.date_idx AS dateIdx,
    caring.id AS caringId,
    caring.clientId AS clientId,
    caring.attendantId AS attendantId,
FROM calendar
LEFT JOIN caring
    ON calendar.date_idx = caring.caringDate
WHERE
    caring.caringDate IS NULL
    AND dateIdx BETWEEN ? AND ? /* your dates of interest */
ORDER BY dateIdx ASC

This means it would be REALLY simple to extend this to your use case.

SELECT
    client.id AS clientId,
    COUNT(openDates.dateIdx) AS openDateCount
FROM client
LEFT JOIN (
    /* select shown above */
) as openDates
    ON client.id = dateRange.clientId
GROUP BY clientId
HAVING openDateCount > 1

Note that the JOIN and WHERE conditions on the derived table above can easily be changed to get different comparisons of dates in caring to all available dates in calendar.  The real "magic" is really just in having a dimension table which represents the full compliment of available "slots" within the schedule that you can easily join against. You often see similar date/time based dimension table representing different levels of granularity in scheduling applications such as this as well as in data warehouse/reporting applications.

If you search for "time dimension table script" or similar, you will find handy scripts for generating different aggregations/granularity for time into tables that can be used in your applications.

Now this may lead you to the question of how to handle sequences of dates (e.g. a customer orders a 10 day block of services).  This may be a case where you consciously decide to de-normalize your database.

So perhaps you have something like:

CREATE TABLE careOrders
    (`id` int, `careStartDate` date, `careEndDate` date, `clientId` int, `orderDate` date);

Which would be used with:

CREATE TABLE caring
    (`id` int, `careDate` date, `careOrderId` int, `attendantId` int);

Every time you create an order you enter it in the careOrders table and then build the associated items in caring to fill out time slots, leaving a reference in the caring table to the order that populated the item into the table. This is de-normalization of data as you are storing a calculated result of the order start and end dates in caring table which could be seen as redundant to the data in the careOrder table, but in fact is there to allow you to optimize queries against this data.

You perhaps even leave the clientId in the caring table (another conscious decision to break normalization) in order to optimize queries like the one in question here (i.e. to not have to include the careOrders table in the query).

Note how I used date fields instead of varchar in my examples.  You should be using the appropriate data type here.

I noted in your fiddle that none of your tables had appropriate primary keys or indexes.  I don't know if this was simply for benefit of given example (it shouldn't be on Code Review where we want to see actual production code), but this certainly should not be the case in your production environment.  You need appropriate indexes on your tables to allow the queries to be performant.

Consider using meaningful (full) names in your queries.  I know there are a lot of examples out there of people aliasing tables or derived tables with one or two character aliases, but what do you gain in doing this?  You avoid typing a few characters (that most good IDEs could autocomplete anyway)?  So what?  Bias your code (including SQL code) for readability.

Even as I read your SELECT statement, I find myself jumping around in the rest of the complex query trying to find out what a, ca, eca, etc. mean.

Same thing with the fields in your SELECT. They seem to be arbitrarily broken up across lines. Why? It just looks more cluttered to the eye.  Is there really any problem in having a query that extends more vertically down the page (the way the eye naturally wants to move)?

Even if I were to combine my example above in to one full query like:

SELECT
    client.id AS clientId,
    COUNT(openDates.dateIdx) AS openDateCount
FROM client
LEFT JOIN (
    SELECT
        calendar.date_idx AS dateIdx,
        caring.id AS caringId,
        caring.clientId AS clientId,
        caring.attendantId AS attendantId,
    FROM calendar
    LEFT JOIN caring
        ON calendar.date_idx = caring.caringDate
    WHERE
        caring.caringDate IS NULL
        AND dateIdx BETWEEN ? AND ?
    ORDER BY dateIdx ASC
) as openDates
    ON client.id = dateRange.clientId
GROUP BY clientId
HAVING openDateCount > 1

Is that not much easier to read (even without use of aliases)?

Be careful using camelCasing in MySQL schema object names. MySQL tables could suffer from OS-level differences in case sensitivity for their names, while columns, indexes, column aliases, etc. are not case sensitive at all in MySQL. For this reason, many who develop regularly with MySQL prefer snake_case for all schema objects avoid potential problems altogether.

AS is MySQL reserved word and should be strongly considered for UPPERCASE usage in your queries to help differentiate it from you database or value references.  I think you do a good job of uppercasing key and reserved words in all other cases here. as is treated inconsistently.

Why alias some fields in your select clause and not others?  I would think you would want to be consistent here. My guess is since startDate and endDate are not aliased here, and are really not relevant to the result, perhaps they should not be in select at all?


Persist keyboard backlight color on Linux laptop

Namespaces...
... are not for creating taxonomies. They are there to avoid name collisions. Also the chosen module alias for argparse seems strange. It's name is derived from argument parser so, if any, the obvious abbreviation should be ap. However, it might be better to just import the needed names, instead of creating taxonomies, since there are no name collisions in your code base.
from argparse import ArgumentTypeError, ArgumentParser
from os.path import exists, join
from re import fullmatch

Don't run business logic on module load
Currently, your script parses the command line arguments and writes to files, as soon as the module is laoded. This can be avoided by using an if __name__ == '__main__': guard and / or a main() function.
def main():
    """Runs the script."""

    arg_parse = ag.ArgumentParser(description="Set the color and brightness of the system76 keyboard backlight.")
    arg_parse.add_argument('-r', help="The red RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-g', help="The green RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-b', help="The blue RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-B', help="The brightness (0 to 255).", default="48", type=brightness_fragment)

    args = arg_parse.parse_args()
    …

if __name__ == '__main__':
    main()

It might be even better to outsource the argument parsing into an own function.
def get_args():
    """Parses the command line arguments."""

    arg_parse = ag.ArgumentParser(description="Set the color and brightness of the system76 keyboard backlight.")
    arg_parse.add_argument('-r', help="The red RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-g', help="The green RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-b', help="The blue RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-B', help="The brightness (0 to 255).", default="48", type=brightness_fragment)
    return arg_parse.parse_args()

def main():
    """Runs the script."""

    args = get_args()
    …

Input validation
Your input validation seems complicated. In both cases, for the RGB values and the brightness, an integer within a certain range is expected.
def parse_rgb(text):
    """Parses an RGB value from a string."""

    rgb = int(text)

    if not 0 <= rgb <= 0xff:
        raise ValueError('RGB value out of bounds.')

    return rgb

def parse_brightness(text):
    """Parses a value for the brightness from a string."""

    brightness = int(text)

    if not 0 <= brightness <= 255:
        raise ValueError('Brightness out of bounds.')

    return brightness

Note that argparse will automatically display an error message if a parser specified at type= raises a ValueError. So you can also get rid of one import and work with a built-in exception instead.
The downside of the integer parsing is, that you'll have to convert the ints back to strings then:
red = hex(args.r)[2:].upper().zfill(2)
green = hex(args.g)[2:].upper().zfill(2)
blue = hex(args.b)[2:].upper().zfill(2)
brightness = str(args.B)
…

You may also subclass an int for this use case:
class RGB(int):
    def __init__(self, value):
        if not 0 <= value <= 0xff:
            raise ValueError('RGB value out of bounds.')

    def __str__(self):
        return hex(self)[2:].upper().zfill(2)

    …

arg_parse.add_argument('-r', help="The red RGB value (0x00 to 0xff).", default=RGB(0), type=RGB)
…
red = str(args.r)


The best and easiest way to do this would be to place the items in a box container with a pre-computed height and width. Then in order to find the max amount of items that can be placed in the container, you just divide the area of the box container by the area of an item.

I used this method with your previous function and got something like this.

Cluster.prototype.initiate_items_per_page_calculation = function () {
    var o = this.get_init_calculation_object(),
        areaOfHeaderAndFooter = ( o.header.w * o.header.h ) + ( o.footer.w * o.footer.h ),
        areaOfExtraPaddingToContainer = 150 * 250 * 2,
        areaOfBoxContainer = (o.screen.w * o.screen.h ) - areaOfHeaderAndFooter - areaOfExtraPaddingToContainer,
        areaOfBox = (o.item.w * o.item.h),
        containerBoxLimit = Math.floor( areaOfBoxContainer / areaOfBox );

    return containerBoxLimit;
};
Cluster.prototype.get_init_calculation_object = function () {
    var $body = $('body'),
        $header = $body.find('header'),
        $footer = $body.find('footer'),
        $item = $body.find(this.cluster_public_classes.item_wrapper);

    return {
        footer:{
            h: $footer.outerHeight(true),
            w: $footer.outerWidth(true)
        },
        header:{
            h: $header.outerHeight(true),
            w: $header.outerWidth(true)
        },
        item:{
            h: $item.outerHeight(true),
            w: $item.outerWidth(true)
        },
        screen:{
            h: $body.outerHeight(true),
            w: $body.outerWidth(true)
        }
    };
};


Sum of HList (where all elements are Nat's)

First for some little things. I'd put bounds on the L type parameter and the Out type member to capture the facts that you know will always be true about them:

trait HListSum[L <: HList] {
  type Out <: Nat
}

This makes the intent clearer to readers and allows you to use Out in places you couldn't otherwise—e.g. this simple example wouldn't compile without the bound:

scala> def foo[N <: Nat]: Unit = ()
foo: [N <: shapeless.Nat]=> Unit

scala> def bar[L <: HList](implicit sum: HListSum[L]): Unit = foo[sum.Out]
bar: [L <: shapeless.HList](implicit sum: HListSum[L])Unit

I'd also change the return type of apply to be a little more specific (or rather less specific, I guess—more focused on what's relevant, in any case):

def apply[L <: HList](implicit ev: HListSum[L]): Aux[L, ev.Out] = ev

This is mostly for legibility—apart from how the type is printed in the console I'm not sure off the top of my head whether there's any real difference between this and the ev.type version.

I'd make two changes to the hListSumInductive implementation (apart from changing the case of the l in the name to be consistent with hlistSumHNil):

implicit def hlistSumInductive[H <: Nat, T <: HList, TS <: Nat](implicit
  rest: HListSum.Aux[T, TS],
  all: Sum[H, TS]
): HListSum.Aux[H :: T, all.Out] = new HListSum[H :: T] {
  type Out = all.Out
}

The first is that I've renamed L to T and T to TS, since using H and T to name the head and tail types of an hlist is a pretty standard convention. More significantly, I've dropped the S type parameter (representing the total sum) altogether, since we don't need a type parameter to refer to that type (all.Out works just fine, since we don't need to refer to it in other implicit parameters).

One other note about this method: I'm not sure whether you chose Sum[H, TS] over Sum[TS, H] intentionally, but it's the right thing to do if you care about compile times (and you should in a case like this), since the instance will be resolved more quickly when the larger number is on the right, and in this operation the larger number will be TS more often.

One other tiny thing—I'd probably rename O in Aux:

type Aux[L <: HList, Out0] = HListSum[L] { type Out = Out0 }

Mostly because O is easy to confuse with 0, and because I personally tend to use the 0 suffix as a convention in these cases. That's entirely a matter of taste, though.

Lastly, if I were writing this for a library I'd probably use a sealed abstract class instead of a trait and would make the object final, but neither change is terribly important.


Shortest way to form a string out of a subsequence of a string

I believe your code is O(n^2*m), where n is the target and m is the source. Overall, though, I think there are a lot of readability improvements that could be made here by separating functions and renaming variables (j is a particularly bad contender).
// indexCharacters('hello')
// = {'h':[0],'e':[1],'l':[2,3],'o':[4]}
const indexCharacters = source => {
    const map = new Map();
    for (let i = 0; i < source.length; i++) {
        const char = source[i];
        if (!map.get(char)) map.set(char,[]);
        map.get(char).push(i);
    }
    return map;
}

// matchLength('abc','abeee') = 2
const matchLength = (source,target) => {
    let count = 0;
    for (let i=0;i<source.length;++i)
        if (target[count] === source[i])
            ++count;
    return count;
}

const shortestWay = (source, target) => {
    const all_character_indices = indexCharacters(source);
    let occurrences = 0;
    let targetIndex = 0;
    while (targetIndex < target.length) {
        const starting_indices = all_character_indices.get(target[targetIndex]);
        if (!starting_indices) return -1;

        const match_lengths = starting_indices.map(
            sourceIndex=>matchLength(
                source.substr(sourceIndex),
                target.substr(targetIndex)
            )
        );

        targetIndex += Math.max(...match_lengths);
        ++occurrences;
    }
    return occurrences;
};

console.log(shortestWay('abc','abcbc'))
console.log(shortestWay('abc','acdbc'))
console.log(shortestWay('xyz','xzyxz'))


Python Find Tuple by Geographic Priority

You're right, it is clunky.

The first important step is to pick a function name that succinctly describes the task that it performs, namely, picking the most specific address component.

Once you do that, you might realize that "the most X of Y" means that you should use the max() function.  You just have to map each tuple to some quantitative measure of "specificity".

def most_specific_address(addresses):
    SPECIFICITY = {
        'country': 1, 'state': 2, 'county': 3, 'city': 4, 'zip': 5,
    }
    return max(addresses, key=lambda addr: SPECIFICITY[addr[4]])


Image Scrolling in UITableView with Parse

I predict that scrolling in this tableview would be choppy.  The problem you are trying to solve is pretty common - for example, find a shopping app that has to display many images of products in a UICollectionView.  The scrolling in these UICollectionViews is smooth even though you might be scrolling through hundreds of images.  How do they do this?

Here are my suggestions.

1)  Find an image caching framework to use like Kingfisher or its Objc predecessor SDWebImage.

2)  Parse objects have a URL property (according to their docs).

3)  When you populate the tableview, each cell gets configured with its own Parse object.  Within each cell, use the image caching frameworks method for setting an image on that cell's image view with that cell's Parse object's url property.

4)  Paging - if you have thousands of users, you don't want to download all 50000 at once.  Inside cellForRowAtIndexPath, you should check the current row against the data source array of the table view and see if you're about to run out of data to display, and when that happens, eg (row <= data.count - 4) call your fetch method for more Parse data.


Double-Ended Queue - Have I over-engineered it again?

I would make it so that you only have one sentanal.

Then the list is empty when head and tail point at the same object.

DeQueue::DeQueue()
    // set up the sentinels
    : head(new QueueItem())   // prefer to use initialize list.
    , tail(head)              // Make sure your declarations are in the correct order.
{

    head->next = head;        // Circular linked list.
    head->last = head;

    head->data = NULL;        // No data in the fake node.
}

Your delete loop does not actually move:

while(current->next != head)
{
    delete current->next;  // your deleting the element
                           // But not moving the the current item
                           // So the loop will not exit.
}

DeQueue::~DeQueue()
{
    // Delete from the head.
    // Just slowly loop over the nodes deleting them as you go
    while(head != tail)
    {
         QueueItem* old = head;
         head           = head->next;

         delete old;
    }
    // Delete the sentanal object created in the constructor.
    delete tail;
}

// Simplify empty.
bool DeQueue::Empty()
{
    return tail == head;
}


Extracting a number from provided URLs inside a text file

You can use a regular expression to find the ID. The pattern [0-9]+$ will match one or more occurrences of 0-9 at the end of the string. You can use it like this:

private static readonly Regex UrlId = new Regex("[0-9]+$");

private static string ExtractID(string url)
{
    var match = UrlId.Match(url);
    return match.Success
        ? match.Captures[0].Value
        : string.Empty;
}

Instead of using a StreamReader, consider using File.ReadLines

foreach (var line in File.ReadLines(path))
{
    if (ValidateUrl(line))
    {
        TweetIDsList.Add(ExtractID(line));
    }
    else
    {
        Logger.Log("Invalid URL: {0}", line);
    }
}

You can remove the variable result from ValidateUrl:

private static bool ValidateUrl(string url)
{
    Uri uriResult;
    return Uri.TryCreate(url, UriKind.Absolute, out uriResult) &&
        (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
}


Yes, if you chain with each then its has to be a recursive structure like that.

I like the mediator pattern for this...

var mediator = d3.dispatch('phase1', 'phase2'),

 bubbles = d3.selectAll(".bubbles")
   .style("opacity", 0.5);

 mediator.on('phase1', function(then) {

  d3.select(".bubble1")
  .transition().duration(2000)
    .style("opacity", 1)
    .transition().duration(2000)
   .style("opacity", 0)
  .each('end.phase1', function () { mediator[then]() })

 });

 mediator.on('phase2', function() {

  d3.select(".bubble2")
  .transition().duration(2000)
    .style("opacity", 1)
    .transition().duration(2000)
   .style("opacity", 0);

 });

 mediator.phase1('phase2');

bubble1

bubble2

It's much easier to automate


String template using concrete implementation instead of external library

One probable issue is performance, suppose there are 30 tokens to be replaced. And email template has a size of 50 kb. strings are immutable in C#/.Net. That means whenever you call StringTemplate.SetAttribute it creates a new string by manipulating existing and return the new string. suppose there are 30 tokens so it will create 50KB * 29 waste string. It will create more pressure on GC and GC will collect more often which will lead to poor performance. Better to use List<char> to do this kind of operation.


Using Python to search a sorted 2D Matrix

Unfortunately, using binary search both for rows and columns is not possible here. It fails if the last element of the first row is too small, i.e. for this input:

matrix = [[ 0,  1,  2,  3,  4,  5],
          [ 6,  7,  8,  9, 10, 11],
          [12, 13, 14, 15, 16, 17],
          [18, 19, 20, 21, 22, 23],
          [24, 25, 26, 27, 28, 29]]
target = 10

However, you could use binary search within each row for \$\mathcal{O}(n\log m)\$ runtime, compared to your \$\mathcal{O}(n + m)\$ runtime, as you noted in the question. While this is nominally worse, for the actual testcases being tested by Leetcode it performs better.

from bisect import bisect_left

class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix or not matrix[0]:
            return False
        for row in matrix:
            i = bisect_left(row, target)
            if i < len(row) and row[i] == target:
                return True
        return False

Your code: 36ms, faster than 85.35%

Binary search: 28 ms, faster than 98.39%

This is probably due to the testcases being small enough (and  if \$m = n\$, \$2n > n\log_b n\$ for \$n < b^2\$).


Collecting company data from accident reports

for i, j in enumerate (list):

You can't iterate through list because it is a type, so I am assuming that list is the name of a variable that you defined earlier on.  Don't do that.  When you use the name of something built-in for something else, you are overriding the variable that was previously defined.  If, for instance, you wanted to iterate through a list of tuples, but you actually wanted a list of lists, you could do for sub in map(list, tuples):, but with list redefined, you can't do that.  Besides that, it may confuse future readers of your code to be using list there when you can't iterate through a type.  Instead, use a name that not only says what type of object it is, but describes what is inside.

You have quite a bit of duplicate code in that if j == 'Last 10 accidents': block.  You should instead use a for loop iterating through different starting points.  That is, for start in (28, 50, 72): and use date = list[last + start], employee = date[list + start + 3], ...  You should be using a more descriptive name than list anyway, but I outlined that above.

with open("report.csv","a+") as report:
    report.write(str(name)+", "+str(date1)+", "+str(employee1)+", "+str(days_lost1)+", "+str(days_paid1))

Using a long string (no pun intended) of concatenations doesn't seem very good, does it?  Instead, use .join():

info = (name, date1, employee1, days_lost1)
report.write(", ".join(map(str, info)) + "\n")

That shortens the code and makes it a little easier to see what you are doing.

report.close()

The with statement will take care of closing the file so you don't need that line.

Your modified program would look like this:

name = company_location
for i, j in enumerate(reports):
    if j == 'Last 10 Accidents':
        last = i
        for start in (28, 50, 72):
            try:
                date = reports[last + start]
                employee = reports[last + start + 3]
                days_lost = reports[last + start + 21]
                days_paid = reports[last + start + 15]
                info = (date, employee, days_lost, days_paid)
                with open("report.csv","a+") as report:
                    report.write(", ".join(map(str, info)) + "\n")
            except (ValueError, TypeError, IndexError):
                with open("report.csv","a+") as report:
                    report.write(str(name)+"\n")