I find that writing it this way makes it more maintainable and relatively efficient.

public class Information
{
    public string Country { get; set; }
    public string City { get; set; }
    public string Street { get; set; }
    public string Block { get; set; }
    public string Building { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }

    private IEnumerable<Tuple<string[], string>> DataFormatPairs()
    {
        yield return Tuple.Create(new[] { Country },             "{0}");
        yield return Tuple.Create(new[] { City },                "city {0}");
        yield return Tuple.Create(new[] { Street },              "street {0}");
        yield return Tuple.Create(new[] { Block },               "block {0}");
        yield return Tuple.Create(new[] { Building },            "building {0}");
        yield return Tuple.Create(new[] { Latitude, Longitude }, "coordinates {0}:{1}");
    }
    public override string ToString()
    {
        var data = DataFormatPairs()
            .TakeWhile(p => p.Item1.All(s => !String.IsNullOrWhiteSpace(s)))
            .Select(p => String.Format(p.Item2, p.Item1));
        return String.Join(", ", data);
    }
}


return '' doesn't have the type List.
List means List[Any], you should use List[str].
Your variable names are garbage.

s -> string
n -> length
ch_map -> char_map or character_map
dp -> what does this even mean?
p1 -> position_1?

Don't put return statements on the same line as an if.
Again strings shouldn't be assigend to lists, yes you can iterate over them because they're both sequences. But they're not the same type. [ch_map[s[:2]]] if s[:2] in char_map else ''
ch_map should be a constant outside the function.
It's far easier to understand your code if it's written using recursion.
Recursion has some problems, and so it should be written in a way that allows you to easily convert it to a while loop.

CHAR_MAP = {str(i): chr(i) for i in range(10, 127)}

def asciidecode(string: str) -> List[str]:
    if not string:
        return []
    string = string[::-1]
    length = len(string)

    def inner(index):
        if index == length:
            yield ''
        else:
            for size in (2, 3):
                if length < index + size:
                    break
                letter = CHAR_MAP.get(string[index:index + size])
                if letter is not None:
                    for word in inner(index + size):
                        yield letter + word
    return list(inner(0))

def asciidecode_pre_while(string: str) -> List[str]:
    if not string:
        return []
    string = string[::-1]
    length = len(string)
    output = []

    def inner(index, word):
        if index == length:
            output.append(word)
            return

        for size in (2, 3):
            if length < index + size:
                break
            letter = CHAR_MAP.get(string[index:index + size])
            if letter is not None:
                inner(index + size, word + letter)
    inner(0, '')
    return output

From the second one it's easy to convert it to a while loop:

CHAR_MAP = {str(i): chr(i) for i in range(10, 127)}

def asciidecode(string: str) -> List[str]:
    if not string:
        return []
    string = string[::-1]
    length = len(string)
    output = []

    stack = [(0, '')]
    while stack:
        index, word = stack.pop()
        if index == length:
            output.append(word)
            continue

        for size in (2, 3):
            if length < index + size:
                break
            letter = CHAR_MAP.get(string[index:index + size])
            if letter is not None:
                stack.append((index + size, word + letter))
    return output


Batch Processing : Design check with SRP and OCP prinicple

Quick question, have you tried testing your code? Trying doing so, and you will find the leaks in your code.

DepositProcessor has a high dependency on DepositBatchProcessorSvc, why not to inject it and make the code flexible (easier to test and change).

public class DepositProcessor{
   private final DepositBatchProcessorSvc service;
   DepositProcessor(DepositBatchProcessorSvc service){
    this.service = service;
  }
}

BatchProcessorSvc could be totally generified,

/*K type of the object's promary key, and T is the object type*/
public interface BatchProcessorDao<K,T> {
  @Override
  Map<K, List<T>> fetchBatchData();
}

Always try to return interfaces and not implementations, ex:

HashMap<String, List<String>> fetchBatchData()

could be refactored to

Map<String, List<String>> fetchBatchData()

Save should never be fire and forget, I know a lot of db clients do it, but it is really bad, I need to know if things were saved successfully, wishful programming is bad, you could return the objects after saving them

List<T> saveBatchData(List<T> data);


I've approached it from a hint @hacatu said, that you are storing all the permutations in an array. I thought move this to a generator, although I think trying out Heap's algorithm could be beneficial too.

I'm only adding the function that has changes, the rest of the code stayed the same. When using generators, you don't need to build up a whole array, you get an Generator object which implements the Iterator interface. The execution of your code stops at the yield statement and only continue if next() is called ie in a foreach

function permutations($letters,$num)
{
    $last = str_repeat($letters[0],$num);
    // no result array
    while($last != str_repeat($this->lastchar($letters),$num))
    {
        yield $last; // <-- one change
        $last = $this->char_add($letters,$last,$num-1);
    }

    yield $last; // <-- another change
}

I've put these methods in a class called Permutation and used it like this:

$perm = new Permutation();
$perms = $perm->permutations('1234', 10); // $perms is a Generator object here

// I'm looping through the results, if needed you can build up an array here, but that will need a lot of memory as you already seen
foreach ($perms as $result) {
    printf("%s\n", $result);
}

printf("Max memory: %sK\n", number_format(memory_get_peak_usage(true)/1024));

When I run this code (as it doesn't do much just prints) it ends up printing me:

lots of permutations here
....
4444444444
Max memory: 2,048K

When I add all the permutations to an array, the memory usage jumps

lots of permutations here
....
4444444444
Max memory: 75,780K

I hope this helps.

Ps: If you are into JavaScript and redux have a look at redux-saga, it can also help understanding generators. If not, I hope the PHP docs will help you :)


Wrapping jQuery empty() To Include A Callback

I can't really see how wrapping empty() with a $.Deferred object manages to achieve anything; after all empty() executes immediately and doesn't need the consumer to wait for a function callback.

Instead think of how you might be using empty() with an asynchronous context and then abstract that. For example if it is an AJAX request which you need to empty an element out, then fetch, then display the new data your implementation might look like this:

var clearAndThenFetch = function($element, ajaxOptions, callback) {
    var deferred = $.Deferred();

    $element.empty();

    $.ajax($.extend({
        success: function(response) {
            callback && callback(deferred, response) || deferred.resolve();
        },
        error: function(xhr) {
            deferred.reject(JSON.parse(xhr.responseText).errors);
        }
    }, ajaxOptions));

    return deferred.promise();
};

Otherwise I can't really see the need for abstraction here.

Edit: In regards to Flambino's comment, why do you need the empty() deferred at all? Remember that DOM operations are synchronous and so don't need to use promises. With this in mind we can rewrite your function like so:

var emptyWithCallback = function(node, callback) {
    console.log('Entered emptyWithCallback()');
    if (typeof callback != 'function') {
        return false;
    }

    var doTheCallback = function() {
        var deferredCallback = $.Deferred();
        callback();
        deferredCallback.resolve();

        return deferredCallback.promise();
    }

    doTheCallback.then(function() {
        $(node).empty();
    });
}


Mouse control of a camera in an OpenGL program

Is the camera a global entity?  Will the only ever be just one?

Perhaps, but perhaps not. You can have two or more viewpoints shown in multiple viewports.  You might use shadow mapping, which positions a camera at a light source for rendering a shadow map.

If you are thinking of a generic “mouse controller” for a camera, which you can reuse in multiple applications, I’d shy away from the global camera.

If you are working on a one of a kind application, have no intention of reusing the code, will only ever use one point-of-view, and needs the minuscule speed gain and reduction of complexity of not passing a pointer to the camera around to functions as required, a global camera is fine.


"Always stay connected" mechanism for socket connection

I see there is problem in the usage to Timer. Consider the case if the server takes more time (> 5000) to connect, than the timer interval specified (3000) specified.  Then the timer elapsed event will fire again though the first elapsed event is not yet finished.  In order to avoid this stop the timer in the begin of Connect() and start the timer in end of Connect().


In your code there are several slow items:

1.

StrComp(Range("B" & i), dontDelete(j, 1), vbTextCompare) = 0
I would use Range("B" & i).Value2 = dontDelete(j, 1).Value2

2.

Like PeterT suggested deleting rows is quite slow, specially when you do it one at the time
I would hide the rows to keep, and at the end delete all visible rows in one operation

3.

Another significant performance issue is caused by interacting with the sheet
You could copy both ranges into 2 separate variants and loop them the same way as ranges

Bellow I'm providing a different approach:

create a new column with a formula that will find all matches from Account_Range
use AutoFilter to hide the rows you want to keep
delete all visible rows in one operation

Option Explicit

Public Sub DeleteRowsFilter()
  Const FAR_ROW1 As Long = 3

  Dim lrInput As Long, lrFAR As Long, lcFAR As Long, lastCell As Range
  Dim srcRng As String, fCell As Range, formulaRng As Range, t As Double

  FastWB
  t = Timer

  With ThisWorkbook.Worksheets("FAR")
    Set lastCell = GetMaxCell(.UsedRange)
    lrFAR = lastCell.Row
    lcFAR = lastCell.Column

    'create a new column showing if row should be deleted (value = 0) or not (value > 0)
    Set fCell = .Cells(FAR_ROW1, lcFAR + 1)
    fCell.Formula = "=IFERROR(MATCH(B" & FAR_ROW1 & ",Account_Range,0),0)"

    'fill down the formula to last row
    Set formulaRng = .Range(fCell, .Cells(lrFAR, lcFAR + 1))
    fCell.AutoFill Destination:=formulaRng: .Calculate

    'hide the rows to keep
    formulaRng.AutoFilter Field:=1, Criteria1:="=0"

    'delete visible rows (not matching values in Account_Range)
    fCell.Offset(1).Resize(lrFAR - FAR_ROW1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    .Columns(lcFAR + 1).EntireColumn.Delete 'delet last column (temp formula)
  End With

  Debug.Print "Duration:" & vbTab & Format(Timer - t, "#,##0.0000") & " sec" & vbCrLf
  FastWB False
End Sub

In my test file I only used 2 columns on each sheet, both with 10,000 rows
This version deleted more than 6,000 rows

Total Duration:   1.9338 sec

I also used 2 helper functions

Turn off visual elements:

Public Sub FastWB(Optional ByVal opt As Boolean = True)
    With Application
        .Calculation = IIf(opt, xlCalculationManual, xlCalculationAutomatic)
        .DisplayAlerts = Not opt
        .DisplayStatusBar = Not opt
        .EnableAnimations = Not opt
        .EnableEvents = Not opt
        .ScreenUpdating = Not opt
    End With
End Sub

Determine the last row and column:

Public Function GetMaxCell(Optional ByRef rng As Range = Nothing) As Range

    'Returns the last cell containing a value, or A1 if Worksheet is empty

    Const NONEMPTY As String = "*"
    Dim lRow As Range, lCol As Range

    If rng Is Nothing Then Set rng = Application.ActiveWorkbook.ActiveSheet.UsedRange
    If WorksheetFunction.CountA(rng) = 0 Then
        Set GetMaxCell = rng.Parent.Cells(1, 1)
    Else
        With rng
            Set lRow = .Cells.Find(What:=NONEMPTY, LookIn:=xlFormulas, _
                                        After:=.Cells(1, 1), _
                                        SearchDirection:=xlPrevious, _
                                        SearchOrder:=xlByRows)
            If Not lRow Is Nothing Then
                Set lCol = .Cells.Find(What:=NONEMPTY, LookIn:=xlFormulas, _
                                            After:=.Cells(1, 1), _
                                            SearchDirection:=xlPrevious, _
                                            SearchOrder:=xlByColumns)

                Set GetMaxCell = .Parent.Cells(lRow.Row, lCol.Column)
            End If
        End With
    End If
End Function


I tried to use WPF and still same preformence lose.. that is weird because WPF suppose to use DirectX and be fast in image proccessing.

Except, in the WPF version, you are cloning a Bitmap (which has nothing to do with WPF) and then calling Imaging.CreateBitmapFromHBitmap, which eventually resolves to a call to:

[DllImport("WindowsCodecs.dll", EntryPoint="IWICImagingFactory_CreateBitmapFromHBITMAP_Proxy")]
internal static extern int CreateBitmapFromHBITMAP(IntPtr THIS_PTR, IntPtr hBitmap, IntPtr hPalette, WICBitmapAlphaChannelOption options, out BitmapSourceSafeMILHandle ppIBitmap);

Now I don't know what that method is doing, but it may very well be copying the data again, but perhaps not.  Either way, your WPF method is performing at least one clone of the entire image and your WinForms version is not.

That's not really the meat of it though.  You haven't even posted benchmark results, so you need to do that first before assuming any one part of code is "slow", and you will have a hard time optimizing until you have that answer.  You're two versions aren't even identical in output; the WinForms version performs HighQualityBilinear interpolation, which is certainly going to take a significant amount of time.

You need to tell us what you requirements are.  I ran a quick test with the following code using a 320x240 size image, and then again at 640x480:

public Form1()
{
    InitializeComponent();
}

private TimeSpan RunTest( int sampleSize )
{
    var sw = Stopwatch.StartNew();
    var baseImg = new Bitmap( @"C:\TestImage.jpg" );
    Bitmap bmp = null;
    for( int i = 0; i < sampleSize; ++i )
    {
        var rect = picBox.ClientRectangle;
        bmp = new Bitmap( rect.Width, rect.Height );
        using( Graphics g = Graphics.FromImage( bmp ) )
        {
            g.InterpolationMode = InterpolationMode.HighQualityBilinear;
            g.DrawImage( baseImg, rect );
        }

        picBox.Image = bmp;
            // the call to Invalidate() that you have is not needed.
    }

    sw.Stop();
    return TimeSpan.FromMilliseconds( sw.ElapsedMilliseconds );
}

private void picBox_Click( object sender, EventArgs e )
{
    int iterations = 100;
    var time = RunTest( iterations );
    MessageBox.Show( String.Format(
        "Elapsed: {0}, Average: {1}",
        time.TotalMilliseconds,
        time.TotalMilliseconds / iterations ) );
}

I then performed another test using the default InterpolationMode.  Under a release build that gave me the following results:

320x240
1. High quality interpolation: Total: 3122ms, Average: 31.22ms, FPS: 32
2. Default interpolation: Total: 2165ms, Average: 21.65ms, FPS: 46

640x480
1. High quality interpolation: Total: 3963ms, Average: 39.63ms, FPS: 25
2. Default interpolation: Total: 2256ms, Average: 22.56ms, FPS: 44

Are you saying that 32 frames per second is not good enough for your application?  Is 42 ok and is it alright to remove the high quality rendering?  You need to provide more details.  You can't expect us to optimize your code with no target requirement in mind.  Also, as you can see, your claim that the performance is better with large images does not appear to be true, though the difference without high quality bilinear rendering is negligible.

If you can forego the Bilinear interpolation you can simply set the StretchMode of the PictureBox to Stretch and just set the Image property to the Frame property of the event args object and be done with it.  This will be significantly faster.


Immuitable recursive linear search of an array of string

The additional argument index is error prone. For example, a user might provide -1 and you end up with array.[-1]. So let us get rid of that first:

let linearSearch (array: string[]) (target: string) =
    let rec search index =
            match array.Length with
                | l when index >= l -> -1
                | _ ->
                    match array.[index] with
                    | x when x = target -> index
                    | y -> search (index + 1)
    search 0

Now the recursive call is hidden in search, and also the index cannot get negative or otherwise mangled by a user. Next, we can make your linearSearch more general:

let linearSearch (array: 'a[]) (target: 'a) =
    let rec search index =
            match array.Length with
                | l when index >= l -> -1
                | _ ->
                    match array.[index] with
                    | x when x = target -> index
                    | y -> search (index + 1)
    search 0

After all it should work for anything we can compare with =. Talking about comparing something, your pattern matches aren't really matching anything. You're just checking whether a condition has been met. Use usual structures instead:

let linearSearch (array: 'a[]) (target: 'a) =
    let rec search index =
            if index >= array.Length then
              -1
            elif target = array.[index] then
              index
            else
              search (index + 1)
    search 0

And last but not least, I would use the same promises as the usual C#/F# functions: either throw an exception when the value has not been found, or return an Option. That way, if we got an int, it's valid, so we don't have to check for an invalid position. I've choosed option:

let linearSearch (array: 'a[]) (target: 'a) =
    let rec search index =
            if index >= array.Length then
              None
            elif target = array.[index] then
              Some index
            else
              search (index + 1)
    search 0

But that's up to you.

Exercise

Write a function linearFind that uses a function to find the correct index:

linearFind (array : 'a[]) (predicate: a' -> bool) = …

If linearFind returns Some index, then predicate array.[index] should be true.
Express linearSearch in terms of linearFind.


A good place to start is to break your big main method into smaller chunks of work. Then you can focus on improving the code in each section.

Currently your main method does many things, it reads user input, builds up a song and writes it to a file. Here's how you might rewrite it:

def main():
  num_bottles = get_num_bottles_from_user()
  hue = get_hue_from_user()
  song = build_song(num_bottles, hue)
  out_filename = create_out_filename(num_bottles, hue)
  write_song_to_file(song, out_filename)

The function is easier to read if all the calls it makes are at a similar level of abstraction. The main method doesn't do low level operations like input reading or file writing, it tells a story.


Let's look at tableView:cellForRowAtIndexPath:.  This needs to be abstracted quite a bit more.
First of all, CustomTableViewCell is a bad name for a class.  Every table view cell is custom.  We need to spend more time working on our cell subclass, because the name is just the start.
Let's change our cell.  Instead of exposing our UI elements, we should create a property for a PFUser and a delegate.  We also need to create an enum in our cell's header to send to our delegate, and a protocol for our delegate to conform to.
Enum:
typedef NS_ENUM(NSInteger, MyUserCellAction) {
    MyUserCellActionCheckUser,
    MyUserCellActionPerformSegue
};

Of course, this needs more accurate, more descriptive names, but only you know what your app does, so be sure to pick some really good names.  It shouldn't be "PerformSegue", but should be whatever action is the reason we're performing the segue... are we logging in?
Protocol:
@protocol MyUserCellDelegate <NSObject>

@optional - (void)myUser:(PFUser *)user didPerformAction:(MyUserCellAction)action;

@end

Again, this needs slightly better naming, because the class shouldn't be called "MyUserCell".  We need a name that is more descriptive, but the protocol method should be something about like this.  An optional method which passes back the user for which this action is being performed, and the action out of the enum we just defined.
@interface:
@interface MyUserCell : UITableViewCell

@property (weak) id<MyUserCellDelegate> delegate;
@property PFUser *user;

@end

And we might have other properties in here, but importantly, we should be exposing the UI elements like the buttons or various text boxes.  The cell should take care of setting up its own view.
Whenever the user property is set, we should set up the dynamic parts of our UI (the labels).
- (void)setUser:(PFUser *)user {
    _user = user;
    // setup UI
}

Our cell's button should already be tied to an IBAction within the cell.  Either we set the cell up in an interface builder and link it from there, or we create it entirely programmatically and add the action in init.
- (IBAction)buttonTapped:(id)sender {
    // cell handles its button being tapped
}

Here, we can preset our action sheet.
In one handler block, we'll put the following snippet:
if ([self.delegate respondsToSelector:@selector(myUser:didPerformAction:)]) {
    [self.delegate myUser:self.user didPerformAction:MyUserCellActionCheckUser];
}

And in the other, this snippet:
if ([self.delegate respondsToSelector:@selector(myUser:didPerformAction:)]) {
    [self.delegate myUser:self.user didPerformAction:MyUserCellActionPerformSegue];
}

Now, all that's left is setting something up as the delegate.
In the .h file with the @interface section, we need to declare the object as conforming to the protocol:
@interface MyDelegateClassViewController : UIViewControll <MyUserCellDelegate>

And do all of our normal stuff, but then in the .m file, we need to include the following method if we wish to handle the action of the button being pressed:
- (void)myUser:(PFUser *)user didPerformAction:(MyUserCellAction)action {
    if (action == MyUserCellActionCheckUser) {
        // do what we want
    } else if (action == MyUserCellActionPerformSegue) {
        // do the other thing we want
    }
}

And now, our cell and table and view controller aren't so tightly coupled.  If we want to add more actions, we can do that.  If we want to add some actions that might just update the PFUser object, the cell can handle that without calling to the delegate.  If we want to use a different delegate for our even number cells than for our odd number cells, we can do that and easily get different actions despite the same set of buttons.


Missing header

Include <cstring> to get a definition of std::memset (and add the missing namespace qualifier where you use it).

Unused headers

We're not using <bitset>, <fstream> or <string>.

Prefer C++ headers

Use <cmath> in preference to <math.h> for new code, to place the identifiers into the std namespace (the only identifier that needs updating where it's used is std::sqrt).

Non-standard headers

Instead of platform-specific headers, you can use Standard C++ <chrono> for timing the code:

#include <chrono>

int main()
{
    auto const starttime = std::chrono::high_resolution_clock::now();

    do_work();

    auto const endtime = std::chrono::high_resolution_clock::now();

    auto const time_in_ms =
        std::chrono::duration_cast<std::chrono::milliseconds>(endtime - starttime);

    std::cout << "Time taken:  "
              << time_in_ms.count() << " ms\n";
}

Unused variable

We never use totalMemset - leaving it in makes your code look like it's not really ready for review.

Use unsigned types

Most of the numbers used in this program are necessarily non-negative.  Prefer unsigned types to make this more apparent (and to give you twice as much range of values).

Prefer constants to preprocessor macros

This is better, as it's strongly typed, and won't be expanded in the wrong context:

const std::size_t RUNS = 10000;

Use * for arithmetic, not <<

An optimising compiler should generate the same code for

int j = (i << 1)*i + (i << 2) + (i << 1) + 3;

as for

int j = 2*i*i + 4*i + 2*i + 3;

The latter more clearly conveys your intent (and you could collect 4*i + 2*i to simply 6*i).  Don't attempt to micro-optimize this!

Prefer range-based for

Instead of counting elements like this:

int count;
for (int i = 0; i<R2; i++) if (primes[i] == 0) count++;

Here's a simpler form:

std::size_t count = 0;
for (auto n: primes)
    count += !n;


list comprehensions aren't too useful in that code. Well, I think I can help improve your code anyway:

valuePerWeight = sorted([[values[i] / weights[i], weights[i]] for i in range(numItems)], reverse=True)

is overcomplicated instead of the index and range. Use zip instead, which is faster and cleaner:

valuePerWeight = sorted([[v / w, w] for v,w in zip(values,weights)], reverse=True)

Same there: not very pythonic to work with indexes when you can use enumerate:

for i in range(numItems):
    if valuePerWeight[i][1] > 0 and maxi < valuePerWeight[i][0]:
        maxi = valuePerWeight[i][0]
        idx = i

could be:

for i,item in enumerate(valuePerWeight):
    if item [1] > 0 and maxi < item [0]:
        maxi = item [0]
        idx = i

clearer and faster right? and after having found idx you could save a lot of access-by-index time by creating:

v = valuePerWeight[idx][0]
w = valuePerWeight[idx][1]

and refer to v and w in the rest of the code: clearer and faster (double access by index is costly cpu-wise)

Last item: you're dividing and multiplying by the same value. Since they're float operations, you could simplfy:

if valuePerWeight[idx][1] > 0:
    value += (capacity / valuePerWeight[idx][1]) * valuePerWeight[idx][1] * valuePerWeight[idx][0]
    return value

by (using v and w as instructed above)

if w > 0:
    value += capacity * v
    return value

Also, you don't need numItems at all now. Just turn the while loop as:

while capacity > 0 and valuePerWeight:

(when valuePerWeight is empty, the loop ends)

So to sum it all up, here's my proposal for an improved code of yours:

def get_optimal_value(capacity, weights, values):
    value = 0.

    valuePerWeight = valuePerWeight = sorted([[v / w, w] for v,w in zip(values,weights)], reverse=True)
    while capacity > 0 and valuePerWeight:
        maxi = 0
        idx = None
        for i,item in enumerate(valuePerWeight):
            if item [1] > 0 and maxi < item [0]:
                maxi = item [0]
                idx = i

        if idx is None:
            return 0.

        v = valuePerWeight[idx][0]
        w = valuePerWeight[idx][1]

        if w <= capacity:
            value += v*w
            capacity -= w
        else:
            if w > 0:
                value += capacity * v
                return value
        valuePerWeight.pop(idx)

    return value

if __name__ == "__main__":
    n = 3
    capacity = 50
    values = [60, 100, 120]
    weights = [20, 50, 30]
    opt_value = get_optimal_value(capacity, weights, values)
    print("{:.10f}".format(opt_value)) # print 180.0000000000

tested and stil returns 180.0, fortunately.


Python - Split nth occurence of a character in string

A python idiom for iterating over a sequence in groups it to use zip() like so:

group_iter = zip(*[iter(seq)]*n)

where seq is the sequence and n is the size of each group. Note that the last group will be dropped if it doesn't have n elements.

Using that idiom, your function could be coded:

def nthofchar(string: str, char: str, n: int = 2) -> list:
    chunks = string.split(char)
    groups = zip(*[iter(chunks)]*n)

    return [char.join(group) for group in groups]

Added a test case for n != 2:

print(nthofchar("1;a;b;2;c;d;3;e;f;4;g;h;5;i;j;6;k;l", ";", 3))
# Output: ['1;a;b', '2;c;d', '3;e;f', '4;g;h', '5;i;j', '6;k;l']


For the second point, since it's easier, typing has an Any:

from typing import List, Any
. . ., variables: List[Any], . . .

For the first, you're just doing a reduction over variables:

from typing import List, Any
from functools import reduce

def format_string(string: str, variables: List[Any]) -> str:
    return reduce(lambda s, val: s.replace("[*]", str(val), 1), variables, string)

Although really, in a real use case, I'd still split this over three lines for clarity:

def format_string(string: str, variables: List[Any]) -> str:
    return reduce(lambda s, val: s.replace("[*]", str(val), 1),
                  variables,
                  string)

And honestly, I might just make that function var-arg instead of grouping things in a list to make it consistent with other format functions:

def format_string(string: str, *variables: Any) -> str:
    return reduce(lambda s, val: s.replace("[*]", str(val), 1), variables, string)

>>> format_string("[*] Hello [*]", 1, 2)
'1 Hello 2'

Note that when annotating a a var-arg parameter, you annotate the type of each element and ignore the type of the wrapping container (a tuple iirc). That means it's *variables: Any, not *variables: Tuple[... Any].

Of course though, whether or not this is better is a matter of taste, but this is the ideal use-case for reduce. Whenever you want to constantly reassign one thing in a simple loop, reduce is likely a good tool to look at.


Adjusting dates in an array based on a start date

var items = booking.ActiveItems(); // each item has check-in and/or check-out dates

var offset = items[0].GetCheckInDate().Date - DateTime.Parse("2017-05-12");

foreach(var item in items)
{
   item.SetCheckInDate(item.GetCheckInDate() - offset);
   item.SetCheckOutDate(item.GetCheckOutDate() - offset);
}

That, however would not account for e.g. holidays, weekends, availability

And the only reason to do iterative adjustmens (as in original code) would be if SetDate would automatically make adjustments to holidays/weekends inside.

In this case original code lacks comments around that area explaining that SetDate might change the date by itself and absolute day offset would change.


The main performance issue is the blocking nature of your script. You don't process the next url until you are done with the current. Think of using asynchronous tools like Scrapy web-scraping framework which is based on twisted; or something like grequests.

Other notes:

if you would stick to synchronous approach, switch to requests, initialize a session (requests.Session) once and reuse - this should be faster than using urllib.request
when you generate HTML files, pre-define a template with placeholders, render the template on the fly filling up the placeholders. You may use a template engine like mako or Jinja2, or use the built-in str.format()
it also looks like you are reopening each of the generated files twice - once for the initial write in the w+ mode and then to append in a mode


Optimize insertion from ArrayList to HashMap

The Language class needs the "addItem()" method that combines incrementing numberItems and adding to the Items collection. The design intent here would be to hide the implementation details of adding an item.

The Language class needs a constructor for the first item added.
 Language language = new Language(item);

The languages map should be a specialization class of the HashMap, with its "add(item)" method to hide details of the new/existing item logic.


Model-View-Controller-Service shared flat expenses interface

Here is a start

I opened your code in php storm and it says
Non-static method Database::getPdo() should not be called statically

Where you have code like this

public function deleteAction()
{
    $id = $_REQUEST['debt_id'];
    if (UserService::isLogged()) {
        if (DebtService::getPaidByFromId($id) == UserService::getCurrentUserId() or UserService::isAdmin()) {
            DebtService::deleteById($id);
            return DebtController::listAction();
        } else {
            RedirectService::goHome();
        }
    } else {
        RedirectService::goHome();
    }
}

I prefer to have a guard clause at the top, so you can easily see the outcome of the if/else without having to scroll to the end of the code

public function deleteAction()
{
    if (!UserService::isLogged()) {
        RedirectService::goHome();
    }

    // TODO what if debt_id doesn't exist, always check isset()
    $id = $_REQUEST['debt_id'];

    if (DebtService::getPaidByFromId($id) == UserService::getCurrentUserId() or UserService::isAdmin()) {
        DebtService::deleteById($id);
        return DebtController::listAction();
    } else {
        RedirectService::goHome();
    }
}

Instead of this

$includes = array("controllers", "services", "models");

foreach ($includes as $dir) {
    foreach (glob("../" . $dir . "/*.php") as $file) {
        require $file;
    }
}

you might want to look at autoloading, it's not very hard to do
http://php.net/manual/en/function.spl-autoload-register.php

In your templates you are doing

<?php echo $debt->getDescription(); ?>

Unless you know for sure there is no html or user editable content,
you should really html escape it

<?php echo htmlentities($debt->getDescription()); ?>

Database service, take the config out of the service, and store it in a config file. otherwise you need to edit the code when you deploy to a different server.

Would a join work better here

// DebtService::getDebtsForMonth

SELECT date, amount, name AS description, paid_by, id, user_id
            FROM debts
JOIN debtors ON debts.id=debtors.debt_id
WHERE MONTH(date) = ? and YEAR(date) = ? ORDER BY date

You may need to use exit; here. setting the location doesn't stop the code from running

public static function goToURI($uri_suffix)
{
    header("Location:" . uri_prefix . $uri_suffix);
    exit;
}

It is not essential but I like to keep all my defines in uppercase

define('URI_PREFIX', "/coloc-web");

That should be enough to get your going for now.


Windows application that draws India's flag

Thanks to your method IndiaFlag, I guess you're drawing a flag of India. The problem is, I don't know what it looks like. OK, I gonna google it.

It consists of 3 stripes: orange, white and green (top to bottom) and a sort of a wheel in the center. So, why don't you just say:

int const width = ...
int const height = ...
int const stripeHeight = height / 3;

drawStripe(0, 0, width, stripeHeight, Orange);
drawStripe(0, stripeHeight, width, 2 * stripeHeight, White);
drawStripe(0, 2 * stripeHeight, width, 3 * stripeHeight, Green);
drawWheel(width / 2, height / 2)

?

This code describes what your're drawing in fact. There are no brushes or pencils here, because if I ask you what the flag looks like, for sure you're not going to tell me about pencils and brushes and how GDI works. You'll probably say there are 3 stripes and a wheel in the center and that's what I want to hear.

So, why do you write the code like you're not going to tell anyone what happens in there?

Looking at your code, I'd say that all the names you give are terrible:

CBrush brush(RGB(255,255,255));

What does it mean? You're only going to have a single brush, so that's why you call it a "brush"? Nothing specific about it? If I see a name brush 20 lines later, do you expect me to remember it is white or any specific at all?

CBrush *oldBrush = dc.SelectObject(&brush);

An old brush? When I see oldBrush 20 lines later, do you expect me to remember what this brush is? Do YOU know why you need this oldBrush? I see no code where you switch back to it, so why do you even do it?

    dc.Rectangle(x,(y+50),(x+200),(y+100));

What is x here? Why y+50? What is 500? What is 200?

    CPen pen2(PS_SOLID, 1,RGB(0,0,255));

And once again, something called pen2. Is this pen any specific, or you're just telling me you're using 2 pens? Should I care? Etc.

P.S. Procedures/Functions/Methods describe actions, so their names are traditionally DoWhat. Your IndiaFlag violates the principle, because it says What.


You are on the right track, but there is some hidden complexity and repetition:

if ($this->rewrite == 1) {
    // ...
} else {
    // ...
}

The if statement above is peppered all throughout your code. You actually have a need one base class Url and two child classes that specialized in the different routing strategies. First, you'll want the Url class to be abstract, and specify all the methods that return URLs to be abstract as well. The one thing both routing strategies share in common is the domain name, which should be a private field with a protected getter to enforce encapsulation.

Lastly, you see a static method called create which chooses which concrete instance to return based on environmental variables.

abstract class Url {
    private $domain;

    public function __construct($domain) {
        $this->domain = $domain;
    }

    public abstract function home();
    public abstract function page($page);
    public abstract function manufacter($slug);
    public abstract function product($slug, $manufacter);
    public abstract function category($slug);

    protected function getDomain() {
        return $this->domain;
    }

    public static function create(): Url {
        if (SITE_REWRITE) {
            return new SearchEngineFriendlyUrl(SITE_URL);
        }

        return new PhpFileUrl(SITE_URL);
    }
}

Now you need one concrete class for each routing strategy:

class PhpFileUrl extends Url {
    public function home() {
        // ...
    }

    public function page($page) {
        // ...
    }

    public function manufacter($slug) {
        // ...
    }

    public function product($slug, $manufacter) {
        // ...
    }

    public function category($slug) {
        // ...
    }
}

class SearchEngineFriendlyUrl extends Url {
    public function home() {
        // ...
    }

    public function page($page) {
        // ...
    }

    public function manufacter($slug) {
        // ...
    }

    public function product($slug, $manufacter) {
        // ...
    }

    public function category($slug) {
        // ...
    }
}

Once you have this, you no longer need IF statements anywhere:

class PhpFileUrl extends Url {
    public function page($page) {
        return $this->getDomain() . '/' . $page . '.php';
    }
}

class SearchEngineFriendlyUrl extends Url {
    public function page($page) {
        return $this->getDomain() . '/' . $page . '.html';
    }
}

Each class becomes very clean and easy to understand. Furthermore, if your SEO friendly URLs change, you need only change the one class without affecting the other, which reduces your testing effort.

Remember that every branch in your code (think if statement and switchs) is another path to failure, and therefore another path you must test... in each method the branch exists.

Now, using this is just as easy as before, but gives you a more maintainable solution:

$url = Url::create();

echo $url->page('about');


Try parallelization. Instead of:

foreach (DirectoryInfo di in subDirs)
{
    WalkDirectoryTree(di, searchname);
}

Do

Parallel.ForEach(subDirs, dir => WalkDirectoryTree(dir, searchname));

Notice that by doing this allFiles will be accessed concurrently so change your collection to a ConcurrentBag.


Displaying a list of attributes and differentiate them from attributes already selected

Generally speaking, I'd avoid relying heavily on function calls if speed is important. Specifically:

_.map(attibutes.metric, function (m)

If attibutes.metric is an array I'd do

var i = attibutes.metric.length;
while(i--) {
/* your code here */
}

or

var i, length = attibutes.metric.length;
for (i = 0; i < length; i++) {
/* your code here */
}

depending on the engine, the while loop will be faster than the for or vice-versa.

if attibutes.metric is an object I'd do

keys = Object.keys(attibutes.metric);
for (var key in keys) {
/* your code here */
}

Any of those constructs is probably faster than calling _.map (you should still profile it, YMMV).

second, i'd invert

if (_.isObject(m.attrData) {

if the alternative is m.attrData is a primitive type, so

if (typeof m.attrData === 'string') { // replace string with whatever primitive
    attr.value = _.values(m.attrData)[0];
} else {
    operator = _.keys(m.attrData)[0];
    if (operator !== "in") {
        attr.operator = operator;
    }
    attr.value = m.attrData;
}


There's a couple of things I'd recommend you change about your current code, and there's an alternative to your using a closure's use construct to pass in other variables.

The first thing I'd do, is to change your function's signatures to type-hint the expected types for each argument, ie change the transaction function to look something more like this:

function transaction(PDO $conn, callable $closure)
{}

Optionally, replacing the callable type-hint with Closure. The upside of callable is that old-school callable constructs will be accepted, too (array($object, 'someMethod') or even ucfirst), the downside is, of course that functions like ucfirst are accepted, but clearly not a valid function in this context.

Anyway, apart from using use to pass in additional variables, you could add a third argument to the transaction function, and type-hint an array:

function transaction(PDO $conn, callable $closure, array $arguments = [])
{}

Then, simply invoke the $closure argument using call_user_func_array to pass the arguments that need to be passed:

array_unshift($conn, $arguments);//prepend $conn to the arguments
call_user_func_array($closure, $arguments);

And you're there... Of course, if you find that array_unshift call clumsy looking (which it kind of is), you can just assume the $arguments array to contain the PDO connection from the off, in which case:

function transaction(callable $callback, array $arguments)
{
    if (!$arguments[0] instanceof PDO) {
        throw new InvalidArgumentException('arguments should contain PDO instance');
    }
    $conn = $arguments[0];
    try {
        $conn->beginTransaction();
        call_user_func_array($callback, $arguments);
        $conn->commit();
    } catch (Exception $e) {
        $conn->rollBack();
        throw $e;
    }
}

Again, there is a downside to this approach, the main disadvantages, IMO, are:

Overhead (a PHP closure is syntactic sugar, it's actually creating a new instance of the Closure class.
The $arguments array will often be a bit too complex for its own good, leaving you with code that actually calls your transaction function to decide on the actual logic -> every call can look different, and often will contain SQL strings, fetch calls and the like. Ugly code is harder to maintain...
Like you said: the stack trace looses some of its relevance, making debugging harder.

The last two issues (code that is harder to maintain + harder to debug) are, to me, severe problems, so much so, that I'd recommend not to use the transaction function, but instead write the try-catch blocks where and when I need them.


External data

Most of your test cases are expected that some records already exist. The details of these records are not visible in the class, which makes them an external dependency. It also makes the test cases harder to understand.

A simple fix is to add the necessary test data in the test cases, or in the @Before method.

Make assumptions explicit

Some of the test cases are hard to understand because they make assumptions that are not exactly obvious, for example:

@Test
public void create_ExistingNameDifferentCountry_Created(){
    CountryEntity countryEntity = countryDao.find(2L);

    CityEntity cityEntity = new CityEntity();
    cityEntity.setName("Bratislava");
    cityEntity.setCountryEntity(countryEntity);

    cityDao.create(cityEntity);

    Assert.assertNotNull("Expected not null value.", cityDao.find(cityEntity.getId()));
}

Here, I suppose you are testing that you can create a city with the same name in a different country. This test case seems to make some assumptions:

There is no city named Bratislava in the Country with id=2
There is a city name Bratislava in some other Country

It's better to make these assumptions part of the code, for example:

private CountryEntity createNewCountry() {
    // TODO: create a new unique country (different from all existing)
}

@Test
public void create_ExistingNameDifferentCountry_Created(){
    CountryEntity someCountry = createNewCountry();
    createCity("Bratislava", someCountry);

    CountryEntity anotherCountry = createNewCountry();

    CityEntity cityEntity = new CityEntity();
    cityEntity.setName("Bratislava");
    cityEntity.setCountryEntity(anotherCountry);

    cityDao.create(cityEntity);

    Assert.assertNotNull("Expected not null value.", cityDao.find(cityEntity.getId()));
}

There are no more meaningless numbers (such as 2L) in this test case, and the assumptions are loud and clear.

Another similar example:

@Test
public void update_ExistingNameSameCountry_ExceptionThrown(){
    exception.expect(ConstraintViolationException.class);

    CityEntity cityEntity = cityDao.find(2L);
    cityEntity.setName("Bratislava");

    cityDao.update(cityEntity);
    cityDao.flush();
}

This test case seems to assume that the city with id=2 is named Bratislava. Consider this instead:

@Test
public void update_ExistingNameSameCountry_ExceptionThrown(){
    exception.expect(ConstraintViolationException.class);

    CityEntity cityEntity = cityDao.findSomeCity();
    cityEntity.setName(cityEntity.getName());

    cityDao.update(cityEntity);
    cityDao.flush();
}

No more hidden assumptions and invisible external data. The city can be any city, if you try to create a new city with the same name as the sample city, the method should throw.

Many of your other methods suffer from the same problem. Review them and ask yourself if there are any assumptions that are not written inside the method itself, and make them explicit.

Covering all corners

Some of your test cases could be more strict, for example:

In create_Created, in addition to checking that you can load the new entry that was created, you could check that:

the number of entries in the database got increased by 1
Assert.assertEquals(cityEntity, cityDao.find(cityEntity.getId()))

Similarly in create_ExistingNameDifferentCountry_Created

Expected exceptions

Have you considered this instead of the @Rule for expected exceptions:

@Test(expected=ConstraintViolationException.class)
public void create_NoCountryAssociation_ExceptionThrown(){
    // ...
}

Personally I find this more readable. @Rule is more powerful, because it can match exception messages too, but you're not using that feature anyway. This may be a matter of taste.

Naming

I think your test case names could be more intuitive, for example:

create_city_with_country_works instead of create_Created
create_city_without_country_throws instead of NoCountryAssociation_ExceptionThrown
...

As for camelCase vs underscores vs mixed vs something else, I think it doesn't matter. You can use what you like best. The general naming rules probably don't apply to the test cases the same way as to regular code. Test case names should be specific, identify what is being tested, and as such they tend to be very long.

For example, underscores are very similar to spaces, so create_city_without_country_throws is just a little bit harder to read than a sentence. In  createCityWithoutCountryThrows there is no visual separation between the words, which makes it much harder to read than a sentence. At least this is my opinion.

The bottom line is, use whatever naming is agreed in your team, or else whatever naming is more readable to you.


First, some comments on the UI:

The word is t e s t * n *
What is your guess? g
You got one right! no hangman for you this turn

The word is t e s t * n g
What is your guess? i
You guessed it right before getting a hangman! You win!
The word was testing

You need to do a better job separating the "game board" from the verbiage. Also, maybe put some quotes and other punctuation around the printed answer:

The word was, "testing"!

Now for the code. I'm not going to do a complete review because ... it makes my eyes burn. Instead, I'm going to assume that:

You're coming to python from C or C# or Java - some language with array support and lots of curly braces.
You're in a course, and being deliberately held back.

So let's look at your coding style:

import random
print('let\'s play hangman')
#set words
first = ['t','e','s','t']
second = ['t', 'e', 's', 't', 'e', 'd']
third = ['t', 'e', 's', 't', 'i', 'n', 'g']
fourth = ['r', 'a', 'n', 'd', 'o', 'm']
fifth = ['g',  'e',  'n',  'e',  'r',  'a',  't',  'e']
#set list of possible answers
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
#set a couple of varibles

Use vertical space to separate unrelated things

You didn't separate things using vertical space. This is perhaps the greatest sin in programming. Always, always use vertical space (blank lines, paragraphs, etc.) to separate parts of your code. If you switch from doing one thing to another, insert a blank line. If you end a paragraph and start a new paragraph, insert a blank line. If you come to the end of a function or a loop, insert a blank line.

Even if you are the most secretive hacker ever, and you never intend to share your code with a single other living human being, at some point you will have to go back and read stuff that you, yourself wrote six months earlier! Make it easy on yourself, or on whatever other humans have to read your code: try to make it easy to read! Use vertical space to separate unrelated things.

Keep related things together

Next, consider the line:

print('let\'s play hangman')

Ignoring the lack of a leading capital letter, and no ending punctuation, why is this line where it is?

This is clearly the "start of the game." That's fine. But at line #2, you aren't ready to start the game. There's a bunch of variable initialization and other things that need to happen before the game starts. This line should be moved down to where all the rest of the user-facing code is located. Keep related things together.

Let your code speak for itself

Your comments suck.

There are six basic questions you can answer: Who, What, Where, When, Why, and How?

Of those, three are only used in intro-to-programming courses: Who, Where, When. If you have to put a big header block at the top of your program with your student id, name, course number, professor's name, etc., that's okay. Just do it once, and we will all skip right over it!

The other three- What, Why, and How- should only be used if you can't actually answer the question with the code itself!

Specifically, if you can't choose your variable, type, and subroutine names in such a way as to make the answer obvious.

If you can make the answer obvious, then don't add a comment. It just wastes my time, and annoys the compiler.

To wit:

#set varible length to the number of letters in the word
length = len(words)

First, you misspelled "variable." But second: how could you possibly think this comment adds value to your source code?

There are some occasions when you need to answer the question "What?" But those occasions are few and far between. You're actually better off never answering that question unless somebody calls you on it. Until and unless someone asks you "what is this code doing?" I would suggest you simply never use a comment to explain what you are doing - because at the "learning" stage, it is almost always obvious.

You might explain "why" you're computing some value, or "how" you're doing a computation. But, again, for the most part these things are obvious.

Now consider your variable, words:

first = ['t','e','s','t']

# ...
random=random.randint(1, 5)
if random == 1: words = first

Apparently, words is actually the secret word the player is trying to guess. Which is fine, except the whole program is about words, and words is plural - suggesting perhaps a list of words or a dictionary of words or a disk file containing more than one actual word!

This variable is the most important piece of data in your program, and you named it wrong. Maybe secret_word instead? (Because answer is taken.)

There are very few beginner programs that need comments. But there are often programs that need better variable or function names. Let your code speak for itself.

K.I.S.S.

Consider this:

for loop in range(length):
    end = end + loop

# ...

while wrong < 5 and endCheck != end:

    # ...

    for marker2 in range(length):
        if words[marker2] == letter:
            # ...
            endCheck = endCheck + marker2

This is "interesting" because it appears that you determine that the player has won the game by adding up the index of all the correctly guessed letters, 0 + 1 + 2 + 3 + 4 ... and matching the sum against a pre-computed value.

This is so bizarre that I wonder if you copied your solution from a different language. Perhaps in C, or Pascal, or assembly, or just any language with bad string support? Also, of course, it won't work: you start with zero, and you use 0 as the index of the first character. This is a bug.

The word is * e n e r a * e
What is your guess? t
You guessed it right before getting a hangman! You win!
The word was *enerate

Ignoring the whole "it doesn't work" thing, this solution is vulnerable to all sorts of programmer errors, and it is not at all obvious what you're doing.

A far better test for "done" would be simple equality: is A equal to B? It turns out that Python implements list equality correctly. You can simply say,

if listA == listB:

and get the correct result. Alternatively, you could store your words as strings rather than lists. This would make it somewhat awkward to manipulate them, since Python strings are immutable. But it would again let you simply say,

if wordA == wordB:

or even,

while wordA != wordB:

and have a simple, obvious operation for checking if the player has won.
As the saying goes, "keep it simple stupid."

A place for everything...

Most of your code is inside a while loop. But much of your code doesn't get executed more than once!

Consider this:

#check if entire word has been guessed
if endCheck == end:
    print('You guessed it right before getting a hangman! You win!')
    print ('The word was ', end = '')
    for word in range(length):
        print(answer[word], end='')
#check if a right letter was guessed this turn
if right > 0 and endCheck != end:
        print('You got one right! no hangman for you this turn')
#check if a wrong letter was guessed this turn
if right == 0:
    print('You missed it this turn!')
    wrong = wrong + 1
    print ('number missed =',  wrong)
#check if to many wrong guesses were made
if wrong == 5:
    print('You got a hangman!')

That code is a mixture of "things to do at the end of the game" and "things to do in a loop."

Mixing things like that is a mistake. First, because it requires you to check your conditions over and over (which is inefficient). And second because you are flipping back and forth: he's in! he's out! he's in! he's out! This is unnecessary complexity (violating the KISS principle), and it doesn't keep related things together.

Instead of jumbling all these conditions together, ask yourself: what things go inside the loop, and what things go outside the loop?

Obviously, winning or losing the game is "outside the loop" because in either case you won't be asking for any more guesses.

Similarly, reporting if a single guess was right or wrong is inside the loop, because then you will ask for more guesses.

Consider using the break or the continue statement to short-circuit the rest of the loop body. Like this:

while True:
    # guess, etc.
    if answer == secret_word or wrong_guesses == 5:
        break

if answer == secret_word:
    # you win
else:
    # you lose

Identify the various conditions, and then have "A place for everything, and everything in its place!"

I'm not going to address the places where your code is not "Pythonic". You've said you're learning, and I believe you. Plus, I expect some other people will chime in for that. There are a lot of things you can do to clean this code up, and to make better use of language features. But I think you should address the "bigger" issues first, because they will still be true even if you aren't programming in Python. Bad comments in C# are still bad comments. Poor variable names in Scheme are still poor variable names.


Drawing a circle with text in it using CSS

Instead going against how the browser naturally renders elements, use it to your advantage.

div.arcs {
    border: 50px solid red;
    display: block;
    min-width: 14em;
    min-height: 14em;
    max-height: 14em;
    max-width: 14em;
    border-radius: 50%;
    border-top-color: rgb(109, 176, 65);
    border-bottom-color: rgb(167, 167, 167);
    border-left-color: rgb(255, 199, 45);
    border-right-color: rgb(104, 162, 219);
    box-shadow: 0 0 20px 5px #a0a0a0;
    position:relative; /*changed*/
}

div.arcs > div {
    font-family: Calibri;
    font-size: 20pt;
    text-align: center;
    text-shadow: 1px 1px 3px #000000;
    color: #e0e0e0;
    position: absolute; /*changed*/
    width: 100%; /*changed*/
    height: 1.5em;
    line-height: 1.35em;
}

div.arcs > div:hover {
    text-decoration: underline;
    cursor: pointer;
}

div.arcs > div.top {
    top: -45px; /*changed - against the size of the border*/
}

div.arcs > div.left {
    transform: rotate(270deg);
    transform-origin: right top 0;
    /*top:0;
    left:-45px; - remove */
}

div.arcs > div.right {
    transform: rotate(90deg);
    transform-origin: left top 0;
    /*left: 10em;
    top: -3.1em; - remove*/
}

div.arcs > div.bottom {
    bottom: -45px; /*changed - against the size of the border*/
}

Then just swop the two div's around:

Text 1

Text 2

Text 4

Text 3

This will allow you to change the size of the circle without having to adjust everything, however if you change the width of the border, you will need to change the line-height of the div and the bottom and top div absolute positioning, there is no way around that.


The code is good, only a few ignorable pointers :

lowerCamelCase is the standard for JavaScript, so

get_link -> getLink
get_first_p -> getFirstParagraph
readmore -> readMore ?

The code could be more DRY for the retrieval of settings.
I would counter-propose something like this:

    var defaultSettings = {
        sentences_number: 3,
        readMoreText: 'Read more.',
        readMoreToggle_text: 'Read less.',
        readMoreWrapClass: 'readmore_link_wrap',
        readMoreClass: 'readmore_link',
        bidirectional: false
    };

   var settings = $.extend({}, defaultSettings, options);

   return this.each(function(index) {

        var text = $(this),
        var elementSettings = {};

        //Optionally replace settings with per text data attributes
        for( key in defaultSettings )
          elementSettings[key] = text.data( key ) || settings[key];

        //Then you could either
        link = get_link( elementSettings ),
        //Or you could
        link = get_link(elementSettings.readmore_wrap_class,
                        elementSettings.readmore_class,
                        elementSettings.readmore_text);

($('.readmore').length !== 0) && $('.readmore').readmore(); this is a bit too Golfic ( reminds me of code golf ) and has a repeated constant  which should be extracted and part of your readMore object in my mind.
Finally, your commenting is very un-even, one part has a lot, the rest has close to nothing. I'd say that your functions deserve each a /* One liner */.


A simple implementation of a mutable String in C

Unsafe loop

This loop in string_find() is unsafe since it could read past the end of your buffer:

    while (str->data[pos] != c) ++pos;

You should add an additional check like this:

    while (pos < str->length && str->data[pos] != c) ++pos;

Short circuit error conditions

Rather than doing this:

 if (str != NULL) {
     // Rest of function indented
 }

it would be easier to read if you rewrote it like this:

if (str == NULL)
    return NULL;

// Rest of function, not indented

Other things

Your reallocation strategy will lead to \$O(n^2)\$ behavior when appending to long strings.  You might want to double the allocation instead of adding a fixed amount.

You might want to use size_t for your sizes and lengths instead if int, because an int might overflow at 32KB on some platforms.


options={}
# ...
if not options[:types]
  options[:types] = ["mp3", "m4a"]
end

I would initialize options with the default values first, instead of checking whether the option is set afterwards. I.e.

options = {:types => ["mp3", "m4a"]}

options[:types].each{|ext| `find -iname '*.#{ext}' -exec mv {} ./ \\\;`}

This can be done with a glob. For this I'd first change options[:types] to be string (i.e. replace Array with String in the optparse code and use "mp3,m4a" instead of ["mp3", "m4a"] as the default. Then you can use Dir.glob with FileUtils.mv like this:

Dir.glob("**/*.{#{ ext }}") {|f| FileUtils.mv(f, ".")}

  I suspect that I could replace the find calls with native Ruby methods, but I can't see how without complicating it significantly.

For the first one see above. However the second one would indeed be more complicated to replace, so I'd just stick with the find call.

  I also suspect that there's a better way of writing FileUtils.cd("#{origin}/#{target}")

Yes, there is: cd optionally takes a block. When given a block, cd will cd into the given directory, execute the block, and then cd back. So you can get rid of origin and just do

FileUtils.cd(target) do
  ...
end

FileUtils.cd(origin)

Even without using the block version of cd the above line would be completely unnecessary. Changing the directory at the end of a script has no effect. Any cd performed in a process will never affect the parent process.


Nothing in std::char_traits::copy says to return src when count is zero.  Further, we must return a pointer to modifiable char_type, which also precludes returning src.

So I think we should write:

#include <cstring>
#include <string>

struct string_custom_traits : public std::char_traits<char16_t>
{
    static char_type * copy(char_type* dest, const char_type* src, size_t count)
    {
        return (char_type*)std::memcpy(dest, src, count * sizeof *src);
    }

    static char_type *move(char_type* dest, const char_type* src, size_t count)
    {
        return (char_type*)std::memmove(dest, src, count * sizeof *src);
    }
};

I've used the template-provided alias char_type for consistency and in case you want to turn this traits class into a template itself.

Make sure you understand and accept the differences between UCS-2 and UTF-16 if you handle characters outside the BMP.


Passing larger sized data in functions by const &data is a good idea since it does not make a copy. Note that when a parameter is passed by const&, the extra cost dereferencing and fewer opportunities for compile optimizing. You should do this typically when the data is large in size

From your next() function

    int next() {
        int curr_next = next_num;
        num_has_next = Iterator::hasNext();

        if (num_has_next) {
            next_num = Iterator::next();
        }

        return curr_next;
    } ```

What is the use of the if (num_has_next) branch? You are returning a copy of next_num that was copied before any modifications, and since curr_next is not a reference of next_num, any changes to next_num will not effect return curr_next. I think what you might want to do is
int next(){
    next_num = (num_has_next) ? Iterator::next() : NULL;
    return next_num;
}

ternary operators
Since @hjpotter92 has mentioned it,  calling next() or peek() on the last element should return NULL.

Have a look at templates in C++ if you want to work with multiple types.


Firstly, your code is buggy. You take a day argument, but you never use it for anything. You always return mondays.

But worse, you're incrementing dates like so:

new Date(today.getFullYear(), today.getMonth(), today.getDay()+x);

Spot the error? You're passing getDay()+x as the date argument. But getDay() returns the weekday number (0-6) - not the day-in-month.

So today, Thursday the 5th of November 20151, you're in effect saying:

new Date(2015, 10, 4 + x);

The year's correct, and the month's correct (January is zero), but the date is 1 day off. Thursday is day #4 in the 0-6 weekday scheme - but really, today's the 5th of November.

So if you were to run this on the, say, the 30th of November, you'd actually be using the 1st of November as your start date, since the 30th's a Monday. If you run it on a Sunday, getDay will return zero, meaning your start date will be the last of the previous month. And so on.

I also have to wonder why you've created a function, which builds an array just to hold a list of incrementing numbers, which you then map to dates. The simpler way of looping through incrementing numbers is a plain old for-loop.

Anyway, while calendars are complex, there's one thing that thankfully doesn't change: There are 7 days in a week. So you're creating 7 times more dates than you need, and filtering most of them away. You could consider simply skipping 7 dates at a time from the first occurrence.

Edit: The only thing in the above paragraph that holds true is that calendars are complex. As RobH points out in the comments, some pacific nations have been known to jump across the dateline. Presumably just to mess with programmers the world over!

Thirdly, don't mix calendar dates and raw time calculations like your division by milliseconds in a day. Switching back and forth between daylight savings time (aka winter/summer time) can cause all sorts of nonsense when mixing raw time and dates. Some calendar days are 25 hours long, some are 23. And since a date constructed from only year, month, and date sets its time to midnight, you risk skipping over a date, or repeating the same date twice.

Anyway, here's a simple solution that adds 1 day at a time until the year rolls over, storing dates that match what you're looking for:

function remainingDays(weekday) {
  var current = new Date,
      year = current.getFullYear(),
      dates = [];

  // a simple helper function
  function nextDay(date) {
    return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
  }

  // as long we're in the same year, keep adding 1 day,
  // and store the ones that match the weekday we're looking for
  while(current.getFullYear() === year) {
    if(current.getDay() === weekday) {
      dates.push(current);
    }
    current = nextDay(current);
  }

  return dates;
}

No need to build ranges, map, and filter them. Just a while loop and push.

Incidentally, if you want to learn more about why programming calendar and time things are just hideously complex, check out this video on youtube

1) Happy Guy Fawkes day everyone


A few remarks:

You can do the .lower() one time by using woord = input().lower()
You could check if they are in alphabetic order by keeping track of the    previous one like this:

previouschar=''
for s in ('aaa', 'bbb', 'ddd', 'efe', 'geg'):
    if previouschar != '' and ord(s[0]) != ord(previouschar) + 1:
        print('Out of order')
    previouschar = s[0]


Exporting information on a collection of books to Excel

I think your code is perfectly understandable as it is.

Here's an idea though. (In case it is not clear: the suggestions here are more for amusement and edification than a serious suggestion. The original procedural code is just fine, but it is interesting to see how it might be done in a functional style.)

var funcs = new List<Func<BookInfo, object>>()
{
    info=>info.BookId,
    info=>info.Book,
    info=>info.System // etc.
}
int rowIndex = 2;
foreach (BookInfo bookInfo in books)
{
    int columnIndex = 1;
    foreach(var func in funcs)
    {
        excelExport.SetCell(columnIndex, rowIndex, func(bookInfo));
        columnIndex += 1;
    }
    rowIndex += 1;
}

However, this still has a disappointingly large number of variable mutations. Why do we need to have local variables to track the rows and columns at all? That's the inelegant part that you want to eliminate.

  Can't tell if trolling...or just addicted to lambdas

Oh, we're just getting started here. I have barely yet even begun to use lambdas. How about this?

var funcs = new List<Func<BookInfo, object>>()
{
    info=>info.BookId,
    info=>info.Book,
    info=>info.System // etc.
}
var cells = bookInfos.SelectMany(
  (bookInfo, row)=>
    funcs.Select(
      (func, col)=>
        new {row, col, item = func(bookInfo)}));
foreach(var cell in cells)
    excel.SetCell(cell.col, cell.row, cell.item);

There, now we've got a selector that contains a lambda that contains a selector that contains a lambda that iterates over a list of lambdas. We've also gotten rid of every index mutation.

That of course has far too many explanatory local variables. We should be able to do this without mutating any variable except the loop variable.  Let's eliminate all the variable mutations except one:

foreach(var cell in
  bookInfos.SelectMany(
    (bookInfo, row)=>
      new List<Func<BookInfo, object>>()
      {
        info=>info.BookId,
        info=>info.Book,
        info=>info.System // etc.
      }.Select(
        (func, col)=>
          new {row, col, item = func(bookInfo)})))
  excel.SetCell(cell.col, cell.row, cell.item);

And now we've illustrated the old saying: every programming language eventually resembles Lisp -- badly.

As Scott Rippey points out in his answer, we actually don't need to be capturing the properties as lambdas at all; we could just capture the values:

foreach(var cell in
  bookInfos.SelectMany(
    (bookInfo, row)=>
      new object[]
      {
        bookInfo.BookId,
        bookInfo.Book,
        bookInfo.System // etc.
      }.Select(
        (item, col)=>
          new {row, col, item})))
  excel.SetCell(cell.col, cell.row, cell.item);

Which is actually not too bad.

But like I said, your original code is just fine.


For the time and space complexity, think about how many sentences are possible with:

s = "aaaaaaaaaaa..."
dict = ["a", "aa"]

Any solutation that creates all of these sentences would need to have exponential complexity.

path.append(givenSentence.substring(0, i + 1) + " ");

If you are using a StringBuilder, you should use its append method instead of the '+' operator as it's more efficient.

The index parameter is always 0. This can be removed.

givenSentence.substring(0, i + 1) is used multiple times. You can assign this to a variable and reuse it instead.

if(isSpace == true)

There's no need to compare with true. Just use if(isSpace)

givenSentence.substring(0, i + 2).length()

Calling substring just to get the length of the String is unnessesary. This is the same as i + 2.

The handling of isSpace adds some complexity. There is some code duplication and extra if statements needed. I would try to remove the need for this.

Changing the bounds of the for-loop can remove the need for adding one to i each time it's used.

With these changes, you have something like:

private static void wordBreakHelper(String givenSentence, Set<String> dictionary, StringBuilder path, List<String> results) {
    if(givenSentence.length() == 0) {
        return;
    }

    if(dictionary.contains(givenSentence)) {
        results.add(path.toString() + givenSentence);
    }

    for(int i = 1; i < givenSentence.length(); i++) {
        String nextWord = givenSentence.substring(0, i);
        if(dictionary.contains(nextWord)) {
            path.append(nextWord).append(" ");
            wordBreakHelper(givenSentence.substring(i), dictionary, path, results);
            path.replace(path.length() - nextWord.length() - 1, path.length(), "");
        }
    }
}


I think that you are mistaking the purpous of the placeholder attribute.

A label element should be used to indicate what the field is for and a placeholder should provide an example of the format to use.

When you use a seperate label you have much more flexability in how you style it. You can use a "label as placeholder" pattern, where you place the
label on top of the input so it appeares to be the placeholder. You would have to move the label when the input is focused.

In the snippet below I have created two lable's for the input. It would be very easy to show and hide based on a media query.

Organization or Company Name
Org/Company
<input type="text" id="org" name="" placeholder="Code Review">


Problems with your interface design:

The Employee interface you've designed is clearly lacking
abstraction, since you have a dynamic_cast in the program to
test if an employee is of a specific type.

Employee should instead have a virtual method such as DoWork()
which in turn will call Compiling() for Programmer,
Selling for a SalesPerson and so forth:

class Employee
{
public:
    ....

    // Virtual function with no default implementation (= 0)
    virtual void DoWork() const = 0;
};

class Programmer
{
public:
    void DoWork() const { Compiling(); }
};

class SalesPerson
{
public:
    void DoWork() const { Selling(); }
};

The constructor of Employee sets salary to 1000 unconditionally.
Perhaps it would be better to take salary as a constructor parameter
so you can easily specify different salaries:

Employee(double salary) : salary(salary) { }

BTW, double seems more appropriate for a monetary value, as it
is likely to include decimal places. int is for whole numbers only.

The destructor of Employee is empty, so it should be made a default:

virtual ~Employee() = default;

Memory management tidbits:

It is generally better to avoid manual memory management, as it is
error prone, not exception safe, and slipping a memory leak is very easy.
In fact, in your current example, the objects you've allocated
with new are not being destroyed. Remember that C++ is not garbage collected. You would have to delete them somewhere.

You should ideally be using an automatic pointer to manage
your dynamic instances. main() could be reworked in the following way:

#include <array>
#include <memory>

int main()
{
    std::array<std::unique_ptr<Employee>, 3> company;

    int choice = 0;
    for (int i = 0; i < company.size(); i++)
    {
        std::cout << "(1) Programmer (2) SalesRep: ";
        cin >> choice;

        if (choice == 1)
        {
            company[i].reset( new Programmer );
        }
        else
        {
            company[i].reset( new SalesPerson );
        }
    }

    ....
}

You should note in the example above the use of std::unique_ptr and
std::array. The unique_ptr is a managed pointer that will delete
the object automatically when you leave the function scope. This way
you don't have to worry about memory leaks. std::array is a fixed size
array which behaves just like a plain C array, but with some extra member
methods and debug bounds checking. It also knows its length, so we no longer
need to keep that numEmployees constant around.


First attempt at writing Rock Paper Scissors game

The style is pretty good, I can just see two minor improvements you could do: Firstly, you can define random in terms of your own randomR in order to save a few keystrokes:

instance Random Throw where
  random = randomR (minBound, maxBound)
  randomR (a, b) g = ...

At this point Haskell's typing even derives the type of minBound for you, so you can lose the explicit annotations.

Second, you should probably use randomIO instead of liftM (fst . random) getStdGen. That is not only shorter, but also updates the generator state, which means that you won't get the same result if you call it twice in the program.


Do not use namespace std:
There is multiple reviews on that here on this site already, so I'll just sum it up shortly:

using namespace std pollutes global namespace and leads to possible conflicts with other functions. For more information you can read this stackoverflow post on the matter.

Naming:
Simply because of your variable names I found it hard to understand what exactly you were doing. Characters are not costly. Anymore that is, but you should really write out what your variables are supposed to do:
od --> oddFactorOccurence
ev --> evenFactorOccurence
v --> currentFactorCounter
n --> number
t --> countOfNumbers
hal --> half / evalThreshold
erastho... no. just. NO. ;)


One improvement would be factoring out the repeated call to this.search.toLowerCase() and storing the result in a block-scoped constant so it:

doesn't need to be calculated on every call to .includes() for each iteration of filter()
can decrease the length of each line where that value is used

That may be a small optimization but it is in line with the D.R.Y. principle
getfilteredData() {
  const lowerTerm = this.search.toLowerCase()
  return this.blogs.filter(blog =>
    blog.name.toLowerCase().includes(lowerTerm) ||
    blog.category.toLowerCase().includes(lowerTerm)
  )
},

Additionally, it could further be simplified by using Object destructuring to eliminate the need for the identifier blog with the callback to the filter method:
getfilteredData() {
  const lowerTerm = this.search.toLowerCase()
  return this.blogs.filter({name, category} =>
   name.toLowerCase().includes(lowerTerm) ||
   category.toLowerCase().includes(lowerTerm)
  )
},


There isn't much code to break this down to smaller components but based on the post :

this.setState() passing an Object or a callback function :

If you want to update the state with a value that's not dependent on the previous one you can do :

this.setState({ key : newValue });

If you have to update the state based on the previous one,

this.setState(prevState => ({key: prevState.key + value }));

see state updates may be asynchronous for more details.

the reason why i mention this is because in componentDidMount() you're passing a callback function to setState when you don't need the the prevState.

componentDidMount() {
  this.setState({ json: getJson() })
}

In checkAll() you can do one setState() instead of two:

checkAll = () => {
   this.setState(prevState => ({
     checked: !prevState.checked,
     json: prevState.json.map(obj => ({
       ...obj,
       items: obj.items.map(item => ({
         ...item,
         value: prevState.checked,
       }))
     }))
   }));
};

Use implicit return  in the render method :

the render method can use implict returns inthe .map() and you don't really need the i, it can be refactored to :

render() {
  return (

          {this.state.json.map(obj => (

              {obj.items.map(data => (

{data.label}

                    <input
                      type="checkbox"
                      checked={data.value}
                      onChange={this.checkboxHandler}
                    />
                	)
              )}

)
          )}

      <button onClick={this.checkAll}>check\uncheck</button>
      <AddRow actualJson={this.state.json}/>

  )
}


Basic API wrapper around a Restful service - follow-up

As @t3chb0t says, the implementation is clean enough already.

However, if you wanted to go one step further, I would inject the implementation of IRestSharp into the TopmanClient, so that you can then test the behaviour of your default implementation when an API error occurs. For instance, if the API returns a 404 Not Found, how will your client behave? How about if a deserialisation error occurs?

For double bonus points, you could run the test once passing in a mock IRestClient; then run the same test again passing in a real RestClient - you now have a test of your client and an integration test for the API (although make sure you are pointing at a non-production API, or a test account, or a sandbox). Whether or not you include those in your automated builds or automated deployments, I'll leave up to you.


List-flattening function in erlang feels too wordy

Little smaller than yours.

% flatten a list
my_flatten([])->
    [] ;
my_flatten([[]|T])->
    my_flatten(T);
my_flatten([[H|T]|T2])->
    my_flatten([H|[T|T2]]);
my_flatten([H|T])->
    [H|my_flatten(T)].

http://erlang99.wordpress.com/2009/01/19/p07-flatten-a-nested-list-structure/

my_flatten_rec(L)->
    lists:reverse(my_flatten_rec([],L)).
my_flatten_rec(Acc,[[]|T])->
    my_flatten_rec(Acc,T);
my_flatten_rec(Acc,[[H|T]|T2])->
    my_flatten_rec(Acc,[H|[T|T2]]);
my_flatten_rec(Acc,[H|T])->
    my_flatten_rec([H|Acc],T);
my_flatten_rec(Acc,[])->
    Acc.


JavaScript Etch-A-Sketch implementation from The Odin Project

Bug
There is a small chance  (about 1 in 16) that the random color function will generate an bad color as you don't check for leading zeros. See code below for an alternative.
DRYing out code (Don't Repeat Yourself)
Yes there is way to much repeated code.
Repeated code is not only a pain to create, it is a source of bugs when it comes time to make changes.
Differences as arguments.
To reduce repetition we use functions to wrap up code that has only slight differences, passing the differences as arguments.
For example you have the 3 button event handlers with 3 sections of almost identical code.

const newGridButton = document.getElementById('newGridButton');
newGridButton.addEventListener('click', function(e){
    clearGrid();
    let newSize = prompt('New Grid Size:');
    createGrid(newSize);
});

const pencilButton = document.getElementById('pencilButton');
pencilButton.addEventListener('click', function(e){
    clearGrid();
    let newSize = prompt('New Grid Size')
    pencilGrid(newSize);
});

const colorfulButton = document.getElementById('colorfulButton');
colorfulButton.addEventListener('click', function(e){
    clearGrid();
    let newSize = prompt('New Grid Size')
    colorfulGrid(newSize);
});

The only difference in each is the Id of the button and the function called at the end. Thus we can simply wrap one of those sections in a function passing the Id and the setup function as arguments.
function setUpButton(buttonId, createGrid) {
    const button = document.getElementById(buttonId);
    button.addEventListener('click', function(e){
        clearGrid();
        let newSize = prompt('New Grid Size')
        createGrid(newSize);
    });
}

Reduce code noise
Shorten it little by removing code noise,

The prompt can move into the function call.
The clearGrid can move to the createGrid function
We can use direct DOM reference for the button element when we call the function, so we don't need document.getElementById
Use an arrow function for the event, and we don't need to event argument.

Thus we get the whole thing done in 6 lines.
function setUpButton(button, createGrid) {
    button.addEventListener('click', () => createGrid(prompt('New Grid Size')))
}
setUpButton(newGridButton, createGrid);
setUpButton(pencilButton, pencilGrid);
setUpButton(colorfulButton, colorfulGrid);

18 lines down to 6.
Using names to reference functions
Looking at the create grid function the only difference is the mouse event, all the rest is identical. Create the mouse event functions separately. We need a reference to the newSquare, that can be found in the event as event.target
To make accessing the functions easier we can add them to an object and use their names in the create grid function.
const draw = {
    colorful(e) {
        e.target.style.background = (Math.random()*0xFFFFFF|0).toString(16).padStart(7,"#000000");
        e.target.style.border = '0px';
    },
    pencil(e) {
        e.target.style.background = 'black';
        e.target.style.opacity += 0.1;
    },
    create(e) { e.target.style.background = 'black' }
}

and modify the create grid function to take the name of the draw function as well as the size. Also move the clear grid function into this function.
The end result
Putting it all together we get it all done in about half the code.
const drawing = {
    colorful(e) {
        e.target.style.background = (Math.random()*0xFFFFFF|0).toString(16).padStart(7,"#000000");
        e.target.style.border = "0px";
    },
    pencil(e) {
        e.target.style.backgroundColor = 'black';
        e.target.style.opacity += 0.1;
    },
    black(e) { e.target.style.backgroundColor = 'black' },
};
setUpButton(newGridButton, "black");
setUpButton(pencilButton, "pencil"");
setUpButton(colorfulButton, "colorful");
createGrid("black");

function setUpButton(button, name) {
    button.addEventListener('click', () => createGrid(name, prompt('New Grid Size')))
}

function createGrid(name, size = 16){
    var count = size ** 2;
    while (gridContainer.firstChild) { gridContainer.removeChild(gridContainer.firstChild) }
    while (count--) {
        const cell = Object.assign(document.createElement("div"), {className : "newSquare"});
        gridContainer.appendChild(cell);
        cell.addEventListener("mouseover", drawing[name]);
    }
    ["--rowNum","--colNum"].forEach(p => document.documentElement.style.setProperty(p, size));
}

I used direct element reference for gridContainer, newGridButton, colorfulButton, and pencilButton so you must ensure that they are unique ids on the page.


Maintaining a count with two threads using conditional variables

Couple of issues:

The code is not exception safe.
Any resource that has an open/close symantic should be handled via RAII

{
    pthread_mutex_lock (&mutexA);

    // Code
    // This may throw an exception thus will
    // cause the code to miss the unlock.

    pthread_mutex_unlock (&mutexA);
}

To fix this you should us an RAII locker object.

{
    MutexLocker    lock(mutexA);  // constructor calls lock.
                                  // detructor calls unlock.
    // Code
    // This may throw an exception
    // and it still works correctly.
}

It may work in this simple example:

    if (count <= 0)
    {
        std :: cout << "\ngnitiaW!\n";
        pthread_cond_wait (&conditionVariableA, &mutexA);
    }

But normally you need to place the wait() inside a loop.

    while (count <= 0)
    {
        std :: cout << "\ngnitiaW!\n";
        pthread_cond_wait (&conditionVariableA, &mutexA);
    }

If there are multiple threads that could enter this function then between the signal from the producer thread and this thread waking up from the wait another thread could have stolen the object. Thus you need to recheck the state you were waiting for and go back to sleep if it was stolen.

This would have been fixed by the MutexLocker above. But the code as it stands leaves the lock locked.

    else
    {
        // Do something.
        std :: cout << "\nTime to enjoy!\n";

        // You are  returning early without unlock the lock.
        // This causes all your other threads to stall
        // and probably causes deadlock.
        return 0;
    }

    // This point is not reached if you return early.
    pthread_mutex_unlock (&mutexA);


The filter function is what you're looking for. Here's an example given on the documentation page that should demonstrate exactly how it's used:

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];

var longWords = words.filter(function(word){
  return word.length > 6;
});

// Filtered array longWords is ["exuberant", "destruction", "present"]

Additionally, the map function can be useful to iterate through arrays to apply a function to each value in the array instead of just filtering out values based on a bool result (in your case, whether the email is in excluded emails). For a basic check to see if the email address is excluded, you'll want filter. If you do any processing on the emails array (say, sending emails), you may want to look into map.


Making adding to a dictionary more efficient?

You're iterating through controlStrings 4 times (because you have 4 Where clauses).

It might be better to rewrite this as a for loop:

foreach (var c in controlStrings)
{
    var cultureN = c.CultureN;

    if (cultureN.Contains("cati") && cultureN.Contains("en"))
        ... add c to CatiControlStrings;

    if (cultureN.Contains("web") && cultureN.Contains("en"))
        ... add c to WebControlStrings;

    ... and the same for Spanish.
}

You can also call Contains fewer times:

foreach (var c in controlStrings)
{
    var cultureN = c.CultureN;

    bool cati = cultureN.Contains("cati");
    bool web = cultureN.Contains("web");
    if (!cati && !web)
        continue;
    bool en = cultureN.Contains("en");
    bool es = cultureN.Contains("es");

    if (cati && en)
        ... add c to CatiControlStrings;

    if (web && en)
        ... add c to WebControlStrings;

    ... and the same for Spanish.
}

Also your Count() statement may be expensive and unnecessary.

You're calculating IndexOf twice for every string.

And you're creating a new Substring for every string you test. Instead of creating a substring, use one of the overloads of String.Compare which lets you compare substrings.

Alternatively something like this might be better (because it doesn't use Substring and is simpler than using IndexOf with Compare:

string compareWith = "_" + newAnswer.QVar;
var controlStrings = answerControlStrings.Where(a => a.ControlN.EndsWith(compareWith,
    StringComparison.InvariantCultureIgnoreCase));

Garbage, garbage, everywhere says that using a Where will generate a lot of temporary objects. I don't understand why you're getting "out of memory" sometimes, but rewriting even your first statement to use less Linq might help (or at least make the cause your "out of memory" exception clearer).

foreach (var a in controlStrings)
{
    if (a.ControlN.EndsWith(compareWith, StringComparison.InvariantCultureIgnoreCase))
    {
        // the add-to-dictionary code above
    }
}

Reading C# Does Lambda => generate garbage? (including comments to the accepted answer), Linq generates temporary garbage.

I have a suspicion, after reading Garbage Collection and Performance, that maybe the framework doesn't garbage-collect before throwing 'out of memory'; my guess is that:

Garbage collection runs when it feels like it
Garbage collection runs on a separate thread, without pausing/blocking your threads
Unlike Java, C# will/may not stop to garbage collect immediately before/instead of throwing 'out of memory exception'
Therefore if your thread generates too much garbage too fast (i.e. faster than the garbage is collected), it may throw.

An alternative theory is that garbage remains uncollectable inside the lambda instances until your var controlStrings goes out of scope.

Simplifying your code to use less Linq and no Substring instances should produce less garbage, which might help to avoid throwing the exception.


Your program is pretty good, imports at the top, some functions and comprehensions.
But they can all be improved.

To adhere to PEP8 you should only import one module per import.
You need some more functions, the ones your are using I would not use and would infuriate me.
This is more an unwritten notion, but _ is known as the throw away variable.
Since you throw away the range's items you could do:

[' ' for _ in range(gridSize)]

I'd change the way you display the rows, currently you display two characters per print,
this is quite hard to read, and not very efficient.
Instead I'd recommend a list comprehension!

You display a space if getGrid(x,y) is "C", otherwise getGrid(x,y), for each character in that row.
So:

row = [" " if getGrid(x, y) == "C" else getGrid(x, y) for y in range(gridSize)]

To then display this row you should use ' '.join(row). This puts a single space in-between each position on the board.

The other major change I'd make is the use of str.format.
Take the following line:

print(" " + result + " [Ships: " + str(ships) + ", Size: " + str(gridSize) + ", Hits: " + str(hits) + "]\n")

That's hard to read with all the string concatenations and conversion, which str.format tidies up.
The equivalent would be:

print(" {} [Ships: {}, Size: {}, Hits: {}]\n".format(result, ships, gridSize, hits))

You can now tell the format of the string, and can reasonably guess what will go there.
All in little to no time.

For a few additional changes I'd recommend you change range with enumerate to get the x positions and the row, where you display the grid.
And I'd completely remove the range when using the row comprehension.
To show this:

for x, row in enumerate(game):
    print(' {} {}'.format(x, ' '.join([" " if y == "C" else y for y in row])))

I would also change the boards variable name to board so that people can instantly understand what you mean when you reference it.

In Python you should use snake_case not pascalCase for functions and variables, so gridSize should be grid_size.

And finally, you should use a try-except block when you are converting user input to a number as CAD97 put in their answer.
This is as your program will crash if I enter "a".

To improve the xLabel creation you can think of it like we did the row, however you display the item you get from the range. This means that the list comprehension that you'd do is:

row = [str(i) for i in range(gridSize)]
xLabel = " " * 3 + " ".join(row)


Using add as a function name seems very ambiguous. The method name used in the Java Solution class from LeetCode seems more appropriate: addTwoNumbers (thereby specifying that the arguments, although not numbers themselves, represent numbers).
You can remove the explicit type specification for var result if you add explicit type arguments to mutableListOf(). I personally find this more readable and less verbose:

var result = mutableListOf<Int>()

You can use start until endExclusive instead of start..endInclusive - 1:

for (i in 0 until Math.max(a.size, b.size))

You can use the slightly shorter getOrElse instead of elementAtOrElse. You can also move trailing lambda arguments out of parentheses:

val sum = a.getOrElse(i) { 0 } + b.getOrElse(i) { 0 } + remainder

You can use an overloaded operator for adding elements to a mutable list:

result += if (remainder >= 1) sum - 10 else sum

I wouldn't use remainder >= 1 or remainder > 0 because it makes it appear that remainder can be greater than 1 which is not true. I recommend using remainder == 1.

Altogether:

fun addTwoNumbers(a: IntArray, b: IntArray): Iterable<Int> {
    val result = mutableListOf<Int>()
    var remainder = 0
    for (i in 0 until Math.max(a.size, b.size)) {
        val sum = a.getOrElse(i) { 0 } + b.getOrElse(i) { 0 } + remainder
        remainder = if (sum >= 10) 1 else 0
        result += if (remainder == 1) sum - 10 else sum
    }
    if (remainder == 1) result.add(1)
    return result
}

However, the "problem" specified in LeetCode does not use arrays which are very different from linked lists. If you convert the Java code it provides you would get the following:

/**
 * Definition for singly-linked list.
 * class ListNode internal constructor(internal var `val`: Int) {
 *     internal var next: ListNode? = null
 * }
 */
class Solution {
    fun addTwoNumbers(l1: ListNode, l2: ListNode): ListNode {

    }
}

Solving such a problem should result in a very different solution than what you've arrived at.


A few quick comments:

As written, the code doesn’t always give the correct answer. Here are some cases I found that give what appear to be incorrect results:

>>> membertester('00000112', '000000011')
['2']
>>> print membertester('0001', '000/2')
['0', '0', '1']
>>> print membertester('002', '001/')
['0', '2']
>>> print membertester('10', '122')
['0']

If I’ve understood the intention of the program correctly, those are all wrong. If they’re correct, you need to do a better job of explaining the program.
The way you’ve written it is a bit fiddly – some comments interspersed with the program would make it much easier to read. That, and choosing better variable names – characters are cheap, don’t just use single letters.

For example, how about longer and shorter instead of l and s?
The construction for assigning (l, maxl, s, minl) is very weird, and it took me several reads to make sure I’d understood it correctly. This is too clever – I’d break it up into multiple statements. A few ways to do simplify it:

You don’t use the minl variable, so get rid of it. (If you meant to use it, is that a bug?)
The for loop can be replaced by for i, item in enumerate(longer), doing away with the need for the maxl variable.
You could assign the two remaining variables in a neater way:

shorter, longer = sorted([a, b], key=len)

or as an if statement if you wanted to be really explicit.

After a bit of tidying, this is what my version of the function looks like (note that it still has the same bugs as above):

def membertester(list_a, list_b):
    """a slow (iterative) dupe-preserving sorting subset tester,
    for mutual membership tests (like set overloads &)"""
    common = []
    shorter, longer = sorted([list_a, list_b], key=len)

    for idx, item in enumerate(longer):
        try:
            if shorter.count(item) >= longer.count(item):
                common.append(list_a[idx])
        except IndexError:
            pass
    return common

Sidebar: how did I find those examples?

I’m not psychic, and I’m not good at spotting obscure bugs. Instead, I used Hypothesis, which is a powerful randomised, property-based testing library. Here’s the property I used:

  Every mutual member of two lists must be a member of each list.

Sounds reasonable, right?

And here’s how I expressed that as a test:

from hypothesis import given, strategies as st

@given(st.text(), st.text())
def test_that_mutual_members_are_in_both_lists(list_a, list_b):
    mutual_members = membertester(list_a, list_b)
    for item in mutual_members:
        assert item in list_a
        assert item in list_b

Hypothesis tries hundreds of randomised examples, and checks whether this property holds – it found a bug on the second run. I highly recommend trying it.

Sidebar 2: what causes that bug?

Notice that in all of the examples, we have len(b) > len(a). So we have longer = b, shorter = a. As you go through the for loop, you’re iterating over the elements of b, but you’re using a to choose which element gets marked as common. You want to replace

c.append(a[i])

with

c.append(l[i])

With that in mind, you can make the code much cleaner:

def membertester(list_a, list_b):
    """a slow (iterative) dupe-preserving sorting subset tester,
    for mutual membership tests (like set overloads &)"""
    common = []
    shorter, longer = sorted([list_a, list_b], key=len)

    for item in longer:
        if shorter.count(item) >= longer.count(item):
            common.append(item)

    return common

I’ve been unable to find any bugs in this implementation.