I honestly have no idea from your code what it is that it's supposed to do.  I've run it several times and am still no better off.
Naming
Naming is an important aspect of coding.  It makes your code much more approachable / self documenting.  Almost none of your names give me any kind of hint as to what they represent or do.  i,j,r,s They may mean something to you, but they don't to me.  Put them together and you get this line if (k[i * s + j] == '*').  Give your variables meaningful names.  Your method names are similarly abstract 'check', check what?  'toLadders' which seems to replace '*' with '#' for some reason.
Give your user a chance
You may write the best program in the world, but if you can't convince people to use it then it has almost no value.  Your program needs some information from the user, however they aren't told what it is.  You simply start scanning characters from stdin.  Maybe this is ok because stdin is always redirected from a file, but if not tell your users what you're expecting.  Ask them for input, then try to get it, don't just assume they're going to know what's expected of them.
Bounds Checking
Some of your bounds checking looks off to me.  You create a matrix[r][s] then do this:
for (i = 0; i < r; i ++){
    for(j = 0; j < s; j++){
        if (matrix[i][j - 1] == '.' && matrix[i][j] == '#' && matrix[i][j + 2] == '.'
            && matrix[i + 1][j] == '.' && matrix[i + 1][j + 1] == '#' && matrix[i + 1][j + 2] == '#' && matrix[i + 1][j + 3] == '.'){

It looks a lot like when j=s-1, you're going to be accessing matrix[i + 1][s - 1 + 3], which is out of bounds...

Keep in mind I wrote this in 1 hour - all the time we had for the task.

Honestly, the amount of time you had initially to write the task is a side issue, you presumably had the option to revisit the code and make it the best you could offer before posting.  Meaningful naming costs very little time and usually pays for itself with maintained understanding.  It is the biggest step you could take to make your code more approachable.  The more approachable your code is, the more value you are likely to get from reviews as reviewers will spend less time getting to grips with what you're doing allowing them to focus more on the how and why.


You can accept arguments from the command line.

You don't need to differentiate between decode and encode, you can simply provide negative shift.

You can hide the big lambda into a char -> char function.

You actually don't need the string -> string nor vector -> vector implementations.

encodeStr is a terrible name :)

You can leverage the char -> char implementation and copy istream_iterator<char> to ostream_iterator<char> char by char, and doing it over std::cin and std::cout will give you the ability to change the files as needed (through pipes) or use standard input / output by default.

#include <iostream>
#include <algorithm>
#include <iterator>
#include <sstream>

const unsigned char caesar_range = 'Z' - 'A' + 1;

char caesar_cipher(char c, int shift)
{
    char offset;
    if (c >= 'a' && c <= 'z') offset = 'a';
    else if (c >= 'A' && c <= 'Z') offset = 'A';
    else return c;

    shift = shift % caesar_range;
    auto base = c - offset + shift;
    if (base < 0) {
        base = caesar_range + base;
    }
    return base % caesar_range + offset;
}

void caesar_usage()
{
    std::cout << "Usage caesar <shift>\n";
    std::cout << "\tshift must be integer and providing -shift decodes string encoded with shift.\n";
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        caesar_usage();
        return EXIT_FAILURE;
    }

    int shift;
    std::stringstream ss(argv[1], std::ios_base::in);
    ss >> shift;
    if (ss.fail() || !ss.eof()) {
        caesar_usage();
        return EXIT_FAILURE;
    }

    // turn off white space skipping
    std::cin >> std::noskipws;

    std::transform(
        std::istream_iterator<char>(std::cin),
        std::istream_iterator<char>(),
        std::ostream_iterator<char>(std::cout),
        [&](char c) -> char {
          return caesar_cipher(c, shift);
        }
    );

    return EXIT_SUCCESS;
}

Encode | decode:
./caesar 5 <in.txt | ./caesar -5


thing I really don't like is my counter variable that I reset at 7

may be just keep incrementing the counter as counter = (counter + 1) % 8 instead of keeping it in the for loop.

  Any advice on how to improve this code?

this may be just me, but bit operations are very mysterious so I'd like to have a variable for 0x7F & 0xFF to understand what's to special

Also, I'm not really sure why counter == 6 leads to the additional bit. It would help if you could take it out into a function that gets called.

result.endsWith("\r") seems a bit odd. Is that a specific requirement. If so, do you also need to handle \n ?

throw new AsnDecodeException("Cannot get charset: X-Gsm7Bit"); when throwing exceptions, I'd recommend adding some context on the  input data leading to the error message. It helps a lot when

Don't forget to test for bad input data like

""
null
"zz"
"123456789ø"

I'd also just recommend creating a helper class and using hamcrest matchers to make the testing more readable i.e. assertThat(hex("f4f29c9e769f1b"), is("testing"))


Bad performance bash, changing display brightness

I'm confused about your goal for this question:

performance is bad
performance isn't terrible
improvements would be appreciated
improvements have nothing to do with performance.

Nevertheless, code review notes:

you don't have to export every variable, only the ones that are needed by processes you spawn from this script.
validate inputs: why do anything if the input is neither "0" nor "1"?

Here's my take:

#!/bin/bash
# increase/decrease display brightness of xrandr of both displays
# use:
# $ ./change_brightness [up/down (0/1)]

current_brightness=$(xrandr --verbose | awk '/Brightness/ { print $2; exit }')
case $1 in
    0) direction=-1;;
    1) direction=1;;
    *) echo "some error message"; exit 1;;
esac

export current_brightness direction
new_brightness=$( perl -E '
    use List::Util qw( min max );
    say max(0, min($ENV{current_brightness} + $ENV{direction} * 0.2, 1.0));
')

xrandr --output eDP-1-1 --brightness $new_brightness
xrandr --output DP-0 --brightness $new_brightness


Generating a data validation list and sorting it alphabetically

I would refactor your code and add  Worksheets("Data Validation").Range("A1").Select to the end to clear the selection.

Refactored Code

Changes:

ColumnLetter(): Removed
sht2: Replaced using a With block.
For j: Changed to For item.  item.Value is much easier to distinguish than sht.Cells(j, listcol).Value
.Range("A1").Select:  Added to clear the dreaded selected column
Cell reference fully qualified for the Sort ranges (I am surprised that the code would run without Worksheets("Data Validation") being the ActiveSheet.
sht2.Range("A2:K500").ClearContents: Replaced made dynamic using sht2.Range("A1:K1").CurrentRegion.Offset(1).ClearContents

Sub PopulateAllDataValidationLists()
    Dim sht As Worksheet
    Dim i As Long, listcol As Long
    With Worksheets("Data Validation")
        Application.ScreenUpdating = False

        .Range("A1:K1").CurrentRegion.Offset(1).ClearContents
        Dim columnName As String
        Dim InvalidValues As Variant

        InvalidValues = Array("UNK", "xxx", "yyy", "zzz", "yxz", "zyx")

        Dim rColumn As Range, item As Range
        For i = 1 To 11
            columnName = .Cells(1, i).Value
            With Worksheets("Sheet 1")
                listcol = .Rows("1:1").Find(What:=columnName, LookAt:=xlWhole).Column
                Set rColumn = Range(.Cells(1, listcol), .Cells(.Rows.Count, listcol).End(xlUp))
            End With

            For Each item In rColumn
                If item.Value <> "" Then
                    If IsError(Application.Match(item.Value, .Columns(i), 0)) And _
                       IsError(Application.Match(item.Value, InvalidValues, 0)) And _
                       Len(item.Value) <= 3 Then
                        .Cells(.Cells(.Rows.Count, i).End(xlUp).Row + 1, i).Value = item
                    End If
                End If
            Next

            .Sort.SortFields.Clear
            .Sort.SortFields.Add Key:=.Cells(2, i), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
            Dim target As Range
            Set target = Range(.Cells(2, i), .Cells(.Rows.Count, i).End(xlUp))

            With .Sort
                .SetRange target
                .Header = xlNo
                .MatchCase = False
                .Orientation = xlTopToBottom
                .SortMethod = xlPinYin
                .Apply
            End With
        Next i
        .Range("A1").Select
    End With

    Application.ScreenUpdating = True

End Sub

Other Method

There are many ways that you can sort the data:

System.Collection.ArrayList : ArrayList Class (System.Collections) | Microsoft Docs, VBA for smarties: ArrayList
System.Collections.SortedList: SortedList Class (System.Collections) | Microsoft Docs, VBA voor smarties: SortedList, VBScript Scripting Techniques: SortedLists - Rob van der Woude
Bubble Sort: VBA Arrays - Bubble Sort - BetterSolutions.com
Quick Sort: VBA Arrays - Quick Sort - BetterSolutions.com

Here is an example of how you can use an ADODB.Recordset to create a table in memory to sort and potentially filter the data.

RSSort: Class

Option Explicit
Public FieldName As String
Private Const adVarChar = 200
Private Const adOpenKeyset = 1
Private Const adUseClient = 3
Private Const adLockPessimistic = 2
Private rs As Object

Private Sub Class_Initialize()
    FieldName = "Values"
    Set rs = CreateObject("ADODB.Recordset")

    With rs
        .Fields.Append FieldName, adVarChar, 255
        .CursorType = adOpenKeyset
        .CursorLocation = adUseClient
        .LockType = adLockPessimistic
        .Open
    End With
End Sub

Public Sub AddNew(ByVal item As Variant)
    rs.AddNew FieldName, item
End Sub

Public Property Get Filter() As String
    Filter = rs.Filter
End Property

Public Property Let Filter(ByVal sFilter As String)
    rs.Filter = sFilter
End Property

Public Sub Sort(Optional SortAscending As Boolean = True)
    rs.Sort = FieldName & IIf(SortAscending, " ASC", " DESC")
End Sub

Public Function ToArray() As Variant
    Dim data As Variant, results As Variant
    If rs.RecordCount = 0 Then
        ReDim results(1 To 1, 1 To 1)
        ToArray = results
        Exit Function
    End If
    rs.MoveFirst
    data = rs.GetRows(rs.RecordCount)
    ReDim results(1 To UBound(data, 2) + 1, 1 To 1)

    Dim r As Long

    For r = 1 To UBound(data, 2)
        results(r + 1, 1) = data(0, r)
    Next

    ToArray = results
End Function

Demo Code

Sub RSSorterPopulateAllDataValidationLists()
    Application.ScreenUpdating = False

    Dim data As Variant
    Dim c As Long

    With Worksheets("Data Validation")
        .Range("A1:K1").CurrentRegion.Offset(1).ClearContents
        For c = 1 To 11
            data = getValidationValues(.Columns(c), "", "UNK", "xxx", "yyy", "zzz", "yxz", "zyx")
            .Cells(2, c).Resize(UBound(data)).Value = data
        Next
    End With
End Sub

Function getValidationValues(MatchColumn As Range, ParamArray InvalidValues() As Variant) As Variant()
    Dim sorter As New RSSorter
    Dim col As Range
    Dim ColumnHeader As String
    ColumnHeader = MatchColumn.Cells(1, 1).Value
    Dim vExcluded As Variant
    vExcluded = InvalidValues

    With Worksheets("Sheet 1")
        Dim item As Range
        Set col = .Rows("1:1").Find(What:=ColumnHeader, LookAt:=xlWhole)
        If Not col Is Nothing Then
            For Each item In Range(col.Cells(2, 1), .Cells(.Rows.Count, col.Column).End(xlUp))
                If item.Value <> "" Then
                    If IsError(Application.Match(item.Value, MatchColumn, 0)) And _
                       IsError(Application.Match(item.Value, vExcluded, 0)) And _
                       Len(item.Value) <= 3 Then
                        sorter.AddNew item
                    End If
                End If
            Next
        End If
    End With
    sorter.Sort
    getValidationValues = sorter.ToArray
End Function

Edit

shtreplaced with With Worksheets("Sheet 1")
Constants (adOpenKeyset, adUseClient, adLockPessimistic) added to completely convert from early binding to late binding.
The ADODB library "Microsoft ActiveX Data Objects x.x Library" removed from original workbook


Unit test an ExecutorService in a deamon

TaskProcessor

I see little reason why this should extend Thread, rather than simply implement Runnable
as a thread it is responsive to interruption, yet there is no way a client can interrupt this thread, through API nor directly. No, I'm mistaken, a client could push a task that interrupts its own thread, yet that is not an obvious way to shut it down, nor a clean one (as the ExecutorWithQueue will not know its executor has stopped working).
I would replace while (true) with while (!Thread.currentThread().isInterrupted())
I'm not happy with the way the ExecutionException is eaten. Clients have no way to know about the Exception that occurred in the Task.
As an extension of the previous point : you deny your clients the benefits of a Future to monitor their submitted tasks.
you accept only Tasks, yet tere is no reason you couldn't handle all Callables.

ExecutorWithQueue

taskProcessor does not need to be a field
The values supplied to timeout and timeoutUnit in their declaration are always overwritten in the constructor. If you omit these initialization, you can make them final.
the queue and executor fields can also be final.

Test

Fiddling with sleep() is error prone. The test can fail if the sleep is too short, and all the time that the test sleeps in excess of what is needed delays the swift completion of the unit test suite. (in projects with many thread safety tests this can really make the total suite of tests too slow). Timing combinations are often more reliably simulated using CountDownLatches, and these will never take longer than needed.
I find it good practice to add a timeout value to the @Test annotation for these kinds of tests. If at some point deadlock or so occurs, the test will fail gracefully, rather than hold up the test server.

Semantics

I'm completely puzzled by what this class is intended to do. All submitted tasks will simply be executed in sequence. But that could simply be achieved by submitting them to an ExecutorService with just one thread, which already uses a queue to store tasks it has yet to run. When the timeout passes and the task isn't finished, you submit the next task, which will simply be queued by the underlying ExecutorService until the timed out task has finished. I suspect you somehow think the timeout will cancel the task, but it won't. If that is your intention, you'll need to add cancelling logic to handle a timeout, if it isn't there doesn't seem to be much point in this class.

The second test seems to assert that a timed out task does not execute. Yet it only asserts this after having slept a certain amount of time. If you increase the sleep time enough, the assertion will fail. (this is another argument pro CountDownLatch as that will communicate the test's intention better).

Hope you found this useful.


Dependency Injected StackExchange.Redis Client

I can share with you an example version of Redis service such as getting subscribers or accessing the other databases and also for catching connection issues.
ConfigurationOptions allows us to initialize service with more Redis servers(Redis pool), if needed you can easily change the constructor parameters.
Note that ConnectionMultiplexer.Connect(); is already static method, so you can initialize service in class when needed as I did below.
In Addition, I assume that you take ISerializer for the object serialization, if it is, I added an example of serialize/deserialize for you.
I hope it helps you.
    public class CacheClient : ICacheClient
    {
        private readonly ConfigurationOptions configuration = null;
        private Lazy<IConnectionMultiplexer> _Connection = null;

        public CacheClient(string host = "localhost", int port = 6379, bool allowAdmin = false)
        {
            configuration = new ConfigurationOptions()
            {
                //for the redis pool so you can extent later if needed
                EndPoints = { { host, port }, },
                AllowAdmin = allowAdmin,
                //Password = "", //to the security for the production
                ClientName = "My Redis Client",
                ReconnectRetryPolicy = new LinearRetry(5000),
                AbortOnConnectFail = false,
            };
            _Connection = new Lazy<IConnectionMultiplexer>(() =>
            {
                ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(configuration);
                //redis.ErrorMessage += _Connection_ErrorMessage;
                //redis.InternalError += _Connection_InternalError;
                //redis.ConnectionFailed += _Connection_ConnectionFailed;
                //redis.ConnectionRestored += _Connection_ConnectionRestored;
                return redis;
            });
        }

        //for the 'GetSubscriber()' and another Databases
        public IConnectionMultiplexer Connection { get { return _Connection.Value; } }

        //for the default database
        public IDatabase Database => Connection.GetDatabase();

        public T JsonGet<T>(RedisKey key, CommandFlags flags = CommandFlags.None)
        {
            RedisValue rv = Database.StringGet(key, flags);
            if (!rv.HasValue)
                return default;
            T rgv = JsonConvert.DeserializeObject<T>(rv);
            return rgv;
        }

        public bool JsonSet(RedisKey key, object value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None)
        {
            if (value == null) return false;
            return Database.StringSet(key, JsonConvert.SerializeObject(value), expiry, when, flags);
        }
        private void _Connection_ErrorMessage(object sender, RedisErrorEventArgs e)
        {
            throw new NotImplementedException();
        }

        //add/set cache methods removed for the sake of brevity.
    }

Adding Service
 services.AddSingleton<ICacheClient>(new CacheClient(allowAdmin:true));


You could move the matching test to a separate method, like this:

private function is_matching_day( $event, $dayOfWeek, $dayOfMonth ) {

    if ( $event['RCE_Type'] === 'Month' && $event['RCE_Day'] === $dayOfMonth )
        return true;

    return $event['RCE_Type'] === 'Week' && $event['RCE_Day'] === $dayOfWeek;
}

Then your foreach statement would be more readable, and the duplicated array_push() is gone:

$matchingEvents = [];
foreach( $this->recurringEvents as $event ) {
    if ( $this->is_matching_day( $event, $dayOfWeek, $dayOfMonth ) )
        array_push( $matchingEvents, $event );
}


Implementation of a Custom Database Class

Returning Early / Guard Clauses

Returning early is very easy to do and can severely improve your code.

Looking at findUserByMobile, it is nearly impossible to say which else closes which if on first glance. In this case it doesn't matter that much as all else do the same thing, but it is still not nice to read.

If you just invert the if and return, the code is a lot nicer:

 public function findUserByMobile($mobile) {
    $db = new Database();
    if (!$db->connect()) {
        return false;
    }

    $query = "SELECT * FROM users WHERE mobile = ?";
    if (!$db->prepare($query)) {
        return false;
    }

    $sql_str = "s";
    if (!$db->set_params($sql_str, $mobile) ){
        return false;
    }

    $ret = $db->exec_query_array();
    if (!$ret) {
        return false;
    }
    return $ret;
}

If you don't care what went wrong, you could also combine some of the ifs. In practice, you probably do care though.

Error Handling

Just returning false on error can make debugging quite difficult. Did the query fail because you couldn't connect to the database? Because the query is wrong? Because the parameter is wrong? Because no result could be found? We just don't know. Think about throwing exceptions instead.

Database connections

You really do not want to create a new database connection for each query. Instead, pass the database object to the method and reuse it.

Misc

connect sounds like it would connect something. Instead, it returns something. It is customary to name the method isConnected.
don't shorten variable names. ret is more difficult to read than return or result, metadata is better than md, etc.
always use curly brackets, even for one-line statements.


There's a much easier way to do this. Python slicing allows you to reverse a string with s[::-1]. So you can just do:

def is_palindrome(s):
    return s == s[::-1]

To make this work for integers, you can just str() the int.

Why would you want to do it this way? For one, you're already converting to a string. So this approach shouldn't have any worse performance characteristics. Your use of a deque here is probably a bit overkill. deques make sense when you have lots of prepending to lists. Here, your numbers aren't likely to be that many digits (even though integers in python can be arbitrarily large).  And then on top of this you then convert back to an int, which is an unnecessary step (as you could just compare the strings) and could fail (although it shouldn't).

And beyond the performance, using the deque (and converting back to an int) makes it more difficult to understand what your code is doing. s[::-1] is a well understood idiom that clearly conveys its purpose in context (s == s[::-1]).

I wouldn't return a tuple from the function. It's much more informative to return a bool and then use that to print whatever string you want:

if is_palindrome(str(num)):
    print(f'{num} is a palindrome')
else:
    print(f'{num} is not a palindrome')

You should also look into PEP8 to make your code look more consistent with Python's widely accepted style guide.

Looking at the performance:

$ python3 -m timeit -s 'from funcs import polindrome' 'polindrome(123456654321)'
200000 loops, best of 5: 1.26 usec per loop

$ python3 -m timeit -s 'from funcs import is_palindrome' 'is_palindrome(str(123456654321))'
500000 loops, best of 5: 435 nsec per loop

is_palindrome is about 2.8 times faster.

You may also want to write some unit tests as there are some strange cases that your code may not handle correctly (eg. should 120 be a palindrome of 21 since 021 == 21 or not since they are different lengths?)


The obvious possibility would be to just define the functions inside the class definition:

template <typename StorageType>
class Metres : public Unit<StorageType> {
public:
    static Metres fromMetres(StorageType metres) noexcept { return metres; }

    Metres operator+ (Metres rhs) const noexcept {
        return getRawValue() + rhs.getRawValue();
    }

    Metres operator+ (Centimetres<StorageType> rhs) const noexcept {
        getRawValue() + rhs.getRawValue() / StorageType(100);
    }

    Metres operator+ (Millimetres<StorageType> rhs) const noexcept {
        getRawValue() + rhs.getRawValue() / StorageType(1000);
    }

protected:
    using Unit<StorageType>::Unit;
};

The problem (as I'd see it, anyway) stemmed from two facts: these are templates, so you needed to include the template parameters, and the bodies of the functions in question are so tiny, they basically got lost in the noise.

Both of these point to the fact that (in this case) including the function definitions inline in the class definition gains a great deal, and loses nothing.


Super simple templated memory pool in C++

This currently will not work.

As every-time you create an object derived from MemoryPool you re-initialize the myUnusedMemory structure thus potentially messing up your management.

struct Game : public ag::util::MemoryPool<Game, 2>  {};

int main()
{
    Game* p1  = new Game;
    Game* p2  = new Game;
    delete p1;
    delete p2;

    // myUnusedMemory now set like this:
    // myUnusedMemory[0] = &myMemory[1];
    // myUnusedMemory[1] = &myMemory[0];

    // Now when we create the next one it resets the array:

    Game* p3  = new Game;
    // myUnusedMemory now set like this: (because the constructor reset the array)
    // myUnusedMemory[0] = &myMemory[0];
    // myUnusedMemory[1] = &myMemory[1];

    Game* p4  = new Game;  // Now p3 and p4 point at the same memory location
}

This line:

static T myMemory[capacity];

Is also not good as you are actually initializing the objects. Thus, when you are calling new your new operator is returning a pointer to an already initialized object . The constructor will then be re-called. Thus overriding the original content without the destructor being called (thus leaking any memory that should have been deleted).

I suppose you could call the destructor inside the new operator but that seems wasteful (and may be expensive) and sort of counter intuitive. So you want to use uninitialized memory for your pool.
You could do this:

static char myMemory[capacity * sizeof(T)];

But unfortunately this is not guaranteed to be correctly aligned.
If you dynamically allocate the memory then it will be fine. Use std::vector and it will be dynamically allocated and safe.

static std::vector<char>  myMemory(capacity * sizeof(T));


Powershell zip subfolders recursively, conditionally

[ValidateScript({
    if (Test-Path $_ -PathType Container) {$true}
    else {Throw "Folder $_ not found"}})]

Test-Path already returns a [bool] which is what is expected by [ValidateScript()] so this can be simplified by removing the if/else:

[ValidateScript(
    (Test-Path $_ -PathType Container) -or $(throw "Folder $_ not found")
)]

pwd is an alias for Get-Location. I always recommend avoiding aliases and abbreviations in reusable scripts.

if ($testzip -eq $True)

This can be simplified to:

if ($testzip)

Else{
"Zip dll not found or couldn't be loaded.
Check file is present and unblocked.
Exiting" >> "$WorkingDirectory\OutputLog.txt"
Exit
}

This should probably be thrown as an exception:

else {
    $e = "Zip dll not found or couldn't be loaded.
    Check file is present and unblocked.
    Exiting"
    $e >> "$WorkingDirectory\OutputLog.txt"
    throw [System.IO.FileNotFoundException]$e
}

$path = $s  #$s variable contains each folder
$path
Set-Location $path.FullName

There are a two things I want to address here.

First, the middle line:

$path

This is implicitly calling Write-Object $path which in your script is probably writing this out to the console, and that's probably the desired behavior. You should be aware that this actually makes it the return value of the current scope/scriptblock you're in, which means it's part of the return value of your script.

You might not care about that right now, and it might never matter because you'll never call this script from something that checks its output, but it's bad practice (unless you very explicitly do want that to be part or all of its return value).

If all you want is to show the path on the screen, use Write-Host. Or even better, add [CmdletBinding()] above your param() block and then use Write-Verbose. That will only show the output when someone calls the script with -Verbose.

Second, I believe you should avoid changing the current path when possible. If it's not possible or it's impractical, then at least make use of Push-Location and Pop-Location along with try/finally so that you restore the original working directory.

if ( $(Try { Test-Path $items }
    Catch { "Cannot find items in $fullpath.
    Sub-folders will be processed afterwards.
    ERROR: $_" >>  "$WorkingDirectory\OutputLog.txt"  }) ) {

This is confusing. Test-Path should not throw an exception; it should return $false when the path doesn't exist, so your catch should never run. In addition, if it did run, the entire expression might still return $true making the if always satisfied.

Seems this would be better written as:

if ( Test-Path $items ) {
    # ... do stuff
} else {
    "Cannot find items in $fullpath.
    Sub-folders will be processed afterwards." >>  "$WorkingDirectory\OutputLog.txt"
}

You should wrap your logging into a function instead of having "Some message"  >>  "$WorkingDirectory\OutputLog.txt" strewn about the code. If you ever have to When you have to update that it will be a pain.

Consider something like this:

function Write-Log {
[CmdletBinding()]
param(
    [Parameter(
        Mandatory=$true
    )]
    [ValidateNotNullOrEmpty()]
    [String]
    $Message ,

    [Parameter(
        Mandatory=$true
    )]
    [ValidateNotNullOrEmpty()]
    [ValidateScript( { $_ | Test-Path -PathType Leaf -IsValid } )]
    [String]
    $LogPath
)
    $Message  >>  $LogPath
}

Now you can do:

Write-Log -Message "Compressing $src to $dest" -LogPath "$WorkingDirectory\OutputLog.txt"

And, you can do this at the top of the script (with v3 or higher):

$PSDefaultParameterValues = @{
    "Write-Log:LogPath" = "$WorkingDirectory\OutputLog.txt"
}

And then just do:

Write-Log -Message "Compressing $src to $dest"

Of course you could also make -LogPath optional, and give it a default value if you must (for v2 and below compatibility).

Even if you have to supply the log file every time though, so what, you're already doing that. And wrapping this in a function gives you more options for changing how its written later (like automatically adding a timestamp to each log entry).


What is better to use for mapping value to Map of functions: tail recursion or foreach?

You never use your Map to lookup a filter function by its key. If you don't need any of the keys then you don't really need a Map.

def filterTwitter(str :String) :String =
  List(Twitter.removeRT
      ,Twitter.removeNickName
      ,Twitter.removeURL
      ,Emoticons.removePunctRepetitions
      ,Emoticons.removeHorizontalEmoticons
      ,Emoticons.normalizeEmoticons
      ,Beautify.removeCharRepetitions
      ,Beautify.removeNSpaces
      ).foldRight(str)(_(_))

EXPLANATION

The 1st underscore is an element from the List that is being folded. Because this is a fold Right, it will start with the last element (removeNSpaces) and work toward the head (removeRT).

The 2nd underscore is the result from the previous invocation and it is being passed as an argument to the filter function. (Actually it's a little more complicated than that, but this is an easy way to think about it.)

So this is what's going down:

removeNSpaces(str)             ===> resStr1
removeCharRepetitions(resStr1) ===> resStr2
normalizeEmoticons(resStr2)    ===> resStr3
. . .
removeRT(prevResStr)           ===> finalResStr


Optimizing producer consumer using monitors

for(;;) is the more idiomatic infinite loop, read as "forever".
Avoid long conditional blocks, and unneccessary indentation. What you actually have is a loop followed by the else-block. Which would be best written as:

while (buffer.size() == MAX_BUFFER_SIZE)
    space_in_buffer.wait(lock);
rest-of-loop;

Unless you prefer using a lambda for the condition.

space_in_buffer.wait(lock, [&]{ return buffer.size() == MAX_BUFFER_SIZE; });
rest-of-loop;

You are using the std::queue as a ring-buffer. That's inefficient, especially as the queue still allocates and frees its nodes on .push() and .pop(). Use a dedicated ringbuffer like boost::circular_buffer, orsomething without any dynamic allocation at all.
The format for printing a std::size_t with std::printf is "%zu". Don't drop the length-marker.
Mutex, buffer, and condition-variables should be encapsulated in a class-template with the buffer-size as a parameter for reuse.
Yes, you should minimize the time you hold the lock to maximize concurrency. See whether you can do that with scoping or need to manually release the lock.


You're missing the essential benefit of using a rolling hash:
for (int i = 0; i < tlen; i++) {
    String sub = haystack.substring(i, plen + i);
    int haystackHash = hashCode(sub);

Here, we examine plen characters of haystack at every character position, which is O(mn) where m is the haystack length and n the needle length.
By using a rolling hash, we only need to examine two characters each time around the loop (one to add to the hash, and one to remove from it).  That is of course O(m), which greatly improves the efficiency when n is large.
Only inspect the substring when there's a hash match, which should be infrequent.

Other issues:

Why convert needle and sub to char arrays to compare them?  You certainly don't want to do that every time around the j loop; you don't even need that loop if you write if (sub == needle) return i;.

if (t == true) is more simply written if (t) since that's the only true value that t can hold.  Again, not needed when you eliminate the j loop.

Improved code
You meant to write something more like this:
public int strStr(final String haystack, final String needle)
{
    if (haystack == null || needle == null)
        return -1;

    final int nlen = needle.length();
    final int hlen = haystack.length();
    if (nlen > hlen)
        return -1;

    int needleHash = 0;
    int hash_remove = 1;
    for (char c: needle.toCharArray()) {
        needleHash = addHash(needleHash, c);
        hash_remove = addHash(hash_remove, '\0');
    }

    int haystackHash = 0;
    for (int i = 0;  i < nlen - 1;  ++i) {
        haystackHash = addHash(haystackHash, haystack.charAt(i));
    }

    for (int i = 0;  i + nlen < hlen;  ++i) {
        haystackHash = addHash(haystackHash, haystack.charAt(i + nlen));
        if (haystackHash == needleHash && haystack.substring(i, i+nlen) == needle)
            return i;
        haystackHash -= haystack.charAt(i) * hash_remove;
    }

    return -1;
}

private int addHash(int h, char c)
{
    // calculation may overflow, but that's fine
    return 31 * h + c;
}

The only magic in there is the computation and use of hash_remove, to undo the effect of characters that have moved out of the match window.


C++ class for capturing broadcast window messages

I haven't worked with WinAPI in years, so I can't help you much with that, but I do have a few concerns regarding style and structure of your code:

What's the meaning of this GUID? Does it have any, or is it just randomly generated?

WNDCLASSW wndcls = {0, wndproc, 0, 0, (HINSTANCE)hmodule, 0, 0, 0, nullptr,
              L"{F9F40031-F77E-4A5C-8A6C-30296B823C22}"};

A comment explaining why this specific value would be nice. Or better, make it a named constant with a self-explanatory name.
You have several instances of C-style casts in the code. Prefer using the C++ cast operators instead. They will give you warnings and diagnostics for potentially dangerous casts.
This looks very obscure:

CDummyWndClass::operator PCWSTR() const {
  PCWSTR p = nullptr;
  std::memcpy(&p, &atom_, sizeof(atom_));
  return p;
}

On my first look, I thought that you were trying to memcpy into a null pointer. The & on p is not easily spotted without a careful look. If you really must do this, then I think a reinterpret_cast would be more clear about your intentions. I did not test this, but something along the lines of the following should do:

CDummyWndClass::operator PCWSTR() const {
    const std::uintptr_t intVal = static_cast<std::uintptr_t>(atom_);
    PCWSTR ptrVal = reinterpret_cast<PCWSTR>(intVal);
    return ptrVal;
}

It would probably look clearer if you'd lay out that loop inside CWndMsgReceiver construtor is a more spaced way, to give it emphasis. Default { } is always good too:

  do Sleep(0); while (!(HWND)hwnd_);

 do {
     Sleep(0);
 } while (!(HWND)hwnd_);

You should also comment that this is not an infinite loop, but that it waits on an independent thread to set the variable.
This might be your personal preference, I for one I'm not a big fan of cast operator overloads. I've seen instances when they can produce some pretty obscure code. IMHO, I think your cast operators would look much nicer as plain Get*() methods.
You don't seem to use the wacky Microsoft prefixes on variable names, though you do use the C prefix for class names. Again, this is a subjective point, but I think your class names would be more readable without it.


Coherent usage of Hibernate's session and DAO

Instead of working with Hibernate sessions, I encourage you to use the JPA API. I think this is the most common way to work with Hibernate now. (http://www.theserverside.com/news/2240186700/The-JPA-20-EntityManager-vs-the-Hibernate-Session-Which-one-to-use)

For the transaction aspects and the initialization of your DAOs, I also think that a solution like Spring (http://projects.spring.io/spring-framework/) would help to simplify the code of your application.

Your code would look more like the following (with annotations stuff):

public class MyService {
  @Resource
  private AModelDAO aDao;

  @Transactional
  public void something(object) {
    // no need to manage transactions or sessions here
    aDao.save(object);
  }
}


Displaying total cost of prices from a table

First, I would switch from using eval to parseFloat, since it appears that eval provides no extra features and allows arbitrary code to be executed unless you just happen to have values other then numbers in total_item_price tds.

Second, since you are performing no extra processing with prices_array, it would be better to skip the array altogether and combine:

 var prices_array = new Array(); // Where our prices are held
 // For each .total_item_price - a <td> within my table.
 $(".total_item_price").each(function(){
     var text = $(this).text();                   // Get the value
     var prices = text.substring(1, text.length); // Format it into a string
     prices_array.push(prices);                   // Push it onto our array
 });

 var result = eval(0);
 //  Add up our array
 for(i = 0; i < prices_array.length; i++)
 {
     temp = eval(prices_array[i]);
     result += temp;
 }

into (with result renamed as totalSum for readability):

 var totalSum = 0;
 // For each .total_item_price - a <td> within my table.
 $(".total_item_price").each(function(){
     var text = $(this).text();                   // Get the value
     var price  = text.substring(1, text.length); // Format it into a string
     price = parseFloat(price);
     totalSum += price;
 });


Let us analyze what the code is doing:

reading a file by calling File.ReadAllBytes()
converting these bytes to a base64 String
passing this String to the Encrypt method
converting the passed String to byte[]
encrypting this byte[]
converting the encrypted byte[] to base64
converting the IV vector to base64
returning the addition of 6., 7. and the extension
converting the returned Stringto byte[] which is saved to a file with .aent extension

I can only see one reason why you want to do it in this way.

-> because you want to store the extension of the original file into the encrypted file.

Let us assume we don't want to store the extension of the original file inside the encrypted file, but we just append the .aent extension to the original filename.

This would have a lot of benefits. The code could be faster and the files could be smaller.

Why so ?

As CodesInChaos pointed out in the comments, Base64 increases the size of the data by 1.33 because for each 3 bytes you get 4 bytes back and the output is padded to always be a multiple of 4.
So starting with a file having a size of 1000 bytes after 2. you have 1336 bytes. After the encryption the conversion to base64 of the encrypted data, only assuming you still would have 1336 bytes, will result in 1784 bytes. Now adding the to base64 converted IV vector, which has a size of 16 for the default RijndaelManaged, will result in additional 24 bytes. The \n will result each in 2 bytes.

So all together: 1784 + 2 + 24 + 2 = 1812 almost a factor of 2.

So let us skip the base64 converting and the adding of the file extension.

Some remarks about the code

using of const for the keysize is good
using proper casing for methodnames and parameter is good except byte[] Encrypted
using the using keyword for using IDisposable objects is good

using a parametername plainText but also stating it could be a jpeg file is not so good
the way of getting the extension, instead of using built in methods is not so good

What you can do, but this is really a matter of taste, to reduce the indention of the code is stacking the using statements together like shown below. If we also extract the getting of the keybytes to a separate method, we loose one more indention and also the Encrypt() method gets shorter.

Refactoring

So let us start with the latter:

private static byte[] GetKeyBytes(string passPhrase)
{
    using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
    {
        byte[] keyBytes = password.GetBytes(keysize / 8);
        return keyBytes;
    }
}

Now we will change the String plainText input parameter to byte[] plainBytes and the returntype to byte[]

But wait, as we get two byte arrays, one of the encrypted data and one of the IV vector data, we need to combine these to one array. So let us introduce a method first

private static byte[] Combine(byte[] first, byte[] second)
{
    byte[] ret = new byte[first.Length + second.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    return ret;
}

And now the Encrypt method

public static byte[] Encrypt(byte[] plainBytes, string passPhrase)
{
    byte[] keyBytes = GetKeyBytes(passPhrase);

    using (RijndaelManaged symmetricKey = new RijndaelManaged())
    {
        symmetricKey.GenerateIV();
        symmetricKey.Mode = CipherMode.CBC;

        using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, symmetricKey.IV))
        using (MemoryStream memoryStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
        {
            cryptoStream.Write(plainBytes, 0, plainBytes.Length);
            cryptoStream.FlushFinalBlock();
            return Combine(memoryStream.ToArray(), symmetricKey.IV);
        }
    }
}

If we want to decrypt this array, we need to get the last 16 bytes and use it as IV vector. The bytes till the last 16 bytes will then be the encrypted data itself.

Now, let us use the Encrypt() method

Console.Write("Enter File Path: ");
docPath = Console.ReadLine();
byte[] binarydata = File.ReadAllBytes(docPath);
byte[] Encrypted = Encrypt(binarydata, m.ToString());
File.WriteAllBytes(docPath + ".aent", Encrypted);

Additional

You really should check out the System.IO.Path class, as this class provides many helpful methods like GetExtension() for getting the fileextension, GetFileNameWithoutExtension() etc. .


applyFilters - function which take array of items and array of excludes and return filtered by excludes array of items

I believe you should take a bit more time on documenting what the applyFilters functionality requires from input parameters. You seem to have pretty specific requirements which would be good to have them documented. You could document them using JsDoc syntax in the following way

/**
 * @method applyFilters
 * @param { object[] } items: An array of objects
 * @param { {k: string, v: object}[] } exludes: An array of objects containing key that need to be checked for certain values
 * @returns { object[] } A filtered array of objects
 */
 const applyFilters = (items, excludes) => { /*...*/ };

I think the algorithmn can be improved however with 1 very simple change, nl:

const applyFilters = (items, excludes) => {
  const newExcludes = excludes.reduce((acc, curr) => {
    if (!acc[curr.k])
      acc[curr.k] = new Set();

    acc[curr.k].add(curr.v);

    return acc;
  }, {});

  return items.reduce((acc, curr) => {
    for (let key in curr) {
      if (newExcludes[key] && newExcludes[key].has(curr[key]))
        return acc;
    }
    // using [...acc, curr] is very expensive here
    acc.push(curr);
    return acc;
  }, []);
};

The operation [...acc, curr] is a very expensive operation to use inside a reduce function. Since you start your operation with an empty arr and you only wish to add 1 item, I don't see why you use the simpler version of pushing an item and returning the existing array. The reason why it is that expensive is because it creates a complete copy of the previous array and just add's one item.

As an addition, I also made a small test that clearly shows the difference in performance, the test generates a set of 1500 items and around a 100 exclude filters, and clearly shows the difference in performance by taking out the expensive copy the spread operator introduces

/**
 * @method applyFilters
 * @param { object[] } items: An array of objects
 * @param { {k: string, v: object}[] } exludes: An array of objects containing key that need to be checked for certain values
 * @returns { object[] } A filtered array of objects
 */
const applyFilters = (items, excludes) => {
  const newExcludes = excludes.reduce((acc, curr) => {
    if (!acc[curr.k])
      acc[curr.k] = new Set();

    acc[curr.k].add(curr.v);

    return acc;
  }, {});

  return items.reduce((acc, curr) => {
    for (let key in curr) {
      if (newExcludes[key] && newExcludes[key].has(curr[key]))
        return acc;
    }
  return [...acc, curr];
  }, []);
};

/**
 * @method applyFiltersNoSpread
 * @param { object[] } items: An array of objects
 * @param { {k: string, v: object}[] } exludes: An array of objects containing key that need to be checked for certain values
 * @returns { object[] } A filtered array of objects
 */
const applyFiltersNoSpread = (items, excludes) => {
  const newExcludes = excludes.reduce((acc, curr) => {
    if (!acc[curr.k])
      acc[curr.k] = new Set();

    acc[curr.k].add(curr.v);

    return acc;
  }, {});

  return items.reduce((acc, curr) => {
    for (let key in curr) {
      if (newExcludes[key] && newExcludes[key].has(curr[key]))
        return acc;
    }
  acc.push(curr);
    return acc;
  }, []);
};

/**
 * @method testScenario
 * @param { number } runTest: how many time should the test be repeated
 */
const testScenario = function(runTest) {

  /**
   * @method generateItems
   * @param { number } totalItems: how many items should be generated
   * @param { object } template: an object describing how the items should look like
   * @param { string[]=* } on or more arrays that provide values for the template to be filled
   * @returns { object[] }
   */
  function generateItems(totalItems, template) {

    let result = [];
    for (let i = 0; i < totalItems; i++) {
      let item = {};
      for (let field in template) {
        let target = arguments[template[field]];
        let index = parseInt(Math.random() * target.length);
        item[field] = target[index];
      }
      result.push(item);
    }
    return result;
  }

  // this will create some larger seeds
  console.time('generate_items');
  const items = generateItems(
    1500, {
      type: 2,
      name: 3,
      color: 4
    }, ['phone', 'laptop', 'computer', 'netbook', 'tablet'], ['iPhone', 'Sony', 'Acer', 'Asus', 'MSI'], ['red', 'gray', 'pink', 'gold', 'silver', 'metalic', 'orange']
  );
  console.timeEnd('generate_items');

  console.time('generate_filters');
  const excludes = generateItems(
    100, {
      k: 2,
      v: 3
    }, ['color', 'type'], ['red', 'black', 'metalic', 'sony', 'iPhone']
  );
  console.timeEnd('generate_filters');

  for (let i = 0; i < runTest; i++) {
    console.log(`running test loop ${i}`);
    console.time('withSpread');
    let setResults = applyFilters(items, excludes);
    console.timeEnd('withSpread');

    console.time('noSpread');
    let noSpread = applyFiltersNoSpread(items, excludes);
    console.timeEnd('noSpread');

    !(noSpread.length === setResults.length && noSpread[0] === setResults[0] && noSpread[noSpread.length] === setResults[setResults.length]) && console.error('results do not match');
  }
};

testScenario(10);


its doing multiple nested for loop. How to reduce to 1?

I've seen this on SO, but only realised the biggest optimisation today.

The first optimization is to not build the $interval_array array in each iteration.  This code starts with the empty array and then in each loop just adds the next number in sequence to this array.

for ($i=0; $i <$n; $i++) {
    // Reset array in outer loop
    $interval_array = array();
    for($j = $i;$j < $n; $j++){
        // Add in new number to interval array as the key
        $interval_array[$main_array[$j]] = 0;

So the first time round it will add be [1], then on the second loop it add the next number in and will be [1,2] etc. (although they are actually [1=>0], [1=>0, 2=>0] the principle is the same)

The main difference is note that it adds the number as the key of the array and not the value.  This allows the main optimization which is when you are checking if you want to exclude particular combinations in...

        if(in_array($abc[$l], $interval_array) &&
         in_array($xyz[$l], $interval_array)){

it will look through (up to) the entire array twice to check for the values.

If instead you had the values as the key, you could use isset()...

            if(isset($interval_array[$abc[$l]]) &&
                isset($interval_array[$xyz[$l]]))   {

This is much more efficient at just checking a value exists.

The last thing I've added is that I create an array with all of the numbers you are checking against in (use array_flip() to again make these numbers the keys)...

$interest = array_flip(array_merge($abc, $xyz));

This allows me to check if the number is even something I'm interested in before running the more detailed checks...

    if ( isset($interest[$main_array[$j]] )) {

Put all of this together...

$n = 1299;
$start = microtime(true);
$main_array = range(1,$n);
$counter = 0;
$abc = [2,1];
$xyz = [3,4];
$count = sizeof($abc);  // $abc and $xyz size will same always.

// Create a combined array which lists all the numbers interested in
$interest = array_flip(array_merge($abc, $xyz));
for ($i=0; $i <$n; $i++) {
    // Reset array in outer loop
    $interval_array = array();
    for($j = $i;$j < $n; $j++){
        // Add in new number to interval array as the key
        $interval_array[$main_array[$j]] = 0;
        $counter++;
        // Only check for exclusion if interested in the number
        if ( isset($interest[$main_array[$j]] )) {
            for ($l=0; $l < $count ; $l++) {
                // if block here to additional condition using isset()
                if(isset($interval_array[$abc[$l]]) &&
                    isset($interval_array[$xyz[$l]]))   {
                        $counter--;
                        // Exit 2 levels of array as all further combinations will be excluded
                        break 2;
                }
            }
        }
    }
}

echo $counter."=".(microtime(true)-$start);

On my laptop (i7-3632QM, 8GB) the results of running this for 1299 are

original code...

841756=206.25858306885

modified code...

841756=0.34013700485229


Determine if elements in an ArrayList are consecutively ordered

You don't need a counter in your code:

public boolean isConsecutive(ArrayList<Integer> list) {
    for (int i = 0; i < list.size() - 1; i++) {
        if (list.get(i) != list.get(i + 1) - 1) {
            return false;
        }
    }
    return true;
}

As a next step, you can change the loop to start at 1 instead of 0, so that the loop condition becomes simpler.

public boolean isConsecutive(ArrayList<Integer> list) {
    for (int i = 1; i < list.size(); i++) {
        if (list.get(i - 1) + 1 != list.get(i)) {
            return false;
        }
    }
    return true;
}

The specification does not require the algorithm to be constant-time (it's not used for cryptography), therefore it should be OK to return as soon as you know the answer.

To be extra correct, you could detect integer overflows:

int prev = list.get(i - 1);
if (prev != list.get(i) /* mismatch */ || prev + 1 < prev /* overflow */) {
    return false;
}

If the requirements were to change that you may only access each list element once, you would need to remember the previous value.

public boolean isConsecutive(ArrayList<Integer> list) {
    Iterator<Integer> it = list.iterator();
    if (!it.hasNext()) {
        return true;
    }

    int prev = it.next();
    while (it.hasNext()) {
        int curr = it.next();
        if (prev + 1 != curr /* mismatch */ || prev + 1 < prev /* overflow */) {
            return false;
        }
        prev = curr;
    }
    return true;
}


Splitting string by words to new strings

Add some documentation to function.

While the name strsplit is pretty descriptive in itself, you should still add documentation to at least explain the argument and the return value.

For example, I was a little confused when I saw strsplit because I thought it should've taken another argument that was the delimiter.

Add some more comments to your code!

I had to rubberduck this code a couple times before I understood what was happening and where.

I think at least having a comment for what each variable was doing would help a lot.

Allocating and re-allocating memory is very inefficient. You should set one size of memory that will definitely fit the amount of memory needed.

For example, you could just allocate, for each output string, the size of the input string. However, this eats up a lot of memory for big strings.

You may have to come up with another algorithm for this.

You are sort-of reinventing the wheel here, and I don't think that that is your intent.

<string.h> already has a function char *strtok(char *str, const char *delim). However, this function only grabs tokens one at a time, so you'd have to take these steps:

Grab a token
Put it in the string array
Go to 1

Is roughly what you'd have to do.

I wrote out an implementation in C. If you'd like to see it, then leave a comment.


Wrapper to translate text in wxPython widgets

After I posted this question and saw that I wrote that I try to write a Wrapper, I thought that this might be the solution...

import wx
from wx.lib.pubsub import pub

def multilingual(wrapped):

    class WrappedClass(wrapped):
        def __init__(self, *args, **kwargs):
            # Translate label parameter
            if len(args) >= 3:
                self.ml_label = args[2]
                args = list(args)
                args[2] = _(self.ml_label)
            else:
                self.ml_label = kwargs.get('label',wx.EmptyString)
                kwargs['label'] = _(self.ml_label)
            super().__init__(*args,**kwargs)
            pub.subscribe(self.Update, 'language.changed')

        def Update(self):
            print('update')
            super().Update()
            super().SetLabel(_(self.ml_label))

        def SetLabel(self, label):
            print('setlabel')
            self.ml_label = label
            super().SetLabel(_(self.ml_label))

    return WrappedClass

@multilingual
class Button(wx.Button):
    pass

@multilingual
class StaticText(wx.StaticText):
    pass


Only see 1 bug:
void ConnectedPoint::connectTo(const ConnectedPoint& point)
{
  next = new ConnectedPoint(point.index(),point.position());
  *(next->next) = *(point.next);
}

In other places where you connect things (copy constructor/assignment) you delete the list of object pointed at by next before overwriting. You don't do that here. So if next is not a nullptr then you will leak.
Simplify
Your code is based on the fact that the next pointer owns a unique version of the object it points at. Whenever you do any manipulation of lists you preserve this by making sure you dynamically create copies of the object (which is fine). But there is already a class that will do this for you.
 std::unique_ptr<ConnectedPoint>  next;

std::unique_ptr is not only designed to correctly do ownership semantics by using you are explicitly telling everybody that you are using ownership semantics and they need to read less of your code to understand the semantics of your object.
Assignment does not provide strong gurantee
ConnectedPoint& ConnectedPoint::operator=(const ConnectedPoint& point)
{
  if(this == &point)
  {
    return *this;
  }

  // Delete the old state
  delete next;
  next = nullptr;

  // STUFF

  // What happens if this fails?
  next = new ConnectedPoint(*(point.next));

  // If an exception is generated (it may be caught higher up in the stack).
  // At this point your object now has lost the state it used to have and
  // never got the new state. So the behavior of your code could be eratic
  // after this point.

  // MORE STUFF
}

The Strong Exception gurantee basically says either the operation works correctly OR (the operation fails with an exception AND the object is unchanged). TO do this you need to use a more conservative technique. But its easy. You just use what is called the copy and swap idium.
ConnectedPoint& ConnectedPoint::operator=(const ConnectedPoint& point)
{
    ConnectedPoint copy(point);
    copy.swap(*this);
    return *this;
}
ConnectedPoint::swap(ConnectedPoint& rhs)
{
    using std::swap;
    swap(m_index,    rhs.m_index);
    swap(m_position, rhs.m_position);
    swap(next,       rhs.next);
}

The first thing people notice is that there is no test for self assignment.
  if(this == &point)
  {
    return *this;
  }

This is because it is no longer needed as we always make a copy. Sure this makes it less efficient when we do self assignment (add it back in if you really want). But self assignment though possible is actually very rare. So you are optimizing for a very rare condition at the expense of the normal operation. So normal operations are slowed down (the thing that happens all the time) while we optimize for things that are unlikely to happen.


You can also overload operator>> instead of using getdata():

std::istream& operator>>(std::istream& in, calculator& obj)
{
    return in >> obj.val;
}

Similar approach with showdata(), using operator<<:

std::ostream& operator<<(std::ostream& out, calculator const& obj)
{
    return out << "value: " << obj.val;
}

As for your existing overloads, you shouldn't need to return a calculator.  You appear to treat each calculator object as a single value.  This makes each one to appear to be single-use, and the more values you wish to enter, the more objects thus the more code you'll need to have.

What you should do is maintain one object and have val maintained as you enter data.  However, this will also mean that your arithmetic operators aren't needed.  If you wish to keep them, then you'll have to approach this differently.  For instance, you can calculate (not merely input) a final value for different calculators and use those operators to get a new value.  This may look like a needless approach for a simple calculator, but at least you're still able to utilize these arithmetic operators.

Some miscellaneous notes:

Be aware of the issues of using using namespace std.
You don't appear to be using <conio.h>, so just remove it.
You don't need to use std::endl in so many places.  A simple "\n" for outputting a newline should be sufficient.  More info about that here.


A Simple Unix Filter in Racket - Learning the Racket Way

Overall, this is very pleasant code to review.  Especially given you're new to the language.  Your function names are follow convention such as the use of ending predicates with ? and indicating conversions with ->.  The comments make this code easy to understand.  So bravo, keep at it!  That being said, here are some pretty minor suggestions.

"Favor define when feasible".  Your let's and let*'s could be changed to internal define's to decrease nesting.
Change (define (main) ...) to (module+ main ...).  Submodule support added in June's 5.3 release make having main's and test's easier than ever.
Within main, should one of the cond branches be using write-as-text instead of write-as-code?  right now, both branches do the same thing.  Along the same vein, the comment above write-as-text was copied but not changed from ;; write-as-code.
In racket, we have 3 ways of doing output, display, write, and print.  Since your write-as-text/code functions use printing, I would change the names of those functions to be called print-as-text/code


The methods verifyRow, verifyCol, verifyGrid, and verifySudoku are all only accessed inside this class. Therefore, there is no point in making them public right?

If there do happen to be other classes, just they aren't shown here, you could probably leave verifySudoku as public because it makes sense for another class to possible access those.

I think Sudoku should be it's own, immutable, separate class. It should probably hold the 2D int array that is the sudoku board.

Now thinking about, the should be the class with the method verifySudoku (I'd call it isValid) because the method is to validate a sudoku board and the Sudoku class is holding a board to being with.

Here is what I came up with for the class:

public class Sudoku {
    private final int[][] board;
    private final int rows;
    private final int columns;

    public Sudoku(int[][] board, int rows, int columns) {
        this.board = board;
        this.rows = rows;
        this.columns = columns;
    }

    public boolean isValid(...) {
        [code]
    }

    private boolean verifyGrid(...) {
        [code]
    }

    private boolean verifyRow(...) {
        [code]
    }

    private boolean verifyCol(...) {
        [code]
    }
}

public boolean verifyRow(int arr[][], int num, int i, int j, int col) {

The argument names i and j are not descriptive whatsoever.

int k;
for (k = 0; k < col; k++) {

You do not need to declare the iterator variable outside of the loop. This can and should be turned in to:

for (int k = 0; k < col; k++) {

I think you have a very smart algorithm for verifying if the board.

Here is the way I thought of:

Create an java.util.ArrayList of the numbers 1-9.
In each verify method, copy this ArrayList.
Iterate through the row/column/grid's squares
If the number is in the array list, go to 6
If not, return false
Take the number out of the array list
If the array list is empty, return true
Go to 3

(I believe) This works because, by removing the numbers from the array list, you are making sure that that number is not repeated again in that row, which would make a row invalid if it contained 2+ of the same number.

Here is my implementation in Java:

private boolean verifyRow(int row) {
    List<Integer> numbers = new ArrayList<Integer>(this.allNumbers);

    for(int i = 0; i < this.rows; i++) {
        if(numbers.contains(i)) {
            numbers.remove(new Integer(i)); // using java.util.ArrayList.remove(Object o) so I turned int i to an Integer
            if(numbers.isEmpty()) {
                return true;
            }
        } else {
            return false;
        }
    }
}

This used my Sudoku class idea.
allNumbers is the list of numbers 1-9 to copy.

I am not sure which version is faster.


Available doors

Why is this a stand-alone function?  Why are door identifiers hard-coded here?  The MontyHallBox knows what the doors are, and what they are called:

class MontyHallBox(object):
    def available_doors(self):
        return list(self.__doors.keys())

Class Syntax

class MontyHallBox(object):
    ...

is obsolete syntax.  Use:

class MontyHallBox:
    ...

Class Private Names

Why use a double underscore for self.__doors and self.__init_doors()?  This is a Python feature for avoiding name collision in derived classes, and "mangles" the names is a predictable fashion (adding the classname as a prefix):

>>> mhb = MontyHallBox()
>>> mhb._MontyHallBox__doors
{1: 'car', 2: 'goat', 3: 'goat'}
>>>

It does not provide any extra security of the member.

Use set notation

Instead of set([initial_door, noncar_door]), write {initial_door, noncar_door}.

Throw-away variables

The variable i is never used:

    for i in range(num):
        results.append(simn_fun(mhb))

The PEP-8 recommendation is to use _ for these throw-away variables:

    for _ in range(num):
        results.append(simn_fun(mhb))

List comprehension

Building up a list of results should be done using list comprehension, instead of initialization & repeated .append operations.  Instead of:

    results = []
    for i in range(num):
        results.append(simn_fun(mhb))

Use:

    results = [simn_fun(mhb) for _ in range(num)]

Counting

There is no need to build up a long list of results, just to count the result distributions.  Pass the results as they are generated to a counter.

>>> import collections
>>> num = 10000
>>> simn_fun = run_sim_always_switch
>>> counts = collections.Counter(simn_fun(mhb) for _ in range(num))
>>> counts['success']
6717
>>> counts['fail']
3283

or, knowing True is 1 and False is zero, count the successes as you generate them yourself:

>>> success = sum(simn_fun(mhb) == 'success' for _ in range(num))
>>> success
6614

Formatting

Use f-strings to put the variables/expressions directly in the format statements:

    print(f'Always switch, run simulation {num} times.')
    print(f'Success ratio: {run_simn(num, run_sim_always_switch)}')
    print(f'Never switch, run simulation {num} times.')
    print(f'Success ratio: {run_simn(num, run_sim_never_switch)}')

Round results to the desired significant figures with appropriate format codes:

    print(f'Success ratio: {run_simn(num, run_sim_never_switch):.3f}')

Named Constants

If you accidentally wrote the tests as if item == 'Car':, you'd find that nobody wins, and would have to hunt down where in the code you made spelling/capitalization errors.  The IDE won't help you; it can't auto complete strings for you.  If you used named constants ...

CAR = 'car'
GOAT = 'goat'

... and you wrote if item == Car:, instead of nobody winning, the program would crash with an unknown identifier and identity the line where the problem exists, which is much better than having to search through all of the code looking for where logic is going wrong.  But the above named "constants" aren't actually constants; they are variables we hope never get accidentally (or maliciously) changed.

from enum import Enum

Prize = Enum('Prize', 'CAR, GOAT')

Now we have Prize.CAR and Prize.GOAT, which are constants.

Malicious Strategies

A friend can say they've come up with a great strategy - and let you test their code:

import friend

run_simn(10_000, friend.strategy)

And lo and behold, they always win the car!  How is this possible?

Friend strategy 1:

def strategy(mhb):
    initial_door = next(door for door, prize in mhb._MontyHallBox__doors.items()
                        if prize == 'car')
    _ = mhb.reveal_noncar(initial_door)
    item = mhb.reveal_selected(initial_door)
    return 'success' if item == 'car' else 'fail'

Friend strategy 2:

def strategy(mhb):
    initial_door = 1
    goats = { mhb.reveal_noncar(initial_door) for _ in range(10) }

    if len(goats) == 2:
        selected_door = initial_door
    else:
        selected_door = 2 if goats == { 3 } else 3
    item = mhb.reveal_selected(initial_door)

    return 'success' if item == 'car' else 'fail'

Friend strategy 3:

def strategy(mhb):
    return 'success'

They are cheating.  Some friend.

A safer (harder to cheat) simulation approach

Let's start by creating some type aliases, to make clearer code.

from typing import Callable, Counter, List, NewType, Tuple

# Doors are numbered
Door = NewType('Door', int)
Doors = List[Door]

This Door is just a fancy way of saying the int type-hint, and Doors is a fancy way of saying the List[int] type-hint.

Now let's create two methods which the let's the user play the Monty Hall game:

def first_pick(doors: Doors) -> Door:
    """
    Ask the player to pick a door
    """

    return int(input(f"Pick a door [{', '.join(map(str,doors))}]: "))

def second_pick(doors: Doors, selected: int, goats: Doors) -> Door:
    """
    Show some goats behind doors the player didn't pick.
    Ask them again to pick a door.
    """

    print(f"Monty shows you a goat behind door #{', '.join(map(str, goats))}.")
    choice = input(f"Pick a new door [default: {selected}]: ")
    return int(choice) if choice else selected

We pass all the information the player needs to make their choices.  In the first case, just the list of available Doors.  In the second, we add what their original Door selection was, and the Doors Monty Hall revealed goats behind.  No extra MontyHallBox object, or self parameter that the user can peek into to cheat and get extra information.

We can even add types for these two functions up where we are defining the types we're using:

FirstPick = Callable[[Doors], Door]
SecondPick = Callable[[Doors, Door, Doors], Door]

Now, let's build the actual game:

def monty_hall(first: FirstPick = first_pick, second: SecondPick = second_pick, *,
               cars: int = 1, goats: int = 2, reveal: int = 1) -> Tuple[Door, Prize]:
    """
    Play a Monty Hall type game.

    The player picks one of several doors, behind each is either a Car or a Goat.
    Monty Hall shows the player behind one of the doors they didn't pick,
    "Oh look, behind this door is a Goat!  Now, do you want to change your mind?"
    The player now gets alter their selection, but does it pay to change their mind?

    Parameters:
        first: given the doors, pick a door
        second: given the doors, the first pick, and what was revealed, pick a door
        cars: number of cars (default 1)
        goats: number of goats (default 2)
        reveal: number of hidden goats to reveal (default 1)

    Returns:
        The door they choose, and the Prize behind it (a Goat or a Car)
    """

    # Sanity checks
    if cars < 1 or goats < 1:
        raise ValueError("Rigged game!  There must be both cars & goats!")
    if reveal >= goats:
        raise ValueError("Monty is not allowed to reveal all of the goats!")

    # Set up the game
    prizes = [Prize.CAR] * cars + [Prize.GOAT] * goats
    random.shuffle(prizes)
    doors = list(range(1, len(prizes) + 1))
    game = { door: prize for door, prize in zip(doors, prizes) }

    # Ask player to make their initial selection...
    selected = first(doors)

    # Monty reveals some doors
    goats = [ door for door, prize in game.items()
              if prize == Prize.GOAT and door != selected ]
    random.shuffle(goats)
    goats = goats[:reveal]

    # Based on original choice and revealed doors, ask player makes new choice...
    selected = second(doors, selected, goats)

    # ... and give the player their prize
    return selected, game[selected]

Ok, I've beefed up the game a little bit.  We've got a configurable number of cars (default 1), goats (default 2), and doors to reveal (default 1).  We've got first and second functions which default to the first_pick and second_pick user player functions above.  We've got a long doc-string describing the function.  Then we've got some validation on number of cars, goats, and reveals.

Then we have the meat-and-potatoes of the function.  Create the prizes, mix them up, and hide them behind doors.  Call the first method to get the initial door selection.  Then Monty Hall picks some doors with goats to reveal.  The second the second function is called to get the final door selection.  Finally, the resulting prize is returned.

Want to play the game?

def human_verses_monty(**kwargs):
    door, prize = monty_hall(**kwargs)
    print(f"Behind door #{door}, you find a {prize.name}!")

Use human_verses_monty().  Or maybe human_verses_monty(cars=3, goats=3, reveal=2)

I'm using **kwargs for brevity, so I can pass additional keywords through to the underlying monty_hall(...) method.  It would be clearer to list all of the keyword arguments out, but this post is already getting pretty long, and I'm not done yet.

Playing multiple times

Now that we have our safe simulation, let's make it so we can play the game multiple times, and collect the results:

def monty_halls(strategy: SecondPick, games, *,
                initial: FirstPick = random.choice, **kwargs) -> Counter[Prize]:
    return Counter(monty_hall(initial, strategy, **kwargs)[1] for _ in range(games))

The initial door pick defaults to random.choice.  We need to pass in a strategy for the second pick.  The game is played the given number of times, with Door, Prize being returned, from which we select only the Prize with [1], and count the number of times we get each prize in a Counter.

Now we need some strategies:

def always_switch(doors: Doors, selected: Door, goats: Doors) -> Door:
    return random.choice(list(set(doors) - set(goats) - {selected}))

def never_switch(doors: Doors, selected: int, goats: Doors) -> Door:
    return selected

Again, no extra information to allow them to cheat.  And they don't get to break the rules and play incorrectly (asking Monty Hall multiple times to reveal doors) to cheat.

How about function to evaluate various strategies:

def evaluate(strategies: List[SecondPick], games, **kwargs):
    for strategy in strategies:
        prizes = monty_halls(strategy, games, **kwargs)
        wins = prizes[Prize.CAR]
        losses = prizes[Prize.GOAT]
        total = wins + losses
        print(f"{strategy.__name__}: wins {wins / total * 100:.2f} %")
    print()

Let's see it in action:

if __name__ == '__main__':
    print("Standard game (1 car, 2 goats)")
    evaluate([always_switch, never_switch], 10_000)

    print("Alternate game (2 car, 3 goats, 2 reveals)")
    evaluate([always_switch, never_switch], 10_000, cars=2, goats=3, reveal=2)

Running this gives:

Standard game (1 car, 2 goats)
always_switch: wins 66.88 %
never_switch: wins 33.12 %

Alternate game (2 car, 3 goats, 2 reveals)
always_switch: wins 80.14 %
never_switch: wins 39.91 %

Cheaters will be cheaters

It is still possible to cheat.  One method would be to capture the stack frame, and look at the local variables in the calling frame.  We can get around this by using a separate thread or process to execute the strategy calls in, so the caller can't simply walk up the stack looking for gold.  This still isn't fool proof, 'cause the cheater could look for the parent thread, or parent process and try to inspect those.

At least we aren't making it easy to cheat, like the original MontyHallBox approach did.


1

I personally like to reduce the amount of string assembling where possible, so instead of:

result = 'PASS' if is_pal else 'FAIL'
str_not = 'a' if is_pal else 'not a'
print('{}: {} is {} palindrome'.format(result, repr(arg), str_not))

I would write:

PASS_TMPL = "PASS: {!r} is a palindrome"
FAIL_TMPL = "FAIL: {!r} is not a palindrome"
s = (PASS_TMPL if is_pal else FAIL_TMPL).format(arg)

In your example you had 3 variables in the string, in my example it's reduced to just 1 variable and 2 different templates.

of-course in this small program probably it doesn't matter which style you use. However if you build larger application the later style will bring you a few benefits:

output is more easily predictable
easier to change the output string without having a need to refactor the code
when debugging, and having to find location in code which produced certain output, it will be easier to grep the code for the specific string in question, if there is less string assembling going on.
if you need to add i18n support for your application at some point in time, you will learn that the way you assembled the strings only works in english, and your code needs to be refactored in order to support other languages

Because both styles usually are equally easy to code, avoiding the first style and preferring the 2nd style I think is a good habit to pick up.

2

Instead of the for loop to compare every individual letter, you can compare if the word is equal reversed version of it:

return word == word[::-1]

word[::-1] will reverse the word

This is not only shorter to write, but also in interpreted languages like python should run much faster too. A simple loop in python is very slow compared to a simple loop in C. String comparison will use compiled C implementation instead of looping each letter in python's loop.


The first solution is infinitely better than the second solution.  In Haskell, tail recursion is not the main concern.  Rather, the primary consideration is laziness.  Furthermore, operations like list reversal (myReverse, which you haven't shown us) and list concatenation (the ++ operator) should be avoided wherever possible, since they involve traversing an entire list to its end.  Considering that lists in Haskell may be infinitely long, you could be inviting trouble.

I consider your insertAt v [] n = [v] case to be superfluous and harmful.  If you are inserting an element into an empty array, I think it's fair to require the index to be 1.  I would write it like this:

insertAt :: a -> [a] -> Int -> [a]
insertAt v xs     1 = v : xs
insertAt v (x:xs) n = x : (insertAt v xs (n - 1))

In my opinion, the interface specified in the challenge is weird: the function would be better named insertBefore, since I expect that inserting an element at position 0 would place it at the head of the resulting list.

As a rule of thumb, Haskell functions should be designed so that the parameters are ordered starting from the one that is least likely to vary.  I would certainly not place the index at the end.  One better design would be insertAt value index list, such that insertAt value index could be treated as a partial function to be applied to some list.  Another reasonable design would be insertAt list index value, such that insertAt list index could be treated as a partial function that is waiting to fill a specified hole in the list.  However, with the current specification, the partial function insertAt value list means "add value to list, but we don't know where yet", which seems like a rare use case to me.


Simple authentication and registration of users

Cryptography

As others have mentioned, I would use bcrypt

Format

You have used good function names and variable names. However, you can add doc strings for each function.

def add_user(username, password):
    """"Function to add a user. Returns True for successful, or False for failure"""
    #Function code here

Additionally, you could improve your compliance with PEP8 (the Python Style Guide) by adding white-space around your equals symbols. This would greatly improve the readability of your code. Also, a more relaxed vertical spacing would improve the look of your code.

__main__

Not to sure if you want to create an default function for your code. But you could add (if __name__ == "__main__":)


Enabling/Disabling button on a certain condition

Some things that crossed my mind:

Your'e polluting the global namespace with embedUrl. Wrap your code in an IIFE, or make use of jQuery's data() method to pass around "global" variables.

IIFE example:

(function($, window, undefined){

    var embedUrl = null;

    // Do whatever you want in this scope without affecting window namespace
    // $ === jQuery, but you can still access the jQuery variable as well
    // window is passed for sligtly faster access
    // undefined is passed as an undefined argument to make sure it's
    // truly undefined (can be modified pre ES5)

})(jQuery)

// console.log(embedUrl); // undefined

jQuery's data example:

// Set data:
jQuery('.button-submit').data({ foo: 'bar' });

// Get data:
var foo = jQuery('.button-submit').data('foo');
console.log(foo); // "bar"

* I prefer Hungarian notation on jQuery objects to improove readbility i.e. change

var jqueryButton = window.jQuery('.button-submit');

to

var $button = jQuery('.button-submit');

In your example, jqueryButton is a jQuery object, so you can't do jqueryButton.href. If you want to access the href property, use the prop() method:

var href = $button.prop('href');

However, if you extract the selected DOM element from your jQuery object, your code would have worked:

var button = $button.get(0), // or $button[0]
    href = button.href;

Use prop() instead of attr(), unless you're using a really old jQuery version.
More info here.

You can use toggleClass() with a switch for your class toggling:

jqueryButton.toggleClass(constants.classDisabled, sender._invalid);

And set the href like this:

jqueryButton.prop('href', sender._invalid ? constants.emptyHref : embedUrl);

Just my two cents.


Speech Recognition Part 3: Training the Neural Network

First things first: you can get far better results by fine-tuning the arguments.

Yes, it goes over 52% at times and I'm sure it can go even higher. Let's take a look at what colours are caused by what.

  ORE1X4
  default settings
  EAPX5J
  Epoch 200 instead of 100
  6DHKQJ
  Dropout 0.9 instead of 0.8
  53O25D
  learning_rate 1e-3 instead of 1e-4
  0TWRK8
  256 instead of 128
  QCAZN8
  Epoch 300, dropout 0.9, learning_rate 1e-3, 256 instead of 128
  H57Z4I
  learning_rate 1e-3, epoch 400

I've rewritten 0.0001 as 1e-4, easier on the eyes. And you made a good start by putting it in a variable (which, according to the PEP8, should be CAPITAL_CASED since they're pseudo-constants). So why didn't you put the others in variables as well? Look at how the functions you call have named their arguments and use this as inspiration for your variable names.

Keep in mind you're using spectograms as input. Spectrograms have some downsides, since they only measure intensity of frequencies and not the phase. You may have heard this problem described as the phase problem. This means every spectrogram has broadband noise, impacting the overall effectiveness of your output. The measured effectiveness might not even be the real effectiveness, since it probably assumes you actually like the noise.

So, not only could you use more data to achieve a higher accuracy, you may eventually need more complete data. As in, less noise and with phase information.

As for performance, there's not much you can do. Your code runs significantly faster on my laptop than on your Mac (original set-up in under 15 minutes), even without using a GPU as acceleration. Tensorflow is pretty well optimized to use multiple cores.

Keep in mind the X-axis displays steps. The time it takes to reach a certain amount of steps can vary wildly depending on the arguments you provide. 0TWRK8 took 3 times as long to reach step 500 than H57Z4I, while the latter appears to be scoring better. Figure out which arguments are 'worth their weight' and which simply slow you down for little to no gain.

My advice? Experiment! After a couple hundred epochs the data will just about flatline, so going above 200 isn't particularly useful when going for sample runs.

Fidgeting with the input reminded me of a game I played a long while back: foldit

There's the early game, the mid game and the end game. In the early game, you're looking for the big changes. The later you get, the more your focus shifts to different aspects to fine-tune your approach. However, if you had an inefficient start, you couldn't fine-tune enough to reach the score you wanted. The score would flat-line.

Consider developing this machine in the same manner. Don't rush the development to make it go fast if that will hurt it's accuracy in the end. After all, nothing is as annoying as speech recognition that only works half the time. If you need certain functions to keep your output in good quality, don't optimize it away only to regret it later.

Something else your dataset doesn't take into account, is combinations of characters. ch isn't exactly pronounced as a combination of c  and h. The same goes for ph, th and other combinations. Keep this in mind when you start field testing your network.


There's a lot of repeated summing taking place in this part:

(sum(row[:i + 1]) for row in wall for i in range(len(row[:-1])))

So this is summing the first i+1 elements in the row, with an upper bound that steps through all values except the last. If the row was [1, 2, 3, 4, 5], these are the sums:

1
1+2 = 3
1+2+3 = 6
1+2+3+4 = 10

The sums differ, but only by the last term. It would therefore save effort to use a running sum instead, only adding that last term each time:

1
1+2 = 3
3+3 = 6
6+4 = 10

This can be done with itertools.accumulate:

(s for row in wall for s in itertools.accumulate(row[:-1]))

Another thing in your code that this approach solves is the i+1 summing. Instead of having this addition performed on every iteration, you could iterate through the correct values directly with for i in range(1, len(row)). But using accumulate, this is already taken care of.


Reddit bot to gather listening suggestions

1. General issues

r.login ('','', disable_warning=True) #notice True is boolean and not string

if you did disable_warning='False' it would still disable warning. Every non-empty string in python when cast to boolean will return True.

Too many global objects. Reddit API client can stay global r, having current_time as global is horrific. Stuff like submission_list results count genres shouldn't be global either but I can understand that your intent was to get those things from database so this is only temporary. All of those things should be returned by their functions at the moment when they are needed.

You shouldn't use login. It is being depreciated soon. What it means is that if not for the fact that praw devs don't want to break every single bot there is they give you a little time to remove login() from old bots. New bots shouldn't use this at all, because by the time you have it up and working it might be broken again cause login() will no longer be there. Check OAuth2 - it's bit more that single call to login() but still can be done in 2 minutes (and it's one time).

2. Multithreading

So there are multiple issues with multithreading here. First off you don't need it here. Your bot has only one functionality. Grab data, parse data, give output, repeat. Second one is that multiprocessing/multithreading in python is generally not too common unless there is actual need for that due to massive overhead, that usually makes things slower in the long run. So it would only be feasible if you want your program to extremely long stuff in parallel.

Lastly reddit bot is extremely bad example to try to multithread. The reason are reddit API restrictions. It will not respond to request more often than 0.5 sec. This is how developers have set it and also praw behaves by it. If you make 20 requests you will have to wait 10 seconds no matter how many threads try to do this. This is why it is always done in sequences with those.

3. Modularity

First off your program should have more functions, just for the sake of readability. Like

def get_submission_list():
    submission_list = []
    for submission in sub.....
    ...
    return submission_list

def send_messsages(results):
   .....

def main_loop():
    while True:
        check_inbox_for_new_bot_subscribers()
        s_list = get_submission_list()
        subscribed_users = get_subscribed_users_and_genres_from_db()
        results = prepare_results(subscribed_users,s_list)
        send_messages(results)

submission_list is kinda obvious, subscribed_users could be a list of tuples or a dictionary with 'username':'genres,separated,by comma' or w/e you feel comfortable working with. results in this case would be (username,[list of links to send to this user])

For the sake of checking multiple users it would be beneficial to also reverse username-genres dictionary, so that we also have fast lookup dictionary of 'genre':[list of usernames subscribed to this genre]'. This would be fun to implement, but benefit is obvious since we have now \$\mathcal{O}(n\cdot{}m)\$ time instead of \$\mathcal{O}(n^2\cdot{}m^2)\$.

Simple database model for this would be:

class BotSubscriber(Model):
    redditor_id = CharField()
    genres = CharField()

You obviously could save other stuff like time of subscription, how many songs you recommended to this user and w/e you feel like.

4. Clean out output

I believe '\n'.join(map(str,results)).strip('[]') or some variation of that would work as you want?

5. String search efficiency and better matching

It would be beneficial to parse submission.title before searching. Band - song [genre] (optional year) is pretty much standard format. Move Band - Song and save it as title and [genre] as genre (stripping starting braces as well).

On top of that you definitely use genre.lower() as well as save submitted user genres as lowercase. No need to be case sensitive in this scenario.

Once you have your genre saved as genre you can do any([1 for a in user.genres if a==genre.lower()]) or use reversed dictionary idea that I've posted in 3.


Solve membership binary mask problem in Scala

The "never occurs" bug is still there. It stems from the fact that the length of b has an inverse relationship to the length of x. Try varying the length of a non-occurring b and see what you get.

There's also the fact that this is a rather imperative approach, whereas good Scala style tries to be more functional.

When I first saw this I thought, "Doesn't indexOfSlice() offer most of what's needed?"

def binmask(seq :Seq[String], slice :Seq[String]) :String = {
  val ios = seq indexOfSlice slice
  if (ios < 0)
    "0"*seq.length
  else {
    val slcLen = slice.length
    "0"*ios + "1"*slcLen + "0"*(seq.length-slcLen-ios)
  }
}

The slight drawback here is that indexOfSlice() will traverse the seq input until it finds a match (or completely if not found) and then seq is traversed again for its length.

The standard Scala means to achieve iteration with early termination but without mutable state, is via recursion. Preferably tail recursion, which the compiler turns into a while loop under the hood.

def binmask(seq :Seq[String], slice :Seq[String], acc :String = "") :String =
  if (seq startsWith slice) {
    val slcLen = slice.length
    acc + "1"*slcLen + "0"*(seq.length - slcLen)
  }
  else if (seq.isEmpty) acc
  else binmask(seq.tail, slice, acc + "0")

Some feel that making the accumulator a passed parameter (even though it is "hidden" behind a default value) exposes too much implementation in the public interface. For them, an inner recursion loop is preferable.

def binmask(seq :Seq[String], slice :Seq[String]) :String = {
  def loop(subseq: Seq[String], acc: String): String =
    if (subseq startsWith slice) {
      val slcLen = slice.length
      acc + "1" * slcLen + "0" * (subseq.length - slcLen)
    }
    else if (subseq.isEmpty) acc
    else loop(subseq.tail, acc + "0")

  loop(seq, "")
}


Optimize Data Sending/Querying to Parse Swift iOS

I have some feedback concerning the usage of Swift optionals  in
your code.

The main point is that there is far too much "forced unwrapping". The forced unwrap operator ! can and should be avoided
in most cases. Instead of comparing with nil and forced unwrapping

if (parseObject != nil) {
     parseObject!.doSomething()
     parseObject!.doSomethingElse()
}

use optional binding to test and get the unwrapped value:

if let theParseObject = parseObject {
     theParseObject.doSomething()
     theParseObject.doSomethingElse()
}

Or, if parseObject is expected to be non-nil when the method
is called (e.g. because it is set up in viewDidLoad), declare it
as an implicitly unwrapped optional

var parseObject : PFObject!
// ...
parseObject.doSomething()
parseObject.doSomethingElse()

There is no reason to declare var notes as an optional Int?.
With

if var votes = parseObject.objectForKey("votes") as? Int { ... }

you get rid of more forced unwrap operators.

Finally, the votesLabel textfield outlet is expected to be non-nil
(otherwise you did not connect it correctly in the interface builder).
That is the reason why it is declared as an implicitly unwrapped optional
UILabel!. There is no need for optional chaining in

 votesLabel?.text = "+\(votes!)"

Putting it all together, the method should look like this:

@IBAction func happyBtn(sender: AnyObject) {

    if let theParseObject = self.parseObject {
        if var votes = theParseObject.objectForKey("votes") as? Int {
            votes++
            theParseObject.setObject(votes, forKey: "votes")
            theParseObject.saveInBackground()
            votesLabel.text = "+\(votes)"
        }
    }
}

No ! anymore!


Here are some tests I'd perform at the very least. There may be more you'd want:

Create an empty Stack. Test that its size is 0.
Push an element onto the stack. Test that its size is now 1.
Push another element onto the stack. Test that its size is now 2.
Pop an element from the stack. Test that it matches the 2nd pushed value. Check that the size of the stack is now 1.
Pop an element from the stack. Test that it matches the 1st pushed value. Check that the size of the stack is 0.
Attempt to pop an element from the stack. You should receive an ArrayIndexOutOfBounds exception.


As usual with your code, I can only come up with very minor nitpicks.

With both push functions, there is a small chance of a memory leak. After the construction of a new Adapter<T> using:

auto ptr = new Adapter<T>{ std::forward<Args>(args)... };

If entities.emplace_back(ptr); fails (say if relocation is required, the vector needs to expand, and this fails), then ptr will leak. Instead of doing it this way, I'd suggest using make_unique and moving the unique_ptr into entities using push_back instead:

template<typename T, typename... Args>
auto push(Args&&... args)
    -> void
{
    auto ptr = std::make_unique<Adapter<T>>(std::forward<Args>(args)...);
    entities.push_back(std::move(ptr));
}


Longest common prefix for set of strings

1. Don't think too much about performance.
Worst performance problems arise because the coder thought something could be faster but she didn't consider that the JVM does runtime optimizations for her code.
So always prefer writing readable code that works. Only step into performance optimization if you actually faced a performance issue and you have proven by measurement that this particular piece of code is the problem and the alternative approach really solves the problem.
2. Why are you inventing the wheel a 4th time?
The JVM has methods to compare strings. There is even a startsWith() method that would perfectly fit.
3 Structure your code
Your code has 2 obvious parts. The first one you marked with an inline comment.
Better use methods with good names for this kind of structuring.
An alternative solution could look like this:
My solution made some assumption on the behavior of the methods in the String class which I verified with spikes coded as JUnit Tests along with the acceptance test using your given example.
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class LongestCommonPrefixTest {

    @Test
    void spike__does_StartsWith_returnTrueForTheEmptyString() {
        assertTrue("someWord".startsWith(""));
    }

    @Test
    void spike__does_substring_returnTheEmptyStringForEndIndexZero() {
        assertEquals("", "someWord".substring(0, 0));
    }

    @Test
    void spike__does_substring_returnShorterStringForLengthMinus1() {
        String someWord = "someWord";
        assertEquals("someWor", someWord.substring(0, someWord.length() - 1));
    }

    @Test
    void acceptanceTest() throws Exception {
        String[] strs = { "flower", "flow", "flight" };
        String longestCommonPrefix = //
                new LongestCommonPrefix().longestCommonPrefix(strs);
        assertEquals("fl", longestCommonPrefix);
    }

}

And this is the solution I came up with:
public class LongestCommonPrefix {
    public String longestCommonPrefix(String[] strs) {
        String currentPrefix = selectFirstWordOrEmptyString(strs);
        for (String currentWord : strs) {
            currentPrefix = findCommonPrefixIn(currentPrefix, currentWord);
        }
        return currentPrefix;
    }

    private String selectFirstWordOrEmptyString(String[] strs) {
        return 0 == strs.length ? "" : strs[0];
    }

    private String findCommonPrefixIn(String currentPrefix, String currentWord) {
        while (!currentWord.startsWith(currentPrefix)) {
            currentPrefix = currentPrefix.substring(0, currentPrefix.length() - 1);
        }
        return currentPrefix;
    }
}

A performance improvement could be possible if you always pass the shorter of currentPattern and currentWord as first parameter to the private method and the longer one as second. But as I wrote you shouldn't do that unless necessary.


Counting letters program with ASCII-art graph

Let just say when I first read the question I was very impressed by the graph.
Well done.

Small mistake in reading the file:

char c;
for (int i = 0; !feof(fp); i++)
{
    c = fgetc(fp);

This is wrong in all languages. The eof is never set until you read past the eof. The last successful read reads up-to (but not past) the eof. So even if there are no more characters in the file the eof flag is not set (until you try and read the character after eof).

As a result you are suffering a one off error. The loop is executed one time to many. The value of 'c' on the last iteration is EOF truncated to fit into a char.

So the standard patter is to read from the file and see if it works. If it works then you enter the loop:

int c;
for (int i = 0; (c = fgetc(fp)) != EOF; i++)
{

Note we need to change the c from a char into an int to make sure that EOF is not truncated out of the value.

Not an error: But you are implementing an O(1) operation is O(n).

  for ( int j = 0; j < 26; j++ ) //find which letter it is
    {
      if( c == alpha[j] )
    {
      letters[j]++;
      break;
    }

With a little though you can invert the array. So you use the letter to look up its ID.

char alpha[256] =
{  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   //  0->15 ignore
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   // 16->31 ignore
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   // 32->47 ignore
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   // 48->63 ignore
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   // 64->79 ignore
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   // 80->95 ignore
   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,   // 96->111 a -
   16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0,   // 112->127 -z
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   // 128->143 ignore

   .. etc

   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};  // 240->255 ignore

   // Now the lookup becomes:
   if (alpha[c] != 0)
   {
       letters[alpha[c] - 1]++;
   }

But do you really care if you count all the characters. I would not (unless there are some serious space constraints). You can just count all the characters. When you print them out you just print the ones you want.

   int letters[256];

   ....
   letters[c]++;   // or maybe letters[tolower(c)]++;
   .....

   // Now we just need to de reference the count of the letters we are interested in.
   for( int i = 0; i < 26; i++ )
   {
       int count = letters[alpha[i]];
       if(count != 0){
           printf("The letter '%c' occurs %d times.\n", alpha[i], count);
       }
   }

Some small tidy up (you seem to have embeded tabs that mess up spacing on this site).