A function does one thing, and one thing only.

Break your findrepeats() function apart. As the name indicates, only search for repeats, nothing else. Especially no output. When you are done, return asciiArray.

Maintain a clear separation of input and output, and the actual logic.

Keeping your functions short increases readability a lot, it also makes testing for bugs and restructuring your program later on a lot easier. In addition to that, it also reduces the number of local variables in a function, which aids further with readability.

int asciiArray[256];
for (int i = 0; i < 256; i++) // creates my refference array for the comparison and sets all the values equal to zero
    asciiArray[i] = 0;

Write it shorter:

int asciiArray[256] = {0};

Or use at least a builtin:

int asciiArray[256];
memset(asciiArray, 0, 256);

See also Array intialization

As mentioned in the other answer, don't try to iterate over the input string twice. You don't need to. asciiArray is all you need to generate the output, as long as the order doesn't matter.

vector <char> alreadyprintedcharacters;

Never use global variables. Just don't. That is bound to have side effects sooner or later.

Try e.g. calling findrepeats() twice now. The second call will not work as expected, as it is still (wrongly) using the exemption list from the first run.

This variable is only used inside findrepeats(), so put it in the local scope where it belongs.

int asciiArray[256];
char ch;

ch = in[i];
charconv = static_cast<int>(ch);
asciiArray[charconv]++;

Something is horribly wrong here, can you guess what?

Try to remember what char actually is. 256 distinct values, but was it 0..255 or was it rather -128..127?

You don't remember?
That's right. It's not defined what the default interpretation for a standalone char is, that depends on your compiler.

char alone is perfectly safe to transfer input to output, as signed or unsigned doesn't matter for that.

But if you want to use it as an array index, you must explicitly state that you want an unsigned char, or your program will crash horribly if the input contains anything outside the ASCII range (0..127), as it may be interpreted as a negative value.

Your compiler probably refused to accept char as an array index, and this problem is exactly the reason why. static_cast<int>(ch) only broke the type check, but your application will still crash.


Checking if a value is within a time range

For example,

package main

import (
    "fmt"
    "time"
)

func IsInTimeRange(tvalue int32, timeout int) bool {
    delta := int(time.Now().Unix() - int64(tvalue))
    return -timeout < delta && delta < timeout
}

func main() {}

tvalue int32 will overflow in year 2038, change it to tvalue int64.

package main

import "time"

func IsInTimeRange(tvalue int64, timeout int) bool {
    delta := int(time.Now().Unix() - tvalue)
    return -timeout < delta && delta < timeout
}

func main() {}


Since you mentioned unit tests, here are 2 unit tests that proves your code does not work (Based on name, age, email, phone header):

@Test
public void testFindIndicesThrowsException()
{
    ClassName x = new ClassName();

    try
    {
        int[] result = x.findIndices("Name", "age", "FieldThatDoesNotExist", "Phone");
        fail("expected exception was not thrown!");
    }
    catch (IllegalArgumentException exception)
    {
        assertEquals("One or more of input arguments could not be found in the headers.", exception.getMessage());
    }
}

@Test
public void testFindIndices()
{
    ClassName x = new ClassName();

    int[] result = x.findIndices("Email", "Phone", "Name", "age");
    assertEquals(4, result.length);
    assertEquals(2, result[0]);
    assertEquals(3, result[1]);
    assertEquals(0, result[2]);
    assertEquals(1, result[3]);
}

Explanation: You are setting a boolean in a loop. This means it could be set to false on one iteration, then set to true on the next.

Instead, you can set the index to the one found, and if it's not found, throw an error:

int k = 0;

for (String s : input)
{
    indices[k] = -1;

    for (int i = 0; i < this.headers.length; i++)
    {
        if (s.equalsIgnoreCase(this.headers[i]))
        {
            indices[k] = i;
        }
    }

    // If we never found the item
    if (indices[k] == -1)
    {
        throw new IllegalArgumentException(
            "One or more of input arguments could not be found in the headers.");
    }

    k++;
}


The common definition of XSS is that code faults which allow someone to manipulate your website appearance, access prohibited sections of data, view inaccessible files or possibly steal credentials and cheat your app's users into entering data on the wrong website.

One of the most commonly used XSS vulnerabilities is what we call "free input" when the app allows users to insert HTML or javascript into a form which using POST or GET HTTP methods.

The reason why XSS exists is not sanitizing user free input, allowing someone to inject code into your form which can lead to injecting remote javascript which can write the data you enter into the app database and stealing your information.

A very common method to do this is for phishing purposes to steal login credentials and account information.

To prevent script injections and attempts to modify your PHP’s global and request variables, use the following in your .htaccess:

<IfModule mod_rewrite.c>
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule .* index.php [F,L]
</IfModule>

You may use this free online XSS scanner to ensure the cleanness of your pages, http://xss-scanner.com/ and don't forget to use mod_security which would help reduce this kind of attacks.

By the way, you never trust user provided data inputs which include $_POST, $_GET, file uploads, cookies and HTTP headers (like User-Agent and Referer) such data must always be treated as untrusted and needs to be secured for each context especially if you're going to insert these inputs to your database.

Here is a very useful article including tips and tricks of .htaccess
http://viralpatel.net/blogs/21-very-useful-htaccess-tips-tricks/


Debounce counter for PIC micro - Suggestions for improvement

Device selection
I guess the reason you're on the PIC16F57 is that you're a hobbyist, and this device was the one on hand. I can nearly guarantee that, for a production application, you can find a device from Microchip that is newer, cheaper, smaller and more capable.
One change that most new PICs include is selectable Schmitt-trigger input mode, which will help with your debounce or even eliminate the need for software debounce, depending on your specifications. Your current device has no Schmitt trigger selection register (chapter 6), and only a limited number of special-purpose pins that have Schmitt trigger inputs (chapter 11.3).
Another feature you can take advantage of is software-enabled weak pullup, which - given that you're monitoring a button - is likely to simplify your circuit, which you have not shown. This is commonly available in new PICs.
Yet another feature you could use is integrated pin change detection, commonly available in new PICs - the IOCI module. This can potentially reduce your power consumption, since you wouldn't have to run a polling loop - you could set up a timer, set up IOCI, and then if the timer fires before an IOCI the button event is valid. If an IOCI fires before the timer expires, reset the timer. Some devices can actually go to sleep while this happens and wake up for either interrupt.
Typo
overflown = overflowed
Assembly
I don't recognize the flavour of assembly you're using, perhaps because I'm used to the assembler bundled with contemporary releases of MPLABX. But any self-respecting assembler should be able to:

Accept 6 instead of 0x06, the latter having no need for hexadecimal representation. The same with 0x00.
Include a device-specific header file with symbols for PORTB so that the magic number 0x1F can be replaced by what you're actually doing, which is

andlw PORTA0_MASK |
      PORTA1_MASK |
      PORTA2_MASK |
      PORTA3_MASK |
      PORTA4_MASK;

All (official) PIC environments offer such symbols in their header files, and using them will make your project more maintainable.
General approach
It seems deeply strange to me that you're debouncing five buttons all at once. I would expect, for the current device you have,

Poll for one button press - you can check all pins of PORTA at once using the Z flag
When you hear a button press, assign a mask variable that monitors only that button pin
Poll until either the time expires (you can use TIMER0 and its prescaler to get 32ms) or the button is released
Poll on that pin only, using your mask, until 32 ms are up

For most applications you'll only care to process one button at a time.


Python to write multiple dataframes and highlight rows inside an excel file

First, starting from your code, you should realize that you are repeating yourself, three times. This goes against the principle Don't repeat Yourself (DRY).

The only real difference between processing your three sheets are their name and the underlying dataframe, so you could make this into two functions:

from win32com.client import Dispatch
import pandas as pd

def highlight_false(df):
    arr = (df.select_dtypes(include=[bool])).eq(False).any(axis=1).values
    return np.arange(1, len(df) + 1)[arr].tolist()

def color_rows(sheet, rows, col):
    for row in rows:
        cells = f"A{row+1}:{col}{row+1}"
        sheet.Range(cells).Interior.ColorIndex = 6
    sheet.Columns.AutoFit()

if __name__ == "__main__":
    Emp_ID_df = ...
    writer = pd.ExcelWriter(OutputName)
    Emp_ID_df.to_excel(writer, 'Sheet1', index=False)

    excel_app = Dispatch("Excel.Application")
    workbook = excel_app.Workbooks.Open(OutputName)
    excel_app.visible = False

    sheet_names = ["Sheet1"]
    dfs = [Emp_ID_df]
    for sheet_name, df in zip(sheet_names, dfs):
        sheet = workbook.Sheets(sheet)
        rows = highlight_false(df)
        col = colnum_num_string(df.shape[1])
        color_rows(sheet, rows, col)

However, there is an even easier method using xlsxwriter:

import pandas as pd

Emp_ID_df = ...

writer = pd.ExcelWriter(OutputName, engine='xlsxwriter')
Emp_ID_df.to_excel(writer, sheet_name="Sheet1", index=False)

workbook = writer.book
format1 = workbook.add_format({'bg_color': '#FFC7CE',
                               'font_color': '#9C0006'})
dfs = [Emp_ID_df]
for df, sheet in zip(dfs, writer.sheets.values()):
    nrow, ncol = df.shape
    col_letter = colnum_num_string(ncol + 1)
    cells = f"A1:{col_letter}{nrow+1}"
    sheet.conditional_format(cells, {"type": "cell",
                                     "criteria": "==",
                                     "value": 0,
                                     "format": format1})
writer.save()

You might have to ensure that the sheets do not get out of snyc from the data frames, or just keep track of what name you save each dataframe to.

In addition I used Python's official style-guide, PEP8, which recommends using lower_case for functions and variables as well as renaming your variables so they are a lot clearer.


What is missing

A compatibility with existing shells. There are certain expectations on how the expansion works; your code expands in an incompatible way; expect end-user complains:

Tilde is expanded only in the beginning of the word. You expand it anywhere.
Tilde may be followed by a login name, then the whole prefix is expanded to a home directory of that user. You do not expand the tilde-prefix.
There is no provision to escape tilde or $ from expanding.
There is no way to limit variable name before it hits the path separator.

How to deal with the duplicate code around ApplyEnvVariable() calls

I guess, the simplest way is to move the duplicated code directly into ApplyEnvVariable(). That would actually justify the name of the method: as of now it doesn't apply the variable but merely expands it.  Of course you'd need to pass Out.end() instead of Temp there.

Naming

It is very unusual to have variable names capitalized.


Collate a growing number of String arrays and search through them

You should use Sets instead of Arrays and Enums when it makes sense. I would write that as:

enum FeedClass {
    TEAM, DRIVER, OTHER;
    private static final Set<String> DRIVER_FEED_TYPES = new HashSet<>(Arrays.asList(
            "SEBASTIAN_VETTEL", "LEWIS_HAMILTON", "CHARLES_LECLERC", "MAX_VERSTAPPEN"));

    private static final Set<String> TEAM_FEED_TYPES = new HashSet<>(Arrays.asList(
            "FERRARI", "MERCEDES", "SAUBER", "REDBULL"
    ));

    public FeedClass fromType(String feedType) {
        if (DRIVER_FEED_TYPES.contains(feedType)) {
            return DRIVER;
        } else if (TEAM_FEED_TYPES.contains(feedType)) {
            return TEAM;
        } else {
            return OTHER;
        }
    }
}

private boolean isFeedEnabled(FormulaOneMessage formulaOneMessage) {
    FeedType feedType = FeedClass.fromType(formulaOneMessage.getFeedType());
    switch (feedType.getClazz()) {
        case DRIVER:
            return isDriverFeedEnabled();
        case TEAM:
            return isTeamFeedEnabled();
        default:
            return false;
    }
}

Driver names isn't really something that should be hardcoded, you probably want to move it to database or external file(s).
You can't really avoid if/switch in isFeedEnabled() unless you move isDriverFeedEnabled and isTeamFeedEnabled into enum, it might not be
 possible in your code to do it cleanly.


Check which state is activated and render the JSX accordingly

If by this question you mean you want to prettify your code then Google "javascript prettify" and you will get numerous hits. For example, I picked the first one, Online JavaScript Beautifier and it did the following to your example with a few clicks. You can adjust the parameters of the prettifier to suit your needs. BTW this web site also mentions a Chrome plugin specifically aimed at prettifying code in Stack Overflow posts.

switch (this.state.selected) {
    case "all":
        styled = this.state.allKeywords.map(keyword =>
            <
            div style = {
                {
                    display: "flex",
                    flexDirection: "row"
                }
            } >
            <
            Input key = {
                Math.random
            }
            style = {
                {
                    height: "45px",
                    marginBottom: "20px"
                }
            }
            onClick = {
                this.onKeywordClick
            }
            value = {
                keyword
            }
            onChange = {
                this.onKeywordChange
            } > < /Input> <
            Button key = {
                Math.random
            }
            onClick = {
                () => this.deleteKeyword(keyword)
            }
            style = {
                {
                    height: "45px",
                    marginLeft: "30px"
                }
            } > Delete < /Button> <
            /div>
        );
        break;
    case "positive":
        styled = this.state.positive.map(keyword =>
            <
            div style = {
                {
                    display: "flex",
                    flexDirection: "row"
                }
            } >
            <
            Input key = {
                Math.random
            }
            style = {
                {
                    height: "45px",
                    marginBottom: "20px"
                }
            }
            onClick = {
                this.onKeywordClick
            }
            value = {
                keyword
            }
            onChange = {
                this.onKeywordChange
            } > < /Input> <
            Button key = {
                Math.random
            }
            onClick = {
                () => this.deleteKeyword(keyword)
            }
            style = {
                {
                    height: "45px",
                    marginLeft: "30px"
                }
            } > Delete < /Button> <
            /div>
        );
        break;
    case "negative":
        styled = this.state.negative.map(keyword =>
            <
            div style = {
                {
                    display: "flex",
                    flexDirection: "row"
                }
            } >
            <
            Input key = {
                Math.random
            }
            style = {
                {
                    height: "45px",
                    marginBottom: "20px"
                }
            }
            onClick = {
                this.onKeywordClick
            }
            value = {
                keyword
            }
            onChange = {
                this.onKeywordChange
            } > < /Input> <
            Button key = {
                Math.random
            }
            onClick = {
                () => this.deleteKeyword(keyword)
            }
            style = {
                {
                    height: "45px",
                    marginLeft: "30px"
                }
            } > Delete < /Button> <
            /div>
        );
        break;
    default:
        console.log("No keyword list mapped");
}


I might be misreading your code, but it looks like all you want is:

def echo(*args):
    six.print_(*args, sep=" ", end="")

For something a bit more manual:

def echo(*args):
    six.print_(" ".join(map(str, args)), end="")

In terms of reviewing your actual code, on top of the issues Morwenn raises, note that:

op = getattr(data, '__str__', None)
if op:

simplifies to:

if hasattr(data, '__str__'):

However, it is rare to call magic methods directly in Python; normally you'd just do str(data) and let Python call __str__. This is safer, as although an old-style class may not implement __str__, you can still get e.g. '<foo.bar object at 0x...>' via str(...).

I would include the filtering as a separate function:

def valid(arg):
    """Include a docstring to explain your filtering rules."""
    if (isinstance(data, (six.string_types, six.integer_types)) or
        hasattr(data, '__str__')):
        return True
    LOG.error("echo called with an unsupported data type")
    return False

Then echo can use filter:

def echo(*args):
    six.print_(*filter(valid, args), sep=" ", end="")


Kattis challenge to finding the number of different elements in a set

As you yourself hinted in the question title, you should be using a set. Discarding duplicates using a set is easier and more efficient than using a vector.


Edit: I've updated the code and uploaded a gist that will work in the TS playground - the gist will compile with Typescript 3.1.

The primary benefit of Typescript is to provide types for Javascript. And since Typescript provides Generics - I don't think your implementation of a Dictionary provides any benefit over a plain javascript object.

In fact, as you noted in the comments, JS Objects (ie TS object) are dictionaries. You just need to provide types around them for your dictionary. (btw - I also come from a C# background, but I've also come to love the underlying functional nature of JS that TS lets us type).

Here's a code sample of the direction I would expect a Dictionary.ts class to have in a code base I work in. Now that we have Mapped Types, we can generalize dictionaries better.

export interface Dictionary<K, V> {
  getKeys(): K[];
  getValues(): V[];
  get(key: K): V | null; // the key might not exist
  put(key: K, val: V): void; // or boolean?
}

export class JSDictionary<K extends string, V> implements Dictionary<K, V> {

  private internalDict: { [key in K]?: V };

  constructor() {
    this.internalDict = {};
  }

  public getKeys() {
    let keys: K[] = [];
    for(let key in this.internalDict) {
      keys.push(key);
    }

    return keys;
  }

  // Type predicate to ensure v exists
  private exists(v: V | undefined): v is V {
    return v != null && typeof v !== "undefined";
  }

  public getValues() {
    let vals: V[] = [];

    for(let key in this.internalDict) {
      let v = this.internalDict[key];
      if(this.exists(v)) {
        vals.push(v);
      }
    }

    return vals;
  }

  public get(key: K) {
    let v = this.internalDict[key];
    return this.exists(v)
      ? v
      : null;
  }

  public put(key: K, val: V): void {
    this.internalDict[key] = val;
  }

}

Example Usage

type myKeys = 'FOX' | 'CAT' | 'DOG';

interface Animal {
  species: string;
  name: string;
  weight: number;
}

// A dictionary that hols one fox/cat/dog.
let myAnimalPen = new JSDictionary<myKeys, Animal>();

myAnimalPen.put('FOX', { name: 'Foxworth', species: 'Fox', weight: 40 });

// a dictionary that takes any string and maps it to a number
let idDict = new JSDictionary<string, number>();
idDict.put('somehas', 1204);
idDict.put('yeahaasd', 3306);

let yeaID = idDict.get('yeahaasd'); // yeaID is a number | null type
let myFox = myAnimalPen.get('FOX'); // myFox is an Animal | null type

Major points:

Code to an interface as much as you can in typescript. Affords you flexibility
Generic types
Transparent use of Plain JS object as the underlying dictionary (JS Engines optimize this very use case!)
I removed overloaded constructors, but you could add that back in with the proper types and it will work as expected
Left out clone - pretty easy to implement though
No exception handling when get returns null, like your 'try*' functions. I actually like try functions like you have, so you could mostly copy/paste, although with the stricter typings sometimes that will be taken care of by the compiler for you.


Remove redundancies in similar properties

You could make your code less redundant through the use of a custom SourceGenerator. It could work kinda like Fody works for WPF and INotifyPropertyChanged.
Sadly I have no example to provide for the SourceGenerator's implementation because I haven't had time to toy with them yet. Though the idea is to make your SourceGenerator generate the redundant code for you at compile time whenever it detects something that you want to be autogenerated.
You have two options but both are gonna require custom attribute(s) :

Make it work like a white-list : don't autogenerate by default, autogenerate only when property is tagged with your attribute. Your property (or field) would then be reduced to
[MyAutoGenerationAttribute]
public object MyProperty { get; set; }

Make it work like a black-list (like Fody does) : always autogenerate by default, don't autogenerate when property is tagged with your attribute.

I'm not really familiar with Unity but my only concern is that this solution may not be compatible with Unity's shenanigans, especially since SourceGenerators is a fairly new feature.
PS : If optimization matters I recommend you edit your setters so that the event gets raised only when the value of the property changes for real (ex: by wrapping the setter with something like if (myBackingField != value))


Working at a bit-wise level for this problem is a superior option than converting it to a string like the linked question (your inspiration) did.

There may be some really tricky magic that can be done with complicated AND/OR/XOR/NOT operations to identify the gaps in a more efficient way, but your solution of "walking" the bits is adequate from an algorithmic perspective.

Note, in your code you have special handling for negative values, but that's not needed if you use the >>> operator for right shifting. Read up on the difference between signed and unsigned right shifts: http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19

The recursion bothers me, though. The overhead for creating a stack frame for each level of recursion, calling the function, etc. seems overkill for something that would be "trivial" with a while-loop.

public static int maxGap(int n) {
    // get rid of right-hand zeros
    while (n != 0 && (n & 1) == 0) {
        n >>>= 1;
    }

    int max = 0;
    int gap = 0;
    while (n != 0) {
        if ((n & 1) == 0) {
            gap++;
            max = Math.max(gap, max);
        } else {
            gap = 0;
        }
        n >>>= 1;
    }
    return max;
}

Now, that runs in \$O(log(n))\$ time where n is the integer being tested.... but, can it be a bit quicker?

I don't think the time complexity can be significantly improved (i.e. I can't see an \$O(1)\$ solution, but I can see some grunt performance improvements out there... assuming that Integer.numberOfTrailingZeros() function is better than O(N) performance:

public static int maxGapX(int n) {
    if (n == 0) {
        return 0;
    }
    int rbits = Integer.numberOfTrailingZeros(n);
    int max = 0;

    // shift off any initial right-most zeros in the init step.
    // then treat any subsequent 1's as the end of a span of zeros.
    for (n >>>= (rbits + 1); n != 0; n >>>= (rbits + 1)) {
        rbits = Integer.numberOfTrailingZeros(n);
        max = Math.max(max, rbits);
    }
    return max;
}

I put this up in an ideone here: https://ideone.com/hllRUa


Setting a common background image on a dozen screens

The short answer is, no, this is not too little code to "extract" into a super class.

If you intend for this bit of code to always be the same throughout every use of this class and its subclasses, then it's absolutely appropriate to put the code in the superclass.  The primary point is, here, if we ever decide to change something about this code, we can change it in once place and have this change applied across all instances.

With that said, however, I want to point out some problems.

As a start, we have no guarantee that this code will actually run.  If our subclass implements viewDidLoad and fails to call to super, now our code doesn't run.  There's still no way to make this guarantee, but there is a way to make a reminder for ourselves.

As this StackOverflow answer outlines, the NS_REQUIRES_SUPER directive will throw a warning when subclass implement the method without calling the super method.  So we should add the following to our .h file:

- (void)viewDidLoad NS_REQUIRES_SUPER;

Now, a subclass of this class which implements viewDidLoad will throw a compiler warning until [super viewDidLoad]; is added to its viewDidLoad implementation.

There's problems still however.  For starters, as a rule, I don't like IBOutlets in my header file.  There's absolutely no reason for these to be public.  But in this particular case, we shouldn't have an IBOutlet at all.  Using an image view set up in interface builder and requiring it be hooked up to this outlet will supremely complicate things.

First, not only do we have to remember to call to super, which I already address.  But we also have to remember to add the image view.  And we have to remember to hook the image view up as an outlet.  Trouble is though, we can't (or shouldn't) hook it up to our current class.  We should open this, the super class, in assistant editor and hook it up to that.  Problem is, assistant editor won't automatically load super class's in the assistant window... so that's kind of a pain.

I'm a huge proponent of using interface builder.  It does a lot to vastly simplify our written code, but in this case, it doesn't suffice for producing simplified results.

We should remove this outlet altogether and not worry in the slightest about relying on the subclass setting up the image view in interface builder and hooking it up properly.  The whole point of subclassing is minimizing redundancy, and so far, we're only half way there.

(Moreover, what guarantee do we have that every subclass of this class will even use interface builder at all?  View Controllers don't require a corresponding interface builder representation--the view can be set up entirely programmatically.)

We need to change our viewDidLoad code to manually create an image view with an image and load it as the background.

The number one problem we'll run into in manually creating and adding the image view to the view controller is getting it appropriately as the background.  We can't be sure whether the subclass will do it's set up first then call super, or call super then do its set up (in case you're wondering, in viewDidLoad, it's appropriate to call to super FIRST, then add your implementation).  Moreover, the view controller will almost certainly have views added on it in interface builder if the developer is using interface builder.

So, we need to add the view as the bottom-most view in the view controller's view's subviews.

This might be a good implementation:

- (void)viewDidLoad {
    [super viewDidLoad];

    // Set up image view
    UIImage *backgroundImage = [UIImage imageNamed:@"background"];
    UIImageView *backgroundView = [[UIImageView alloc] initWithImage:backgroundImage];
    [backgroundView setTranslatesAutoresizingMaskIntoConstraints:NO];
    // aspect fill may be preferred
    backgroundView.contentMode = UIViewContentModeScaleAspectFit;

    // Add background view as back-most view
    [self.view insertSubview:backgroundView atIndex:0];

    // Set up auto layout constraints so this view controller is applicable
    // on any device in any rotation
    NSDictionary *views = NSDictionaryOfVariableBindings(backgroundView);

    NSArray *verticalConstraints =
        [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[backgroundView]-0-|"
                                                options:0
                                                metrics:nil
                                                  views:views];
    NSArray *horizontalConstraints =
        [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[backgroundView]-0-|"
                                                options:0
                                                metrics:nil
                                                  views:views];

    [self.view addConstraints:verticalConstraints];
    [self.view addConstraints:horizontalConstraints];
}

I'm not particularly a fan of setting up UI in code (especially auto layout).  I much, much prefer interface builder.  But in some cases, it is absolutely necessary to get it right.

This auto layout code may seem bulky and unnecessary if your current app is just for iPads and just for a single orientation.  But as soon as you want to subclass this view controller into an app that rotates or is made for iPhones, or is a universal app, you'll be glad to have this auto layout code.

As one final comment, I might make a UIImage property in the .h file so that the background image could be changed.


couple of points from my side:

If you add same TKey instance to your List it will be added only
once. But if you add other instance of TKey but with the same
'content' the end result of Add method is dictionary with two keys with same content and two
lists. Is that part of requirement?

Example:

public class Foo
{
    public string X;
    public int Y;

    public Foo(string x, int y)
    {
        X = x;
        Y = y;
    }
}

var multiDict = new MultiDict<Foo, string>();

var firstFoo = new Foo("abc", 1);
multiDict.Add(firstFoo, "someValue1");
multiDict.Add(firstFoo, "someValue2");

var secondFoo = new Foo("abc", 1);
multiDict.Add(secondFoo, "someValue3");

Similar problem is for TValue, but it's related with removing elements. Solution for both cases is implementing IEqualityComparer for both TKey and TValue and force class user to inject it via constructor and use [THIS] dictonary constructor. That will guarantee uniqueness for your key. Please keep in mind that you should also use RemoveAll method on list to be sure that all elements that matches predicate are removed.
You're incosistent with indentations of methods, curly brackets,
whitespaces between methods. Please clean that up.
I don't see the point of Entry struct. You can easily get rid of it
and put all methods in MultiDictionary class itself.
I would consider to change interface to more 'detailed' interface.
What I mean by that? Let's say that Remove returns count of elements
actually removed. Point only to consideration.
I will change implementation of Add method to something different,
because you always (when key exists in dictionary or not) seeking
through dictionary twice: first time is on TryGetValue method and
second while attaching list to key. Attaching list to key is
necessary only when you're creating new one.


Looking for improvements on basic dice roll code (Python 3)

You should have imports at the top of your code. Having them in the middle of code makes it needlessly confusing with no benefit.
You code doesn't account for the possibility of a user not entering an integer as input. You can utilize a while, try and except ValueError to allow a user to attempt to re-enter a value.
You should keep code out of the global scope. Wrapping your code in a main function will help prevent future mishaps.
You should really use a better name than x, amount is descriptive.
Rather than r you can use _ or __ to denote that you are throwing away the value. This is no different that what you have done now, but it is a custom to help others understand your code quickly.

import random

def roll_dice(amount):
    for _ in range(amount):
        print(random.randint(1, 20))

def main():
    while True:
        try:
            amount = int(input("How many times do you want to roll the dice? "))
            break
        except ValueError:
            print("That is not a valid whole number.")
    print(amount)
    roll_dice(amount)

main()

There are some more advanced things you can do too.

You can use an if __name__ == "__main__": guard to help prevent your main code from running accidentally. If it is imported by accident from another script.
It would be better for you to return the values of the dice rather than print. This allows you to reuse the function later if you need to use the results of the thrown dice.
You can use random.choices to select k amount of values.
Print is slow. You may want to change to use "\n".join to reduce the overhead from calling print multiple times. However you need to convert all the values to strings.
To easily convert each value in a list to a string you can use a for loop, building a new list.

output = []
for item in roll_dice(amount):
    output.append(str(item))

This contains a lot of noise, so we can use a list comprehension to simplify this.

output = [str(die) for die in roll_dice(amount)]

import random

def roll_dice(amount):
    return random.choices(range(1, 21), k=amount)

def main():
    while True:
        try:
            amount = int(input("How many times do you want to roll the dice? "))
            break
        except ValueError:
            print("That is not a valid whole number.")
    print(amount)
    print("\n".join([str(die) for die in roll_dice(amount)]))

if __name__ == "__main__":
    main()

Note: Personally I don't think using the list comprehension and str.join to be as nice as a for loop when it comes to non-performance critical code. This is to show you how you can improve future code with the code you have today.


Your naming conventions are hard to follow, or you're not following them; either way, you're not following the standard/recommended/established conventions.

public byte[] genReportBytes(int id, string fromm,string too,string filetype)

Public members should be PascalCase; locals and parameters should be camelCase. That would make the signature read like this:

public byte[] GenReportBytes(int id, string fromm, string too, string fileType)

getOneReport(id) would be GetOneReport(id), and getReportData(sqlGet, repD.ParametersCommandLine)) would be GetReportData(sqlGet, repD.ParametersCommandLine)), and streamids would be streamIds.

But if I had to pick only 1 name to change, it would be this one:

reportDetails repD = new reportDetails();

reportDetails is a TYPE and should be PascalCase like every single other type name in the framework. Notice how that one even gets the syntax highlighter confused?

The filetype parameter is stringly typed, and wants to be an enum. And I don't understand the doubling-up of m in fromm and o in too - if that's just to make from and to usable names, you have two options:

Prefix with a @ verbatim specifier, making them @from and @to. Seriously though, don't do that.
Give them a meaningful name; I'd match them with the parameters they're mapped to, so that would be startDate and endDate.

There are other points to add, but I have to go... will come back and edit this answer if no one else points them out by then.


OOP Web-scraper w/ Python and BeautifulSoup

Bugs

Lines 32 and 42:

        for titles, info in zip(self, titles, self.comicinfo):

        for dol_amount in comic_prices:

both have unresolved variable references - titles and comic_prices.

Bare class declaration

class ComicScraper():  # Class ComicScraper for scraping comic books

can be

class ComicScraper:
    """
    For scraping comic books
    """

Note the more common format for docstrings used.

Doing too much in an init

requests.get(self.url)

should probably not be done in an __init__. Constructors are usually best to initialize everything that the class will need without "doing" too much.

Argument names

titles doesn't actually accept multiple titles; it only accepts one. Providing the argument twice overwrites the first value. That means that this loop:

        for comic_title in self.comic_titles:

is actually going to loop through each of the characters in the provided string, which is probably not what you want.

Reading the docs - https://docs.python.org/3/library/argparse.html - you probably want action='append'.

Reaching past argparse

This:

    if len(sys.argv) == 1:

should not be done. Instead, rely on the output of argparse.

Suggested

Here is a re-thought program:

from bs4 import BeautifulSoup, Tag
from datetime import date, datetime
from typing import Iterable
import argparse
import re
from requests import Session

class Comic:
    # ·  Apr 8th, 2020  ·  $7.99
    RELEASE_PAT = re.compile(
        r'^\s*·\s*'
        r'(?P<month>\S+)\s*'
        r'(?P<day>\d+)\w*?,\s*'
        r'(?P<year>\d+)\s*'
        r'(·\s*\$(?P<price>[0-9.]+))?\s*$'
    )

    def __init__(self, item: Tag):
        self.id = int(item['id'].split('-')[1])
        sku = item.select_one('.comic-diamond-sku')
        if sku:
            self.sku: str = sku.text.strip()
        else:
            self.sku = None

        consensus_head = item.find(name='span', text=re.compile('CONSENSUS:'))
        if consensus_head:
            self.consensus = float(consensus_head.find_next_sibling().strong.text)
        else:
            self.consensus = None

        potw_head = item.find(name='span', text=re.compile('POTW'))
        self.pick_of_the_week = float(potw_head.find_next_sibling().text.rstrip('%'))

        title_anchor = item.select_one('.comic-title > a')
        self.title: str = title_anchor.text
        self.link = title_anchor['href']

        details = item.select_one('.comic-details')
        self.publisher: str = details.strong.text

        parts = self.RELEASE_PAT.match(list(details.strings)[2]).groupdict()
        self.pub_date: date = (
            datetime.strptime(
                f'{parts["year"]}-{parts["month"]}-{parts["day"]}',
                '%Y-%b-%d'
            )
            .date()
        )
        price = parts.get('price')
        if price is None:
            self.price = price
        else:
            self.price = float(price)

        self.desc: str = list(item.select_one('.comic-description > p').strings)[0]

class ComicScraper:
    URL = 'https://leagueofcomicgeeks.com/'

    def __init__(self):
        self.session = Session()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.session.close()

    @staticmethod
    def _parse(content: str) -> Iterable[Comic]:
        soup = BeautifulSoup(content, 'html.parser')
        list_items = soup.select('#comic-list > ul > li')
        return (Comic(li) for li in list_items)

    def get_from_page(self) -> Iterable[Comic]:
        with self.session.get(self.URL + 'comics/new-comics') as response:
            response.raise_for_status()
            return self._parse(response.content)

    def get_from_xhr(self, req_date: date) -> Iterable[Comic]:
        params = {
            'addons': 1,
            'list': 'releases',
            'list_option': '',
            'list_refinement': '',
            'date_type': 'week',
            'date': f'{req_date:%d/%m/%Y}',
            'date_end': '',
            'series_id': '',
            'user_id': 0,
            'title': '',
            'view': 'list',
            'format[]': (1, 6),
            'character': '',
            'order': 'pulls',
        }
        with self.session.get(self.URL + 'comic/get_comics', params=params) as response:
            response.raise_for_status()
            return self._parse(response.json()['list'])

def print_comics(comics: Iterable[Comic]):
    print(f'{"Title":40} {"Publisher":20} {"Date":10} {"Price":6}')

    for c in comics:
        print(
            f'{c.title[:40]:40} {c.publisher[:20]:20} '
            f'{c.pub_date}', end=' '
        )
        if c.price is not None:
            print(f' ${c.price:5.2f}', end='')
        print()

def main():
    parser = argparse.ArgumentParser()
    # Titles of comicbooks i.e "Detective Comics #1"
    parser.add_argument('-t', '--titles', help='Print these comic titles ONLY',
                        action='append')
    args = parser.parse_args()
    titles = args.titles and set(args.titles)

    with ComicScraper() as scraper:
        comics = scraper.get_from_xhr(date(year=2020, month=3, day=25))
        if titles:
            comics = (c for c in comics if c.title in titles)
        print_comics(comics)

if __name__ == '__main__':
    main()

Points:

Your original class is not useful as a class - it's effectively a function; the important stuff to capture in a class is distinct fields on the data you're trying to represent
You can still class-ify the generator as a class method
Use type hints
Use set membership check for titles
Use a regex to parse the info field
Pull out price and date as a float and date, respectively; don't leave them stringly-typed

Note the second method to use an XHR backend instead of the web front-end. The return format is awkward - they return rendered HTML as a part of the JSON payload - but the interface is more powerful and the method might be more efficient. I have not done a lot of investigation into what each of those parameters means; to learn more you will probably have to dig around the site using developer tools.


First of all you should use a deeper indent than one space. Changing it to three spaces makes the logic more readable:

if($k==0)
{
 $k=0;
}

vs:

if($k==0)
{
     $k=0;
}

The next thing is, that you named your variables in a way, that makes them not readable. $k and $n are not readable at all. If you rename $n to $colspan and $k to $countAsc they express their meaning in your logic, which improves your code style by a lot. Other programmers (like me) can  read way easier into your code then and have a faster understanding of your formulas.

Speaking of formulas, you should not put the calculations into the echo statement, but extract them, to separate the calculation of your values from its usage. That increases the overview of your variables by alot.

$red = $colspan * 25;
$green = (10 - $colspan) * 25;
/* ... */ "background:rgb(" . $red . "," . $green . ",0);" /* ... */

Speaking of the echo statements, you can separate the PHP from the HTML code. Since PHP 5.6 this is really easy due to the short echo tags <?= 'string to echo' ?>. This also enables you to indent the HTML tags as well, giving the reader an easier way to understand your overall structure.

<?php
$red = $colspan * 25;
$green = (10 - $colspan) * 25;
?>

<td style="background-color:rgb(<?= $red ?>, <?= $green ?>, 0);" colspan="<?= $colspan ?>">
    <?= $colspan ?>

As a next step you can safely extract the building of the 	 out of the if clauses. They are equal in both cases and therefore are always echoed, no matter the if conditions. This is also true for your 	 loop. Both inner for loops are exactly the same, given the difference, that the variables have a different names. In addition to that, the $countAsc variable only has two states: Being 1 or 0. Because of that it can safely be changed to a boolean variable.

$colspan = 1;
$countAsc = TRUE;
for ($line = 0; $line < 1000; $line++): ?>

        <?php
        $red = $colspan * 25;
        $green = (10 - $colspan) * 25;
        ?>

        <td style="background-color:rgb(<?= $red ?>, <?= $green ?>, 0);" colspan="<?= $colspan ?>">
            <?= $colspan ?>

        <?php
        for ($column = 0; $column < 10 - $colspan; $column++)
        {
            ?>

            <?php
        }

        if ($countAsc) ...

After extracting all these things you can see, that the if clause only determines, whether the iteration of the $colspan variable is rising or falling. Therefore the if clause should represent only that, to make the logic more readable:

if ($countAsc && $colspan >= 10)
{
    $countAsc = false;
}
elseif (!$countAsc && $colspan <= 1)
{
    $countAsc = true;
}

After this logic is extracted, the calculation for the $colspan is that simple, that it can be shortened to the short if syntax (condition ? true value : false value;) to be in a more readable manner:

$colspan = $countAsc ? $colspan + 1 : $colspan - 1;

Defining the conditions in a more fitting way reduces the necessarity to redefine the $colspan at all and therefore makes your logic less complex. Also if you have huge for loops, it is more readable to use the for(condition): ... endfor; syntax, because like this you can see first hand what type of "closing bracket" is displayed at the end of the loop, giving the code, again, a better readability.
The whole code is:

<?php
$colspan = 1;
$countAsc = TRUE;
for ($line = 0; $line < 1000; $line++): ?>

        <?php
        $red = $colspan * 25;
        $green = (10 - $colspan) * 25;
        ?>

        <td style="background-color:rgb(<?= $red ?>, <?= $green ?>, 0);" colspan="<?= $colspan ?>">
            <?= $colspan ?>

        <?php
        for ($column = 0; $column < 10 - $colspan; $column++)
        {
            ?>

            <?php
        }

        if ($countAsc && $colspan >= 10)
        {
            $countAsc = false;
        }
        elseif (!$countAsc && $colspan <= 1)
        {
            $countAsc = true;
        }

        $colspan = $countAsc ? $colspan + 1 : $colspan - 1;
        ?>

<?php endfor ?>


You can define a mapping between Types and the Deserializers. You can do this for example like this:
public class GenericDeserializer<T> : IDeserializer<T>
{
    private readonly ImmutableDictionary<Type, object> _deserializers =
        new Dictionary<Type, object>
    {
        { typeof(double), Deserializers.Double },
        { typeof(float), Deserializers.Single },
        { typeof(int), Deserializers.Int32 },
        { typeof(long), Deserializers.Int64 },
        { typeof(Null), Deserializers.Null },
        { typeof(string), Deserializers.Utf8 },
        { typeof(byte[]), Deserializers.ByteArray },
    }.ToImmutableDictionary();
}

You can't use the IDeserializer<T> in the Dictionary's Value type parameter that's why it is an object.
Then all you need to do is to make a lookup call and try to cast the value to IDeserializer<T>
if (_deserializers.ContainsKey(typeof(T)))
{
    var deserializer = _deserializers[typeof(T)] as IDeserializer<T>;
    ...
}

If the type was found then you can make branching based on the isNull value:
if (_deserializers.ContainsKey(typeof(T)))
{
    var deserializer = _deserializers[typeof(T)] as IDeserializer<T>;
    var retVal = deserializer.Deserialize(data, isNull, context);
    return !isNull ? retVal : default;
}

If it is not found then you can use the JsonSerializer as your fallback.
return JsonSerializer.Deserialize<T>(data, new JsonSerializerOptions()
{
    PropertyNameCaseInsensitive = true
});

The final code would look like this:
public class GenericDeserializer<T> : IDeserializer<T>
{
    private readonly ImmutableDictionary<Type, object> _deserializers =
        new Dictionary<Type, object>
    {
        { typeof(double), Deserializers.Double },
        { typeof(float), Deserializers.Single },
        { typeof(int), Deserializers.Int32 },
        { typeof(long), Deserializers.Int64 },
        { typeof(Null), Deserializers.Null },
        { typeof(string), Deserializers.Utf8 },
        { typeof(byte[]), Deserializers.ByteArray },
    }.ToImmutableDictionary();

    public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context)
    {
        if (_deserializers.ContainsKey(typeof(T)))
        {
            var deserializer = _deserializers[typeof(T)] as IDeserializer<T>;
            var retVal = deserializer.Deserialize(data, isNull, context);
            return !isNull ? retVal : default;
        }

        return JsonSerializer.Deserialize<T>(data, new JsonSerializerOptions()
        {
            PropertyNameCaseInsensitive = true
        });
    }
}


Code in Python that parses fund holdings pulled from EDGAR, given a ticker or CIK

There are a few improvements I would apply to the code.

Code Style

address PEP8 violations, in particular:

variable and function naming - your functions and variables follow the camel case convention, but PEP8 and Python community advocate for lower_case_with_underscores naming style
watch for the use of whitespaces around operators and in expressions

remove unused imports - re module is unused
the backslash is unnecessary and can be removed
the parentheses around not holdings are redundant and can be removed
you can create a set using a set comprehension directly:

holdings = {h.text for h in soup.find_all((lambda tag: 'issuer' in tag.name.lower()))}

I would also define urlSec url and urlForms url template as proper constants
I think you are also overloading the code with too many things in a single expression. Apply the "Extract Variable" refactoring method to improve readability and simplify the code
use urljoin() to join parts of a URL

Web-scraping and HTML-parsing

since you are issuing multiple requests to the same domain, you may re-use requests.Session() instance, which may have a positive impact on performance:

  if you're making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase

you may also win performance on HTML parsing by utilizing SoupStrainer class which allows parsing only the specific things in the DOM tree

Improved code:

from urllib.parse import urljoin

from bs4 import BeautifulSoup, SoupStrainer
import requests

class Scraper:
    BASE_URL = "https://www.sec.gov"
    FORMS_URL_TEMPLATE = "/cgi-bin/browse-edgar?action=getcompany&CIK={cik}&type=13F"

    def __init__(self):
        self.session = requests.Session()

    def get_holdings(self, cik):
        """
        Main function that first finds the most recent 13F form
        and then passes it to scrapeForm to get the holdings
        for a particular institutional investor.
        """

        forms_url = urljoin(self.BASE_URL, self.FORMS_URL_TEMPLATE.format(cik=cik))

        # get the recent form address
        parse_only = SoupStrainer('a', {"id": "documentsbutton"})
        soup = BeautifulSoup(self.session.get(forms_url).content, 'lxml', parse_only=parse_only)
        recent_form_url = soup.find('a', {"id": "documentsbutton"})['href']
        recent_form_url = urljoin(self.BASE_URL, recent_form_url)

        # get the form document URL
        parse_only = SoupStrainer('tr', {"class": 'blueRow'})
        soup = BeautifulSoup(self.session.get(recent_form_url).content, 'lxml', parse_only=parse_only)
        form_url = soup.find_all('tr', {"class": 'blueRow'})[-1].find('a')['href']
        form_url = urljoin(self.BASE_URL, form_url)

        return self.scrape_document(form_url)

    def scrape_document(self, url):
        """
        This function scrapes holdings from particular document URL
        """
        soup = BeautifulSoup(self.session.get(url).content, 'lxml')

        holdings = {h.text for h in soup.find_all((lambda tag: 'issuer' in tag.name.lower()))}
        if not holdings:
            print("No Holdings at: {}".format(url))
            return

        return holdings


A few thoughts:

Instead of

do {
    std::getline(words_file, word);
    words.push_back(word);
} while (!words_file.eof());

You should do

while(std::getline(words_file, word))
    words.push_back(word);
}

Otherwise, the read which causes the stream to go into an invalid state will still be pushed.

Also, why not include the filename that cannot be opened in the exception text and then output the exception text instead of the hard-coded text you have now.  As things are, you may be ignoring other exceptions (although I don't see when one would happen).  Perhaps output the exception.what() in addition to what you have now.

I would also advise splitting some of the game logic into functions -- you don't need them in multiple places as things are, but it could be easier to follow.  Things like the piece setting word_contains_letter would look better as function calls, in my opinion.

Oh, another thing:  you may want to use #ifndef NDEBUG rather than #ifdef DEBUG, as that is the default way to check whether debugging is enabled or not.


Refactoring Java class with lots of constants

This is a classic case for using an Enum....

public enum MyEnum {
    ID_MAIN("Desc Full Name", Type.A),
    ID_MAIN_UK("Desc Full Name", Type.B),
    ID_SUB("Desc1 Full Name", Type.A),
    .....

    private final String description;
    private final Type type;

    private MyEnum(String desc, Type type) {
        this.type = type;
        this.description = desc;
    }

    public int getID() {
        return ordinal() + 1;
    }

    public String getDescription() {
        return description;
    }

    public Type getType() {
        return type;
    }
}


OOP Decision Maker Class - ServerArbiter

Why does the decide() method do more work? It's the problem of the object constructing your Rules, which is not necessarily the ServerArbiter.
Isn't that already a part of the Server entity? Why do you need to inject yet another dependency. If the server's address isn't in the Server entity, why the hell the server's address isn't in the Server entity?!
Your architecture is fine. Easily separated, Servers don't know about the Rules.
Yes. Since querying all the servers to get their downloads count, it makes sense to remember the best server in the ServerDownloadsComparisonRule the first time resolve is called, and then just reference it from the cache.

if ($bestServer == null) {
    $bestServer = $this->findServerWithLeastDownloads();
}
return $server === $bestServer;


Defining a simple function-calling operator

This coding style is confusing.

Let's unravel the line of code in question:

self.currentDog >>> getWalks >>> getWalkAtIndex >>> setUpCell

What's happening here?  To make sense of this, we essentially have to read this backwards.

What are we doing?  We're setting up a cell.

With what information are we setting up the cell?  The walk at index.  (What index?  Well, the function has a bad name...)

What collection are we looking through for this index?  The one returned by "get walks".

And what does that return?  self.currentDog.walks

If we were to code this more normally, it'd look more like this:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell",
    forIndexPath: indexPath) as UITableViewCell

let currentWalk = self.currentDog.walks[indexPath.row];

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .MediumStyle

cell.textLabel.text = dateFormatter.stringFromDate(currentWalk.date)

This is fewer lines of code.

This is going to be less confusing to your average Swift programmer.  Swift programmers aren't very likely to be functional programming types.

Ultimately, the biggest problem here is that the operator you've created relies on the left hand argument being the argument for a function on the right hand side.  Which means in order to use this, we have to invent lots of very specific functions that are very specific toward the objects we have.

For example, the getWalks function is only usable on Dog objects and it simply returns the walk array.

Why would I ever want to do dog >>> getWalks when I can just do dog.walks?

And truly, should this operator be different somehow?  The dog isn't getting the walks.  We're applying the getWalks function to the dog.  dog <<< getWalks makes more sense.  The arrows point to the object we're getting walks of.  However, I actually like getWalks >>> dog better.  This reads better if we say "of" in place of the arrows.

"Get walks of dog"

And it looks more like a function we'd write.

getWalks(dog)

And that feels more like functional programming.

But the problem is when we start inventing functions that aren't reusable and end up extending the lines of code we write just for the sake of using an operator.  Moreover, these are functions that don't even take in the necessary number of arguments.

Isn't indexPath.row a value that should be passed into getWalkAtIndex?  The easiest, clearest thing to do would just treat the returned walks array as what it is... an array... and get the object at index the same way you would anyway... but if you insist on a function, then the function should be more like this:

getWalk(walks: NSOrderedSet index atIndex:NSInteger) -> Walk? {
    return walks[index] as Walk?
}

And we should call it as such:

getWalk(walks atIndex:indexPath.row)

We shouldn't require an NSIndexPath when we're only going to use the .row property of it.  And we really shouldn't be reaching outside of the function at what is effectively a global variable as far as this function is concerned.

Some of the same can be said for the setUpCell function.  Although truly, this should be a function.  We don't need a function to set a cell's text label's text property.

The function should be to format the date string.  And it should simply take an NSDate object and return a string.

So we'll have:

cell.textLabel.text = formatDate(walk.date)

At the end of the day though, Swift is an object oriented language.  If you're writing Swift, you're using all of the Apple libraries, frameworks, etc.  And that means you're using a lot of stuff that was designed for OOP.  And unless you intend to write a function sister to match your pattern for all of these existing methods for all these classes, then any code you write using this operator is going to be a hodge-podged mix of styles that will be confusing to people expecting OOP.


Simple and efficient data structure for standard deviation queries in Java

Overall I don't see any major problems with the code. There are some things I would change though:

Write unit tests.

Whenever I deal with mathematical classes, I think that it is obligatory to provide unit tests to verify correct computation and computational precision.

Add JavaDoc

Please add a JavaDoc to clarify whether it computes sample or population statistics.

Add comments

The use numberValue instead of number in the look ups to countMap has a significant but subtle difference that is easy to miss if you're not an expert. I would add comments to clarify this (you are correctly avoiding Integer(3) and Double(3) getting different counts).

Use map.getOrDefault

Since Java 8, which we have to assume is wide spread by this point, you can replace:

    Integer count = countMap.get(numberValue);

    if (count != null) {
        countMap.put(numberValue, count + 1);
    } else {
        countMap.put(numberValue, 1);
    }

with

    countMap.put(numberValue, countMap.getOrDefault(numberValue, 0) + 1);

Consider handling NaN and Inf inputs

Currently your code will silently break if any of the inputs contain NaN or Infinity. I would consider testing for these inputs and throwing if they are encountered.

Return type of remove is weird

As far as I can tell remove will return the input value or NaN if the input value was not removed. To me this feels very strange, I would much rather it'd return true if the statistics changed and false otherwise.

Change API to use double instead of Number

Currently your methods like public void add(Number number) first unbox the number into a double then rebox it into a Double. So calling add with a Double causes unnecessary boxing and unboxing.

Further more calling add with any of the primitive types (int,long,float etc) causes first a boxing to Number, then an unboxing to double then a re-boxing to Double (to use in countMap.get). This is a lot of unnecessary boxing and unboxing and will also generate a compiler warning on many systems.

So I would change:

public void add(Number number) {
    double numberValue = number.doubleValue();
    Integer count = countMap.get(numberValue);

    if (count != null) {
        countMap.put(numberValue, count + 1);
    } else {
        countMap.put(numberValue, 1);
    }

    sum += numberValue;
    squareSum += numberValue * numberValue;
    numberOfElements++;
}

to:

public void add(double number) {
    // JIT will use CSE to consolidate the auto boxings of number.
    countMap.put(number, countMap.getOrDefault(number, 0) + 1);
    sum += number;
    squareSum += number* number;
    numberOfElements++;
}

public void add(Number number){
    add(number.doubleValue());
}

and similarily for remove.

I would prefer to use the primitive double in the API because more often than not the user will do some computations to end up with the input value and will thus have a primitive double that they want to pass in. Other primitive types will automatically be type promoted to double. In the odd case that the user actually has a Number of some sort, we add an overload to handle it.

Add methods for querying the count and mean as well

You have all the data to get the mean value and sample count as well and these are commonly used in conjunction with the standard deviation so to me it makes sense to provide these methods as well as they are trivial.

Edit/Addendum

I would consider leaving the validation of removed values to the user. By having the countMap you add \$O\left(n\right)\$ memory requirement even if the user doesn't need the remove ability. And in many cases where you do need a remove (like a sliding window) the removal is guaranteed to be valid by the definition of the window.


Lookup class to get descriptions of values

Getting a distinct list from MySQL would slow things down quite a bit, I wouldn't do that.

Perhaps you're overdoing it a bit? Yes, it is always good to filter user input, but I would do that at the point where this input arrives in your application, not in each class inside the application. You are already binding the parameters, which secures the database against injection. Anything apart from what's in your database will result in false, which might be better behaviour than throwing an exception.

So the protection is in the binding of the parameters, and not really in the validation.

Talking about validation. There might be a perfectly good reason to insert all that code. Regretably your validation is incomplete. If I give your method a $lookup_value of 10 it will just return false. That might be a real value, or a sign that the value doesn't exist. You would normally use null in these cases, which is what you do when the query fails.

So my suggestions are:

Filter user input, perhaps with static arrays, directly at the point
of entry. So at the point where you get user input out of $_POST,
$_GET, or anything else. Try to be as strict as possible. When a
value doesn't meet all the criteria, give feedback and allow the user
to enter a correct value. Never let an user freely enter values into
your application in the (false) assumption that the application will
deal with any abnormal values all by itself: It won't. You will
eventually make mistakes.
Keep the validation inside your application very simple and flexible,
this will make it easier to read, modify, and understand the code.
The validation is there to support you to debug your application, it
should not be relied upon as a security feature.
Always bind parameters, of course.

Something like this:

function getLookup($lookup_type,$lookup_name,$lookup_value)
{
  // checking type of arguments
  if (!(is_string($lookup_type) &&
        is_string($lookup_name) &&
        is_int($lookup_value))) {
    throw new InvalidArgumentException('Invalid arguments in Lookup->getLookup().');
  }
  // select a description of ???
  $query = 'SELECT lookup_description
            FROM Lookup
            WHERE lookup_type  = :lookup_type AND
                  lookup_name  = :lookup_name AND
                  lookup_value = :lookup_value
            LIMIT 1';
  try {
    $statement = $this->pdo->prepare($query);
    $statement->bindParam(':lookup_type', $lookup_type);
    $statement->bindParam(':lookup_name', $lookup_name);
    $statement->bindParam(':lookup_value',$lookup_value);
    $statement->execute();
    // return any results
    if ($statement->rowCount() > 0) return $statement->fetchColumn();
  }
  catch (PDOException $exception) {
    error_log('Database error in Lookup->getLookup(): '.$exception->getMessage());
  }
  // failure: no results or database error
  return null;
}

While I was writing this code I noticed that you're using strange names in your database: A Lookup table, containing columns like lookup_name. From these names I get no idea what the content of that table is. The names describe the functions in PHP and not their meaning. A database should be comprehensible on its own, without any code operating on it.

PS: Perhaps someone told you to validate the arguments of your method thouroughly. I cannot help that, this happens when many people can give advise.


Notification system using PHP+jQuery+Ajax

JAVASCRIPT SECURITY
Javascript is running on the client, and is therefore under full control of the user. It can be disabled, inspected, manipulated, and everything else that can done in a programming language. You knew this, didn't you?
Javascript is, almost by definition, insecure. Things that have to do with the security of your site, like validating passwords, should not be done in Javascript. And in your code you don't do anything security related in Javascript. All you do is set a timer running and call two PHP scripts. No risks there.

PHP SECURITY
The PHP scripts are another matter. Here is where things really happen, and you should implement your security measures here. Even though these scripts implement AJAX calls, they can be executed by anybody.
You seem to have users, that can log in. Their user ID is stored in $_SESSION['userid']. I notice that you don't do anything, in your PHP scripts, when this ID is absent. You still execute the database queries. That is a bad idea.
When the two current PHP scripts are called, without an user ID, they will probably just perform database queries that are invalid. No real harm done. But you shouldn't rely on just pure luck. Good security should leave no doubts about what will happen.
I therefore propose I slight change to your code. Instead of writing this:
if (isset($_SESSION['userid'])) {
  $userid = $_SESSION['userid'];
}

you could write this:
if (!isset($_SESSION['userid'])) die('Not logged in.');
$userid = $_SESSION['userid'];

this means that the PHP scripts will halt execution when there's no user, as they should.

PERFORMANCE
You code is evidently not very efficient. Polling the database every second does not scale very well. There are other ways to do this. For instance with web sockets: https://developer.mozilla.org/en-US/docs/Web/API/Websockets_API ( you would use a combination of the tools mentioned there). Updates will be quicker, without polling.
For now polling will probably be fine for you, after all you're still learning Jquery and that is a challenge in itself. It takes time to understand how everything hangs together.


Implementation of an OkHttp singleton for Android

You don't need to create new instance of OkHttpClient. Remove it.
You can use Initialization-on-demand holder pattern to create singleton in Java. No need to use synchronized block
Change coding style in your code. Remove m before instance variable. See naming convention.

Here is the code:

public class OkSingleton extends OkHttpClient {
    private static class LazyHolder {
        private static final OkSingleton instance = new OkSingleton();
    }

    public static OkSingleton getInstance() {
        return LazyHolder.instance;
    }
}


Could be simplified

For what you are doing, using a mutex and a condition variable is more complex than necessary.  You could just use a semaphore or signal instead.  A mutex should guard some shared variable or state, but your code doesn't have any.  Instead, you are using the mutex + condition variable simply to wake up another thread.

As far as your implementation goes, I have the following comments:

A loop containing pthread_cond_wait() should always check a predicate variable to guard against spurious wakeups.  This is in the documentation for pthread_cond_wait().  So for example:

pthread_mutex_lock(&count_mutex);
while (count == initialCount) {
    pthread_cond_wait(&count_threshold_cv, &count_mutex);
}
// Do something here...
pthread_mutex_unlock(&count_mutex);

The loop doing the work should lock the mutex for as short a time as possible.  You only need to hold the mutex when you want to access shared variables.  So for example:

for (;;) {
    // Do this long work outside of the mutex
    int countnow = getDirFileCount();

    if (countnow > initialCount) {
        // Only lock the mutex when you need to actually need to access
        // shared state (in this case the variable "count").
        pthread_mutex_lock(&count_mutex);
        count = countnow;
        pthread_cond_signal(&count_threshold_cv);
        pthread_mutex_unlock(&count_mutex);
        return;
    }
}


JavaScript function for printing a countdown

Try this:

var time_format = (function() {

    var names = "yr mo w d h m s".split(" ");

    return function(time) {
        var elms, ret, i, n;
        elms = [
            time / 29030400,
            time / 2419200 % 12,
            time / 604800 % 4,
            time / 86400 % 7,
            time / 3600 % 24,
            time / 60 % 60,
            time % 60
        ];
        ret = [];
        for( i=0; i<elms.length; i++) {
            n = elms[i];
            n = n | n;
            if( n) ret.push(n+names[i]);
        }
        ret = ret.join(" ");
        if( ret == "") ret = "0s";
        return ret;
    }
}());

It moves the array initialization out of the function and into a closure so it's only evaluated once.

And, it uses a faster way to do the floor operation.  See this article for different ways to do floor and their timing.


Removing duplicates from a file containing IP addresses

For all practical reasons, you should

    > sort in.csv | uniq > out.csv

from the command line, unless the goal is the programming exercise.

As mentioned in the comments, the bottleneck is a linear search over the list of encountered IPs. It drives time complexity quadratic. Sorting is a way to reduce the complexity.

If the file is indeed too large to fit into RAM (which I seriously doubt; these days 13M records shouldn't be a problem), use an external sort (merge works the best). You can also greatly reduce the memory consumption by keeping IPs as numbers (4 bytes per IP), instead of strings:

    in_addr_t addr;
    while(fgets(line, sizeof(line), in)) {
        bool rc = inet_aton(line, &addr);
        if (!rc) {
            // Deal with malformed address
        } else {
            // Business as usual. Work with addr.
        }
    }


React.js hook to move a car on a 5×5 board

I'm trying to address the same issue.
What I'm currently doing is splitting my big hooks into smaller hooks, each with a single responsability.

For example, in your example, you could split your onKeyDown, rotateRight and rotateLeft functions into a hook which takes a state with values and setters as only parameter:

const useCarRotation = state => {
  const changeDirection = direction => {
    if(direction === -1) {
        state.setDirection(3)
    } else if(direction === 4) {
        state.setDirection(0)
    } else {
        state.setDirection(direction)
    }
  }

  const rotateLeft = () => {
    state.setDegrees(state.degrees - 90)
    changeDirection(state.direction - 1)
  }

  const rotateRight = () => {
    state.setDegrees(state.degrees + 90)
    changeDirection(state.direction + 1)
  }

  const onKeyDown = e => {
    switch (e.which) {
      case 37: // Left
        rotateLeft()
        break
      case 38: // Up
        move()
        break
      case 39: // Right
        rotateRight()
        break
      default:
        break
    }
  }

  return {onKeyDown, rotateLeft, rotateRight};
}

You can then use it in your main hook like this:

const useController = () => {
  const directions = [
    {x: 0, y: -1, degrees: 0}, // up
    {x: 1, y: 0, degrees: 90}, // right
    {x: 0, y: 1, degrees: 180}, // down
    {x: -1, y: 0, degrees: 270}, // left
  ]
  const [initiatedGame, setInitiatedGame] = useState(false)
  const [degrees, setDegrees] = useState(0)
  const [direction, setDirection] = useState(0)
  const [position, setPosition] = useState({'x': 0, 'y': 0})
  const [carPlaced, setCarPlaced] = useState(false)

  const chooseDirection = direction => {
    setDirection(direction)
    setDegrees(directions[direction].degrees)
    setInitiatedGame(true)
  }

  const move = () => {
    const root = process.env.REACT_APP_API_ROOT
    const {x, y} = directions[direction]
    axios.post(`${root}/move`, {
        x: position.x + x,
        y: position.y + y
      })
      .then((response) => {
        if(response.data.valid) {
          setPosition({x: position.x + x, y: position.y + y})
        }
      })
  }

  const placeCar = (x, y) => {
    if(!carPlaced) {
      setCarPlaced(true)
      setPosition({x, y})
    }
  }

  const {onKeyDown, rotateLeft, rotateRight } = useCarRotation({
    degrees,
    direction,
    setDegrees,
    setDirection,
  })

  return {
    rotateLeft,
    rotateRight,
    move,
    degrees,
    position,
    placeCar,
    carPlaced,
    chooseDirection,
    initiatedGame,
    onKeyDown
  }
}

To take your example further, I believe the chooseDirection and placeCar function could be placed in a hook responsible for initializing your values.

I currently keep all useState and useSelector calls into my main hook but I guess they could be put into a separate hook too if you have a lot of them.


Removing stray brackets from in between shortcodes

You can simplify and improve this part:

$pattern = '/\[('.$k.'.*?(?=\]))\]/';
$content = preg_replace($pattern,'*{*$1*}*',$content);
$pattern = '/\[\/('.$k.'.*?(?=\]))\]/';
$content = preg_replace($pattern,'*{*/$1*}*',$content);

Instead of using two replacements for [k] and [/k],
you can add the /? inside the capture group and use a single replacement:

$pattern = '/\[(\/?'.$k.'.*?(?=\]))\]/';
$content = preg_replace($pattern,'*{*$1*}*',$content);

This regex can be still improved. Is the positive look-ahead really necessary?
It seems to me that this should do the job just as well:

$pattern = '/\[(\/?'.$k.'.*?)\]/';

On the other hand, this is not very strict. For example,
if you have shortcode gallery, then [galleryzzz] will also match and not be treated as "stray brackets". Maybe that's fine with you, but in any case,
it's easy to prevent that by adding a zero-width word boundary check:

$pattern = '/\[(\/?'.$k.'\b.*?)\]/';


Empty Line delimiter, single line output

I don't really see why you used two scanners instead of just one.
And I also don't see the need for a custom delimiter.

You can use a simpler alternative logic:

Process line by line
If the line is not empty, append it + a space
If the line is empty

Print the content buffer, except the last charater (the extra space)
Reset the buffer

At the end, if the buffer is not empty, print its content, except the last character

That is:

StringBuilder sb = new StringBuilder();

while (input.hasNextLine()) {
    String line = input.nextLine();
    if (!line.isEmpty()) {
        sb.append(line).append(' ');
    } else {
        System.out.println(sb.substring(0, sb.length() - 1));
        sb.setLength(0);
    }
}
if (sb.length() > 0) {
    System.out.println(sb.substring(0, sb.length() - 1));
}

An easy way to "test" this is by instantiating a Scanner with a string containing newlines:

Scanner input = new Scanner("Bubbles,\n" +
        "Blossom and\n" +
        "Buttercup\n" +
        "\n" +
        "Nostalgic\n" +
        "Examples for the\n" +
        "Win.\n" +
        "\n" +
        "Quick Brown Fox\n" +
        "Jumping Over Lazy\n" +
        "Dog.");

I don't know a simpler way to do this.
But I have some ideas for possibly interesting variations you could try, for example:

Instead of collecting lines in a buffer, print as you go. That will save you memory usage. To track whether to put a space or not, you would need a flag of some sort. (A simple boolean would do.)
Instead of printing paragraph by paragraph, let the buffer grow and print at the very end. This uses more memory, but it will make the implementation properly testable, as you could return the buffer, which can be used by unit tests.

Both alternatives have advantages and disadvantages.
The simplified version I gave you above is somewhere in the middle.


How can I not mess up the global scope?

You can use an IIFE ( Immediately Invoked Function Expression ) to surround your code and then assign all your variables with var <- Very important.

(function(){

  var quicksearch = document.getElementById('quicksearch_top');
  var comment = document.getElementById('comment');

  var severity = document.getElementById('bug_severity');
  var priority = document.getElementById('priority');

  var commit_top = document.getElementById('commit_top');
  var commit = document.getElementById('commit');

  //the rest of your code here

}());

  How should I use functions (in var or not)?

It really is up to you, at this point I prefer function.

Other than that:

You should use lowerCamelCasing, so

commit_top -> commitTop
quicksearch -> quickSearch
selectelement -> selectElement

etc.etc

Your keycode map is very nice, keep it that way!

One last comment is that you should not use document.onkeydown = navigation;, there is a good chance that you will break something this way.

Try document.addEventListener("keydown", navigation, true); instead.


Calculate amount of elements in collection by property

That looks quite fine to me. You can remove the parentheses around e in the arrow function.

If you're really going for efficiency, a regular for loop is faster than the .forEach() method. That can help if you have a very large amount of objects to process and need to display a result instantly to a user, but otherwise the optimization is unnecessary for what you're trying to accomplish.


Accessing MySQL to make queries and scalars

Question #1

No. You do not need to ref the connection object in your methods' parameters - think object oriented way not class oriented.

Question #2

The only way is to make this as a non static class. Avoid always statics when the current problem contains some kind of state management like a MySQL connection.

Question #3

No you don't but you should implement the IDisposable interface and apply the correct disposable pattern.

public class MySQLGear : IDisposable
{
    private readonly MySqlConnection _connection;

    public MySQLGear(string connectionString)
    {
        _connection = new MySqlConnection(connectionString);
    }

    protected MySqlConnection Connection()
    {
        if (_connection == null)
        {
            throw new ObjectDisposedException("The underlying connection has been closed");
        }

        if (_connection.State != ConnectionState.Open)
        {
            _connection.Open();
        }

        return _connection;
    }

    public MySqlDataReader GetReader(string queryMysql)
    {
        using (var cmdMysql = new MySqlCommand(queryMysql, Connection()))
        {
            return cmdMysql.ExecuteReader();
        }
    }

    public int MakeQuery(string queryMysql)
    {
        using (var cmdMysql = new MySqlCommand(queryMysql, Connection()))
        {
            return cmdMysql.ExecuteNonQuery();
        }
    }

    public object MakeScalar(string queryMysql)
    {
        using (var cmdMysql = new MySqlCommand(queryMysql, Connection()))
        {
            return cmdMysql.ExecuteScalar();
        }
    }

    ~MySQLGear()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_connection != null)
        {
            if (_connection.State != ConnectionState.Closed)
            {
                _connection.Dispose();
            }
            _connection = null;
        }
    }
}


There's not a lot to say about such a simple program, mainly nitpicks.

You are violating PEP8 at a few places.
The code reformatted to follow PEP8 would look like this:

def my_crawler(url, max_pages=1, max_items=1):
    for page_number in range(1, max_pages + 1):
        source_code = requests.get(url + str(page_number)).text

        products = SoupStrainer(class_='productTags')
        soup = BeautifulSoup(source_code, 'html.parser', parse_only=products)

        for item_number, a in enumerate(soup.find_all('a')):
            print(str(item_number) + ': ' + a['href'])

            if item_number == max_items - 1:
                break

In particular:

Write method parameters compactly as max_pages=1 instead of max_pages = 1
Break line after :

Instead of range(1, max_pages + 1) I would find range(max_pages) simpler if you only need to do max_pages + 1 in the code. So I'd rewrite the above as:

for page_number in range(max_pages):
    source_code = requests.get(url + str(page_number + 1)).text

And as a mild case of paranoia,
I'd prefer the if statement for breaking out of the loop this way:

if item_number >= max_items - 1:
    break

And yes, it's fine to break out of the loop this way.
I don't think there's a better way.

When you print the item number and the link,
I think this is slightly more readable:

print('{}: {}'.format(item_number, a['href']))

Finally, don't execute code in global scope,
it's recommended to wrap code in an if __name__ == '__name__': guard:

if __name__ == '__name__':
    my_crawler('http://www.thesite.com/productResults.aspx?&No=')

These are mainly just nitpicks though. You're doing fine.


Efficient loop over a integer range in Python

I think that having a range is not necessary here. If you're only comparing against integer ranges, simple \$ \le \$ and \$ \ge \$ comparisons should suffice.
So, the following function is essentially the same:
def search_position(ranges, positions, window_size=10000):
    for low, high, range_id in ranges:
        for pos in positions:
            if low <= pos < high:
                print(pos, range_id, 'exact hit!')
            elif (low - window_size) <= pos < (high + window_size):
                print(pos, range_id, 'neighbour hit!')


Given time intervals, find the minimum number of conference rooms required

The code looks much simpler than I would expect for this task. I tried several examples but could neither make it fail, nor did I understand why and how this algorithm works, I was only delighted that it seems to work. Therefore I have only a few remarks.

The early return for length <= 1 is not necessary.

The ++rooms is missing the semicolon.

Apart from that, it looks perfect.


Looping through a string finding nested brackets

I'm not sure how viable this would be when looking up against large strings with lots of nested brackets [...]

"how viable" is a very vague question.
Two common performance metrics are CPU load and memory load,
perhaps that's what you were trying to get at.
It's good to clarify what exactly you want to know.

In terms of CPU, how will this program behave as the input grows?

The algorithm does a single pass over all characters of the input.
When the input doubles, the number of operations doubles, roughly.

=> In other words, it's linear.

Can it be any better than linear?

=> No, because we cannot know the positions of the brackets without looking through each character once.

In terms of memory, how will this program behave as the input grows?

Aside from the memory used by the input string,
what consumes memory in this program?

=> The dictionary storing the starting positions of brackets.

How do brackets on the same nesting level impact the memory consumption?
That is, in a string like [][][][]?

=> Since the storage for a [ is removed when the corresponding ] is found, brackets at the same nesting level use a single entry in the dictionary.

How do deeply nested brackets impact the memory consumption?

=> The dictionary has as many entries as the deepest nesting level. As closing brackets are found, entries get deleted. The maximum memory consumed by the dictionary throughout the program is proportional to the maximum depth of nesting encountered.

  So how could this be improved, especially in terms of memory (i.e. large strings)?

The current performance of the program is on the expected order of complexity, so it's fine.
However, a dictionary is not the most natural choice for this purpose,
and its actually overkill.
A simpler data structure, a stack, would have been enough to solve this.
Instead of storing (depth, index) pairs in a dictionary,
you could store just index in a stack:

When you see a [, push the index onto the stack.
When you see a ], pop the last pushed index from the stack.

The result will be equivalent, the depth variable becomes unnecessary.


Extension for grouping array into two dimensional array based on element ([] -> [[]])

That looks like a clean implementation to me. One minor thing: I find it more
natural to assign the new index before the group array is extended,
so that you don't have to subtract one:

indexKeys[key] = grouped.count
grouped.append([element])

The Swift standard library defines many methods for the Sequence protocol and not
for concrete sequences like Array, examples are map, filter, min/max, contains ...

You can do the same with your method to make it more universally applicable:

extension Sequence {
    // ... no other changes necessary ...
}

However: You are essentially reinventing the wheel. In Swift 4 there is a
Dictionary(grouping:by)
method which does almost what your code does, only that a dictionary is returned:

let groupedThings = Dictionary(grouping: things, by: { $0.category } )
// [String : [Thing]]

The keys are the categories, and the values are arrays of corresponding things. With

Array(groupedThings.values)

you get a nested array which (apart from the order) is identical to what your method
returns.


Extracting contents of dictionary contained in Pandas dataframe to make new dataframe columns

I suspect the try-except in the loops are the main cause of the slowness. It's not clear at which point you get ValueError due to "funky" data. It would be good to clean that up, get rid of the try-catch, and I think your solution will get noticeably faster.

Another small thing, that might not make a noticeable difference at all, you have some repeated lookups, like in this snippet:

if g.get('weather'):
    for name in weather_list:
        if g.get('weather').get(name):

Here, the g.get('weather') bit is executed twice. It would be better to save the result of the first call, and then reuse that. Apply this logic to other similar places. Although it might not make a practical difference, avoiding duplicated logic is a good practice.


The formatting of your code is broken, so I've reproduced it here for clarity.

union' :: (Eq a) => [a] -> [a] -> [a]
union' xs ys = xs ++ union'' ys xs
    where union'' [] _         = []
          union'' (a:as) first = if (a `elem` first) then union'' as first else a : union'' as (a:first)

Your code is correct, but can be rewritten to exhibit better style.

module MyUnion where

import qualified Data.List as List (union) -- For testing with QuickCheck

union :: (Eq a) => [a] -> [a] -> [a]
union xs ys = xs ++ union' ys xs
    where union' []       skips                   = []
          union' (y':ys') skips | y' `elem` skips =      union' ys'     skips
                                | otherwise       = y' : union' ys' (y':skips)
                             -- ^ Guards instead of ifs
                                               -- ^ Aligned for readability

prop_equal xs ys = union xs ys == List.union xs ys -- QuickCheck-able property

Good Haskell style also involves using higher-level functions whenever other considerations don't require otherwise (e.g., performance, comprehensibility). Here's my version of union, note that it looks much more like your version from before the edits.

union xs ys = xs ++ filter (`notElem` xs) (nub ys)

For reference here is the definition of unionBy from base (union is defined as unionBy (==)).

unionBy                 :: (a -> a -> Bool) -> [a] -> [a] -> [a]
unionBy eq xs ys        =  xs ++ foldl (flip (deleteBy eq)) (nubBy eq ys) xs


This is a review of the initial code that was posted. Unfortunately, I don't have time to revise it now for the new code.

Wanting to lessen the number of methods in a class is on its own a poor reason to split up a class into multiple. Classes can have many methods, and we can use IDE functionality and good documentation to make sense of a class.

Having many methods can suggest though that the class is doing too much, and that would be a more logical justification to split the class up. A better thing to think about is not the size of the class, but what the job of the class is, and if it's doing too many things.

That said, if you feel like it's justified to split it, I wouldn't do it as you have here. You've given the entire state of the Greeter object to Spanish. If Spanish begins using a lot of the state in Greeter, you now have two tightly coupled classes that will begin to break as you make changes to either.

Just give Spanish the information that it explicitly needs:

class Spanish:
    def __init__(self, name):
        self.name = name

    def hola(self):
        return f"Hola, {self.name}"

    def buen_dia(self):
        return f"Buenos días, {self.name}"

And

class Greeter:
    def __init__(self, name):
        self.name = name
        self.spanish = Spanish(name)  # And just pass the name
    . . .

This setup really doesn't make sense though. To get a greeting in Spanish, you need to access an object that greets in English? Even combined it doesn't make much sense. Having an object that greets in multiple languages seems odd. It would make more sense to have completely discrete classes that don't know about each other.

With a toy example like this though, it's really hard to make a concrete suggestion because the actual intent isn't clear. The textbox that I'm writing the answer in is also bugging out, so I'm going to submit this before I lose everything.


Your code is buggy and can quickly invoke undefined behavior.

The function tolower must not be called with a char directly, its argument must be cast to unsigned char first. Read the tolower documentation for details.

bool is_vowel(char chr) {
    int lower = tolower((unsigned char)chr);
    return strchr("aeiou", lower) != NULL;
}

In the part that counts the vowels from stdin, you have a serious bug. You read a large buffer and then check the whole buffer for vowels. But you must only check the part that you have actually read, which can be less.

To demonstrate, create a file of size 1025 that is filled with vowels. Your program will count 2048 vowels in that file. Or even more if you are unlucky. Or it crashes. Now that's what undefined behavior means.

To fix this, remove all the buffering code from your program. Instead, read the input one byte at a time:

size_t count_vowels_in_file(FILE *f) {
    size_t vowels = 0;
    int ch;   // It's important to use "int" here, not "char" or "unsigned char".
    while ((ch = fgetc(f)) != EOF) {
        if (is_vowel(ch)) {
            vowels++;
        }
    }
    return vowels;
}

This code is much simpler than reading buffers, and it is almost as fast, since stdin is already buffered.

In short, you didn't test your code well. Code that reads data must be tested with empty input, short input, long input, random input.

To get comparison data, you can use the following shell command:

tr -cd 'AEIOUaeiou' | wc -c

These commands read from stdin. The tr command deletes all characters except the vowels, and the wc command counts the remaining characters, which are all vowels. For every input file, your C program should produce the same result as the tr | wc command combination.


If you have to identify the main objects here, we could conclude that you have at least 3

-- The connection to the DataBase

-- The pagination object that knows how to paginate a query

-- The query it self

so ie this is a possible solution:

abstract class DBConnection{
    //Logic
    public function executeQuery(Query $query)
    {
        $sql = $query->getSql();

        //Logic and return results
    }
}

class Query{
    private $sql;
    private $limit;
    private $offset;

    //getters and setters for each private property ... getSql ... setSql ...

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

    public function getSql()
    {
        return $this->sql += "offset $this->getOffset() limit $this->getLimit()";
    }
}

class Paginator
{
    private $currentPage;
    private $perPage;
    private $query;
    private $connection;

    //Getters and setters...

    public function __construct(Query $query, $currentPage = 0, $perPage = 10)
    {
        $this->query = $query;
        $this->connection = new DBConnection();
    }

    public function nextPage()
    {
        $this->currentPage++;
    }

    public function prevPage()
    {
        $this->currentPage--; //check if 0 not substract
    }

    public function execute()
    {
        $this->query->setOffset($this->currentPage * $this->perPage);
        $this->query->setLimit($this->perPage);
        return $this->connection->executeQuery($this->query);
    }
}


I would not use Chain of Responsibility to solve this problem. For every request, a single handler is chosen based on the same property: it's output format. For that you can use a simple dispatch table: a dict mapping each output format to its handler. There's no point asking each handler if it can handle the request.

Update: As usual, the Portland Pattern Repository has some good historical discussion of this pattern, specifically when not to use it:

  Do not use Chain of Responsibility when each request is only handled by one handler, or, when the client object knows which service object should handle the request.

Note: Report and ReportFormat are unchanged from the OP and omitted for brevity.

class ReportDispatcher(object):
    def __init__(self):
        self.reports = {}

    def add(self, report):
        self.reports[report.format] = report;

    def handle(self, request):
        report = self.reports[request.format_]
        if report:
            report.handle(request)
        else
            print "Invalid request"

class Handler(object):

    def __init__(self, format):
        self.format = format

    def handle(self, request):
        print "subclass responsibility"

class PDFHandler(Handler):

    def __init__(self):
        super(PDFHandler, self).__init__(ReportFormat.PDF)

    def handle(self, request):
        print ''
        print '  '
        print '    <title>%s</title>' % request.title
        print '  '
        print '  '
        for line in request.text:
            print '
%s
' % line
        print '  '
        print ''

class TextHandler(Handler):

    def __init__(self):
        super(TextHandler, self).__init__(ReportFormat.TEXT)

    def handle(self, request):
        print 5*'*' + request.title + 5*'*'
        for line in request.text:
            print line

if __name__ == '__main__':
    reports = ReportDispatcher()
    reports.add(PDFHandler())
    reports.add(TextHandler())

    report = Report(ReportFormat.TEXT)
    reports.handle(report)

As you can see from the main method, sending a report request is completely decoupled from the various report handlers. Instead, the request is sent to the dispatcher which knows about the handlers.