Distribute items based on the time duration

Nice implementation, it's well structured and easy to understand. Few general suggestions:

int instead of long: the constants MORNING_SPAN and AFTERNOON_SPAN contain minutes in a day, using an int is enough.
Input validation: the talk duration needs to be validated. If the talk duration is greater than MORNING_SPAN or AFTERNOON_SPAN it won't be included in any track. If it's negative it will also lead to issues. In the Conference class ensure that the list talks is not empty.
Creating the schedule: I see that the schedule is created (lazily) in the displaySchedule method of Conference. I think that creating the schedule is an important action, it can be the responsibility of another class, like ScheduleMaker. Then, the list of tracks can be added to Conference in the constructor.
Talk interface: talk.duration returns a string like "30min", while talk.duration() returns 30 as a long. I find it a bit confusing. If you need both, consider creating two different variables and two getters. Otherwise, parse the duration in the constructor and use only the long value.

Bin packing problem
Let's consider this example:
morning_span = 2m (2 minutes)
afternoon_span = 1m
daily_span = morning_span + afternoon_span = 3m

talk1 = 2m
talk2 = 2m
talk3 = 2m
total_talks_duration = 6m

Calling conference.makeSchedule() will result in:
numberOfTracks = total_talks_duration / daily_span = 6 / 3 = 2

Schedule:
Track1 = talk1 (morning)
Track2 = talk2 (morning)
talk3 ??

As you can see the current makeSchedule will create two tracks, but talk3 won't be included.
This bug can be fixed by running the other loop till all the talks are placed:
private void makeSchedule() {
    while (talks.size() > 0) {
        // Create a new track
        // Add in the track as many talks as possible
        // Remove talks added to the current track
    }
}

Now all talks will be placed in the tracks, however, there are cases where the algorithm will create more tracks than needed. This is considered a Bin packing problem. Basically, fit the talks in the minimum number of tracks. Interestingly, my university professor developed an exact algorithm for this problem (pdf). I'll leave it to you for additional study.


One-dimensional circular Conway's Game of Life

Here is an idea to speed things up, given that the input is only 15 numbers:

Since the numbers are binary, you could represent the board as a bitmask in an integer instead of an array (see wikipedia/masks).
There are only \$2^{15}\$ possible states. You could create a Map<Integer, Integer> from each state bitmask to the next. Then each iteration in your algorithm is gonna be a simple map lookup.

There are more optimizations you could to make it even faster, but this should be enough.


Conway's Game of Life command line program in C++

Overall, this is pretty good. You've avoided the most common mistakes I see, like bad naming, using magic numbers, passing bare values that really belong together in a data structure. Nice job! I appreciate the comment at the top that explains the rules, too.
To answer your question, I think that using the extra rows and columns is a great idea. They're 2 characters per row, and 2 extra rows. It's not a lot of memory, and it makes the code much cleaner.
Here are some thoughts on some things that could be improved.
Avoid Globals
Your game board is a global variable. You've structured the code nicely, so it only ever gets modified in generation(), but small programs have a tendency to become large programs, and global variables in large programs have a tendency to get modified all over the place. I'd move the grid variable into main() and pass a reference to it into the various functions that use it.
Always Name Your Arguments
Your definition of the sleep() function looks like this:
void sleep(int);

What is the int? A function prototype with unnamed arguments is close to useless. Now I have to read through the function to get any useful information about what the parameter means. If it was named something like iterations or time like in the actual function it would be infinitely better.
Things in main()
The gen variable is set up, and it's incremented, but it's never checked. It's just busywork for your CPU. If you were going to use it to bail out of the loop after so many iterations, it would be useful, but you've made an infinite loop. So I'd just get rid of it.
You're using std::endl at the end of every line you print. That's pretty heavy-weight. It flushes the output buffer. I'd say in most cases you want to just use "\n" instead. Maybe you could use std::endl after printing the last character of the board.
Your command to clear the screen is non-standard. My system doesn't have a command named cls on it, so that just outputs an ugly error message. I don't do a lot of console programming, so I'm not sure if there's a universal way to clear the screen, but you might look into ANSI escape codes.
The sleep() Function
Likewise, your sleep() function has some issues. There's a standard POSIX function named sleep() that is often used to sleep the process for an amount of time. I don't know whether it exists on Windows or not. But regardless of that, the way you've implemented it, it will sleep for a different amount of time on different machines. So a 1GHz machine will probably take twice as long to complete that loop as a 2GHz machine. You probably don't want that. I recommend finding a more standard method for performing sleep on your target system. Something that at least checks the clock rather than just counting.
According to the comments, you can use:
#include <chrono>
#include <thread>
...
std::this_thread::sleep_for(std::chrono::milliseconds(500));

setup_grid()
For the most part, setup_grid() looks pretty decent. If any errors occur, you will end up with a partially uninitialized grid, though. You might want to at least clear it all to DEAD_CELL to start with so you have something sensible in there. Better yet, if any errors occur, return them to the caller and let the caller decide how to handle them (tell the user, exit the program, whatever).
You don't need the file.close() at the end. The destructor for std::ifstream will call it for you when the function ends.
generation()
This function is pretty well written, too. I didn't have time to do timing trials, but I have to wonder if using the same grid for input and output is fastest? (Not that it matters given your sleep() function!) Another way to handle it would be to pass in 2 grids - the current state and the next state. Rather than noting which cells changed and then overwriting them, you'd simply fill in the new cells given the state of the old cells. It might be a wash, though. You could code it up and profile it to be sure.
There's nothing wrong with the set of if statements you have for checking the cells. In fact, some would argue that you've done loop unrolling which could theoretically improve performance. I think it would be easier to read, though, if it were done in a loop like this:
for (int cell_y = y - 1; cell_y < y + 1; ++cell_y) {
    for (int cell_x = x - 1; cell_x < x + 1; ++cell_x) {
        if (grid[cell_y][cell_x] == ALIVE_CELL) {
            neighbors++;
        }
    }
}

As noted, this will count the current cell, so you can subtract it out at the end with:
if (grid[y][x] == ALIVE_CELL) {
    neighbors--;
}

At the very least, you should avoid writing the condition and the statement it executes on the same line, as it makes it impossible to tell whether the statement executed or not when stepping through with a debugger. Not a big deal here, but it can be in larger programs, so it's a good habit to avoid putting it all on one line.
I recommend always using braces in if statements, even if they're only one line as that avoids another common error, which is adding a line to an if without realizing you didn't actually add it. Like this:
 if (someCondition)
    doSomething();
    doSomethingElse();

In this case, doSomethingElse(); will be called regardless of whether someCondition is true or false because there are no braces around the intended body of the if statement.


Running shell script as root via external binary

This is an ambitious thing to try, with many pitfalls - especially for environments which are Web-accessible.  I urge you to learn how to configure and use sudo instead - that's not foolproof, but it is a good deal safer than rolling your own.

That said, I'll make some observations:

We're using argv[1] without checking whether any arguments were supplied (we should test argc >= 2 before using argv[1] - possibly check argc == 2, since we ignore any extra arguments).
There's a time-of-check/time-of-use (TOCTOU) race, because we examine the supplied file and later assume the properties haven't changed (we we get to running it).
Using system causes the supplied argument to be parsed as a shell command, which will do word splitting, expand variables and globs, and more.
Using a shell script from a privileged program is vulnerable to the script being changed between the interpreter being started and it opening the script to read commands (e.g. by switching symlinks).

It's quite easy to exploit this script to execute anything I want on your system, if there's a directory I can write to:

ln -s /bin/true 'ls -l ~root; id; cd; echo rm -rf; true .sh'

/some/path/run-as ls*.sh

We can avoid using system() (and accept extra arguments if we choose), by using execv() instead:

            if (match && !strcasecmp(match, ".sh"))
            {
                execv(argv[1], argv+1);
                /* if we got here, exec failed */
                /* so fall through to return 1 */
            }

This does still leave us vulnerable to a user creating a symbolic link to a root-owned file and rewriting it to point to the user's file between the access check and the exec(), though.

In short: please use sudo if you really have to run some things as root.  Configured properly, it can give tight control on the commands you can execute with elevated privileges.  It's not completely attack-proof, but it is much better than writing your own (it has had decades of scrutiny to improve it).


is there a reason for $(which foo) ?

If foo is in your path, it will be found, if not which will give you an error.

Expressions like command will have a return code, so do not write

if [[ $(command -v "$dependency") = "" ]]

just use

if command -v "$dependency" > /dev/null
then ...


Write the HTML markup for several of (profile picture + message heading + message)

If it's all about semantic then let's see what HTML5 specs say (emphasis is mine):

  The article element represents a component of a page that consists of a self-contained composition in a document, page, application, or site and that is intended to be independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

In this case it seems that
 is an appropriate choice for your comments. Is it
 an appropriate container? I don't think it is, specs says:

  The section element represents a generic document or application section…The section element is not a generic container element. When an element is needed only for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element’s contents would be listed explicitly in the document’s outline.

I agree that interpretation can be little bit subjective here but I'd take it literally: you do not have a specific header for this section. In your case if
 is not to group a section of your document (for example an outer
 with its list of comments) then I'd use the good old
:

If, however, comments are just a part (section) of your main document which you may want to see in document outline and not simply a styling container (remember that it's important for screen-readers and all the others assistive tools) then don't refrain and use
.

Now let's talk about article content. You're using
 for styling purposes. I don't see whole page outline then I can't comment on this but keep in mind that heading elements should be used to denote an hypothetical structure, not for their styling. Imagine to replace your
Title
 with
Title
 where div.header is appropriately styled. Does the meaning of your document is lost? If answer is no then you're using heading elements because of styling and you shouldn't.

HTML5 introduced a new element  which may be appropriate in your case:

      ...

Note that even if you really want to keep  because of its meaning in document outline I'd wrap it inside an  section.

Title

What is it useful for? For example if tomorrow you will add subtitle to hold the date and the author of the comment...

Now let's think about . First of all it has to have an alt attribute but I'd also consider to move it into its own  element. It may help screen readers to keep "focus" on the content. About this...do not forget to include all the proper aria- attributes!


Was this shell script ready for open-source? (Random XKCD wallpaper)

#!/bin/bash

The shebang line has no effect unless it's on the very first line, so you should put it before the copyright notice.

echo $(pwd)

echo $(command) is almost always the same as just writing command (the exception being that echo adds a newline at the end if the command doesn't already produce one, but that's not the case here). So you can just change the above to pwd.

cat index.html | grep -o -m 1 http://imgs.xkcd.com/comics/.*\.png

That's useless use of cat. If you want to grep through a file, you can just pass the filename as the last argument - no need to cat and pipe. (The same goes for later places in the code where you do the same with .jpg).

gconftool-2 --set --type=string /desktop/gnome/background/picture_filename $(pwd)/"$name_pic"

I think it'd be a good idea to make the command to change the wallpaper configurable, so non-GNOME users can use your script too.

Also I'm not sure why you set the image to be the wallpaper before renaming it. I think it'd make more sense to do so afterwards (that might also solve your issue of having to sleep).

On a general note you might take care to gracefully handle already existing files. For example if the script is called in a directory where an index.html already exists (which is not that unlikely), your script will a) not work and b) delete that index.html, which its owner might not appreciate.


First of, I'm gonna give you a basic idea...

Instead of doing 2 loops over two different arrays, check their sizes first. Create a loop for the smaller of both array sizes. In that loop you will process that Array, and then create another loop for the remainder of unprocessed data.

This can be done for your two double fors you have in there. This way you could reduce the complexity from O(n+m) to O(n+(m-n))

The pseudo code is this...

if(Arr1 > Arr2)
{
   process(Arr1, Arr2);
}
else if (Arr2 > Arr1)
{
   process(Arr2, Arr1);
}
else //They're the same size!
{
  for(idx = 0; idx != count(any will do); ++idx)
  {
     //process Arr1
     //process Arr2
   }
}


Alternating sort order within a sorted group

1. Quick review

This function returns a new list, like the built-in sorted. It does not update data in place, like the sort method on lists. So a name containing "sorted" would give a better hint at its behaviour.

The docstring is not detailed enough to explain how to call the function. What arguments do I pass for group_key and sort_key? What happens if I pass True for group_reverse or sort_reverse?

The function calls operator.itemgetter to make key functions. But this means that the function will only work when the keys are dictionary or sequence values. If you want to use object properties as keys, you're out of luck (that would need operator.attrgetter). And if you want to compute something more complicated by passing in your own function, that's no good either.
I would recommend accepting any function for group_key and sort_key and letting the caller use operator.itemgetter if that's what they need. This makes the function behave more like the built-in sorted and similar functions that take key arguments.

Extend a list using the extend method, which updates the list in-place. If you use augmented assignment +=, Python may have to create a new list and copy all the elements across.

2. Rewrite
The algorithm you've chosen is:

Sort data by the group key.

Iterate over the data, collecting the groups.

Iterate over the groups, sorting each one.

Steps 2 and 3 can be combined into one iteration using itertools.groupby. The alternation between ascending and descending can be implemented using itertools.cycle. These two iterations can be combined using zip, like this:
from itertools import cycle, groupby

def sorted_alternately(data, group_key, sort_key,
                       group_reverse=False, sort_reverse=False):
    """Sort data on group_key (in reverse order if group_reverse=True) but
    within each group of items, alternately sort in ascending and
    descending order on sort_key (in descending and ascending order in
    sort_reverse=True).

    >>> from itertools import product
    >>> from operator import itemgetter as get
    >>> sorted_alternately(product(range(3), repeat=2), get(0), get(1))
    [(0, 0), (0, 1), (0, 2), (1, 2), (1, 1), (1, 0), (2, 0), (2, 1), (2, 2)]

    """
    data = sorted(data, key=group_key, reverse=group_reverse)
    groups = groupby(data, key=group_key)
    reverses = cycle((sort_reverse, not sort_reverse))
    result = []
    for (_, group), reverse in zip(groups, reverses):
        result.extend(sorted(group, key=sort_key, reverse=reverse))
    return result


Okay, trying to answer a few of your questions to the best of my knowledge:

  What desktop hardware will that work on? Is there any restriction, or will it work on any 10 years old desktop?

Probably not in a 10yo PC. Your code is currently targeting GLSL version 3.3, which was released circa 2010. You can check a version history here. However, if you need to be backward compatible, there are changes you can make to this code to target older OpenGL versions. I'll mention those at the end.

  Would that work on an android tablet?

No. Android devices use OpenGL-ES, which is a variant of Desktop OpenGL version 2.0. You wouldn't have the texelFetch() function neither integer types in the current OpenGL-ES used by both Android and iOS devices.

  Will any interpolation of pixel be performed, if my rendering surface is the same size as the texture? Is it possible to have interpolation (with some flag, not by implementing it)?

What exactly do you mean by interpolation? By any chance are you talking about texture filtering? By using texelFetch(), you have opted-out of texture filtering. It is not clear to my why you did this however. If you were to switch your texture sampling to a function like texture() (or texture2D if targeting older versions) you would be able to have filtered lookup and also avoid the non-portable texelFetch(). texture()/texture2D() also take the UVs as normalized 0-1 range texture coordinates, so it would make your shader faster too by eliminating the integer conversions.

Backward compatibility: You can make this code backward compatible with older OpenGL version by replacing texelFetch() with texture()/texture2D(), as I've mentioned before. That would also be necessary for current OpenGL-ES compat. You would also have to remove any integer conversions. Older OpenGL and OpenGL-ES hardware can only operate on floating point types! (no int or ivec).

A comment on performance: Branching is still an expensive operation on a lot of graphics hardware out there. So the most obvious improvement here would be to eliminate the conditional if test. You might be able to pull it off using several clever tricks. Maybe the mod function might be of help.


Initializing an Array of Alternating Values

On my computer (a 1.2 GHz Intel Core m5 MacBook) I measured

Array(repeating:count:)        663μs 995ns
Array(repeatingValues:count:)  13ms 105μs

with the code compiled in the Release configuration, i.e. with
optimizations. This is approximately a factor of 20 between those methods.

It seems that one “culprit” is the remainder calculation in

        newArr.append(arr[i % arr.count])

If we replace that by an addition with wrap-around test

public init(repeatingValues arr: Array, count: Int) {
    precondition(!arr.isEmpty, "Initialization values cannot be empty")
    precondition(count > 0, "Count cannot be less than 1")

    var newArr = Array<Element>()
    var srcIndex = 0
    for _ in 0..<count {
        newArr.append(arr[srcIndex])
        srcIndex += 1
        if srcIndex == arr.count { srcIndex = 0 }
    }
    self = newArr
}

then the performance improves to

Array(repeatingValues:count:)   3ms 315μs

which is “only” by a factor of 5 slower than Array(repeating:count).

Another possible bottleneck is the array bounds check on each access.
This can be bypassed  by accessing the element storage directly:

init (repeatingValues2 arr: Array, count: Int) {
    precondition(!arr.isEmpty, "Initialization values cannot be empty")
    precondition(count > 0, "Count cannot be less than 1")
    var newArr = Array(repeating: arr.first!, count: count)
    newArr.withUnsafeMutableBufferPointer { src in
        arr.withUnsafeBufferPointer { dest in
            var j = 0
            for i in 0..<count {
                src[i] = dest[j]
                j += 1
                if j == arr.count { j = 0 }
            }
        }
    }
    self = newArr
}

This reduces the execution time to

Array(repeatingValues:count:)   1ms 889μs

which is now slower roughly by a factor of 3 than Array(repeating:count).

Other possibly useful technique is to avoid reallocations of the
array element storage by calling

    newArr.reserveCapacity(count)

However, this did not make a significant difference in my tests.

One further remark: Requiring the destination count to be strictly
positive seems unnecessary restrictive to me. I would change that to

init (repeatingValues arr: Array, count: Int) {
    precondition(!arr.isEmpty, "Initialization values cannot be empty")
    precondition(count >= 0, "Count cannot be negative")
    if count == 0 {
        self = []
        return
    }

    // ...
}


You can re-throw an exception:

int main() {
    ...
    try {
        ...
        try
        {
            foo();
        }
        catch(std::exception const& e) {
            std::cout << "Fatal error: " << e.what() << std::endl;

            throw; // re-throw the exception.
                   // or you could throw a different exception.
        }
        ...
    } catch (const std::exception &e) {
        std::cout << "Fatal error: " << e.what() << std::endl;
        return;
    }
    ...
}


Given one of the main highlights of Robot Framework is readability, I'll show my suggestions to improve that first and then go into my mechanical suggestions.

First, good readability practice in Robot Framework is to line up your cells by tabs (or sets of four characters depending on your IDE) and capitalize each word of your keyword uses. So, your code as sent would look like this.

*** Settings ***
Library         Selenium2Library
Suite Setup     Open Browser    http://robotframework.org/Selenium2Library/Selenium2Library.html    chrome

*** Variables ***
${SHORTCUTS} =  dom=document.getElementsByClassName("shortcuts")[0].childNodes

*** Test Cases ***
Testing
    #   First half of the shortcuts table has shortcuts-container xpath name
    ${Cuts-Container} =     Get Matching Xpath Count    //*[@id="shortcuts-container"]/div/a
    #   Second half of the shortcuts table has keywords-container xpath name
    ${Key-Container} =      Get Matching Xpath Count    //*[@id="keywords-container"]/table/tbody/tr
    #   Count is the addition of both xpath names integer
    ${COUNT} =              Evaluate    ${Cuts-Container}+${Key-Container}

    #   Simple for loop that will only click on every odd element because every even
    #   Element is a non-clickable symbol used to make the shortcuts table look pretty
    : FOR   ${INPUT}    IN RANGE    0   ${COUNT}
    \   ${ODD?} =   Evaluate    ${INPUT}%2
    \   Only Click Odd  ${ODD?}     ${INPUT}
    \   Sleep   .2s

*** Keywords ***
Only Click Odd
    [Arguments]     ${EvenOrOdd}    ${Counter}
    Run Keyword If  ${EvenOrOdd}==1     Click Element   ${SHORTCUTS}[${Counter}]

I'm not trying to be too critical of your variable naming but I do have to be for completionism and for other future Robot Framework users looking for how to write readable code. Because (it appears) that you're using the Python version of Robot Framework, I'd say it's good practice to keep to the Python convention of naming variables, which is lower_case_with_underscores for local variables or UPPER_CASE_WITH_UNDERSCORES for global variables and index variables in loops. Also, shorter, more descriptive variable names are perfectly acceptable for this size of program. Re-written for that, your variables should be ${shortcuts}, ${keywords}, ${count}, ${odd}, ${even_or_odd}, and ${counter}.

Mechanically, I'm assuming it works fine as-written, but there's a few optimization problems. First, having a custom keyword for a single action is usually redundant (unless you want to simplify a repeated action with a lot of parameters to a single word for readability), so you could re-write your For loop as follows (using the re-formatted variables):

: FOR   ${INPUT}    IN RANGE    0   ${count}
    \   ${odd} =   Evaluate    ${INPUT}%2
    \   Run Keyword If  ${odd}==1     Click Element   ${SHORTCUTS}[${INPUT}]
    \   Sleep   .2s

That makes the keyword unnecessary, making your code easier to maintain.

Finally, as another good practice, Selenium2Library is outdated. You'll need to download it separately, but ExtendedSelenium2Library is more robust, contains more keywords, and includes code to deal with Angular applications.

The final code after formatting and optimization looks like this (I also took some liberties on comments that are either unnecessary or too wordy for what they describe):

*** Settings ***
Library         ExtendedSelenium2Library
Suite Setup     Open Browser    http://robotframework.org/Selenium2Library/Selenium2Library.html    chrome

*** Variables ***
${SHORTCUTS} =  dom=document.getElementsByClassName("shortcuts")[0].childNodes

*** Test Cases ***
Testing
    #   Count the number of shortcuts and keywords
    ${shortcuts} =  Get Matching Xpath Count    //*[@id="shortcuts-container"]/div/a
    ${keywords} =   Get Matching Xpath Count    //*[@id="keywords-container"]/table/tbody/tr
    ${count} =      Evaluate    ${shortcuts}+${keywords}

    #   Click every odd element (evens are unclickable)
    : FOR   ${INPUT}    IN RANGE    0   ${count}
        \   ${odd} =        Evaluate    ${INPUT}%2
        \   Run Keyword If  ${odd}==1   Click Element   ${SHORTCUTS}[${INPUT}]
        \   Sleep           .2s

In other notes, this is actually a very good first Robot Framework script that is very optimal (as far as I can tell) other than my suggestions.

Also, I completely missed who wrote this code originally when I was writing up this review. I know this guy IRL. Hey Fin! Hope this explained how I get my code to look so nice.


You are just sorting by date, correct? I'd use

using System.Linq;
// ....
List<Log> errors = _logHandler.GetErrors(daysBack);
List<Log> errorsSorted = errors.OrderBy(l => l.Date).ToList();

According to this stackoverflow question, OrderBy uses QuickSort in this case, which usually has a run time of O(n log n).


This will depend on your content and how you prepare it, but I'd suggest a very generic solution that'll work for any level of nested points. Now, arbitrary nesting doesn't appear to be required in your case, but, hey, nice to have.

Suppose your JSON content is structured like so:

var points = [
    {title: "Point", children: [
        {title: "Point"},
        {title: "Point"},
        {title: "Point"},
        {title: "Point", children: [
            {title: "Point"},
            {title: "Point"},
            {title: "Point", children: [
              // more...?
            ]}
        ]}
    ]}
]

You'll note that you can just keep nesting the points indefinitely.

To render this as HTML, you can use a recursive function. Like this:

function buildList(parentElement, items) {
    var i, l, list, li;
    if( !items || !items.length ) { return; } // return here if there are no items to render
    list = $("

").appendTo(parentElement); // create a list element within the parent element
    for(i = 0, l = items.length ; i < l ; i++) {
        li = $("

").text(items[i].title);  // make a list item element
        buildList(li, items[i].children);          // add its subpoints
        list.append(li);
    }
}

And call it like so:

buildList($("#pageContent").empty(), points);

The point is that since the structure is recursive, it can nest to any depth, but the code is simpler.

Here's a jsfiddle. This is quite a different approach, and Daniel Cook's answer is probably more immediately applicable to you current code, but I thought it worth to point out.

You could also extend it to add the "1", "1.1", "1.2" (and so on) numbers to the titles.


Mapping to and from domain models and view models is exactly what automapper is designed for.


You can’t use the label element like that. Its for attribute may only refer to "labelable elements" (and div isn’t labelable).

Semantic markup

(Assuming that you can’t use fieldset.)

You can ignore all the div elements (except their "meaningful" attributes, if any), because they are meaningless. So your markup is essentially this:

<form method="get" novalidate>

  Pet Type

  <input id="r3" name="same2" type="radio" />
  Cat

  <input id="r4" name="same2" type="radio" />
  Dog

</form>

Having a label without associated form control is not wrong, but maybe uncommon. It "represents a caption in a user interface", so I guess you could keep it like that.

If you want more "structure", you could use the dl element. However, I think it might be overkill for such a simple case.

Accessibility

WAI-ARIA recommends "that elements with role radio are explicitly grouped in order to indicate which ones affect the same value".

(In HTML5, input elements in the radio button state have the radio role by default.)

How to group them explicitly?

  This is achieved by enclosing the radio elements in an element with role radiogroup.

So you should use the radiogroup role, e.g.:

<form method="get" novalidate>

    Pet Type

    <input id="r3" name="same2" type="radio" />
    Cat

    <input id="r4" name="same2" type="radio" />
    Dog

</form>

(HTML5 recommends not to set role="radio" for the radio buttons explicitly, but you may do so if you want to.)


Insert and Remove Element in Deque using threads in C++

Here are some things that may help you improve your code.

Isolate platform-specific code

If you must have stdafx.h, consider wrapping it so that the code is portable:

#ifdef WINDOWS
#include "stdafx.h"
#endif

In this code, with a single file, the use of stdafx.h does not gain anything on any platform, including Windows.

Don't use leading underscores in names

Anything with a leading underscore is a reserved name in C++ (and in C).  See this question for details.

Be careful with conditional variables

Right now, t2 waits for a conditional variable and t1 sets it.  If t1 never pushes anything to the deque, t2 would wait forever and never terminate.  Similarly, if t1 is launched before t2, it could execute the cond.notify_one() before any threads are waiting for that variable, so t1 would push 10 and notify, but no thread would "hear" the notification with the effect that t2 would only be notified after t1 pushes 9.  The effect is that the code would almost work but never terminate.  To allow the launching of threads in either order, I'd recommend that t2 should keep popping until the deque is empty.  This is a typical pattern in multithreaded code.

Remember that main is a thread, too

I realize that this code is probably written for practice using threads and locks and such, but it's important to remember that main is also a thread, so this program actually uses three threads and not two.  Because the main function isn't really doing anything useful while the threads are running, an alternative approach would be to launch only t1 as a thread and then simply invoke function2 directly from main, thereby using only two threads instead of three and getting the same work accomplished.

Remember that std::cout is a shared resource

It's not an issue in this code because only one thread at a time prints to std::cout, but as you create more complex code, it's important to remember that std::cout is a shared resource, too,  For that reason, you'll want to have a mutex for access to it as well if you want to avoid possible interleaving of output.


UIView position updates based on device motion via RxSwift

You are correct that you are not using it correctly. For example Subjects are only needed to convert non-rx code into Rx code or to handle cycles. The fact that you have two of them is problematic.
When working on an Observable sequence, start with the effect you want to achieve the figure out what causes the effect to change. In this case, the effect is the updating of the center of the levelDot view.
The center of a view doesn't have a reactive wrapper on it in RxCocoa, so the first step is to make that:
extension Reactive where Base: UIView {
    var center: Binder<CGPoint> {
        return Binder(base) { view, point in
            view.center = point
        }
    }
}

With the above, you will now be able to .bind(to: levelDot.rx.center). In order to do that you need an Observable<CGPoint> that is emitted every time the CMMotionManager updates. CoreMotion is also not in the RxCocoa library by default, but the tools are available in RxCocoa to wrap it.
extension Reactive where Base: CMMotionManager {
    func startDeviceMotionUpdates(to queue: OperationQueue) -> Observable<CMDeviceMotion> {
        return Observable.create { [base] observer in
            base.startDeviceMotionUpdates(to: queue, withHandler: handler(observer: observer))
            return Disposables.create { [base] in
                base.stopDeviceMotionUpdates()
            }
        }
    }
}

func handler<T>(observer: AnyObserver<T>) -> (T?, Error?) -> Void {
    return { data, error in
        if let data = data {
            observer.onNext(data)
        }
        else {
            observer.onError(error ?? RxError.unknown)
        }
    }
}

(I moved the handler into its own function because it can be used for many of the other CoreMotion handler callbacks.)
With the above, you can now call myCoreMotionManager.rx.startDeviceMotionUpdates(on:) with whatever queue you want to use. It will create an Observable. When that observable is subscribed to, it will call the supplied closure which calls the manager's startDeviceMotionUpdates(to:withHandler:) method. The handler will send onNext events to the server whenever the device motion updates. When the observable is unsubscribed to, the disposable will turn off the updates.
Now, it's just a matter of mapping from one to the other which can be done with a pure function. Since you have outside data that is needed in that function, you need a function factory:
func point(limiatedBy positiveMax: CGPoint) -> (CMDeviceMotion) -> CGPoint {
    return { deviceMotion in
        let attitude = deviceMotion.attitude
        let x = max(0, min(positiveMax.x, positiveMax.x + CGFloat(attitude.roll) * positiveMax.x * 1.15 / 2))
        let y = max(0, min(positiveMax.y, positiveMax.y + CGFloat(attitude.pitch) * positiveMax.y * 1.3 / 2))
        return CGPoint(x: x, y: y)
    }
}

Lastly, you forgot the DisposeBag to unwind everything when the view controller goes out of scope...
With all of the above available, your view controller is quite simple. It almost writes itself and you might want to try writing it before you examine the code below:
class ViewController: UIViewController {

    @IBOutlet var levelDot: UIView!
    var positiveMax: CGPoint = CGPoint.zero
    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        levelDot.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
        positiveMax = CGPoint(x: view.bounds.maxX, y: view.bounds.maxY)
        initGryo()
    }

    fileprivate func initGryo() {
        let motion = CMMotionManager()
        guard motion.isDeviceMotionAvailable else { return }
        motion.deviceMotionUpdateInterval = 1/60

        motion.rx.startDeviceMotionUpdates(to: OperationQueue.main)
            .map(point(limiatedBy: positiveMax))
            .bind(to: levelDot.rx.center)
            .disposed(by: disposeBag)
    }
}

The other critique you asked for involves capturing self... You should never capture self in a .map(_:) or filter for that matter. Just don't do it.


I'm sorry, but my review is going to be short; your code looks pretty good.

Refactor node deletion

You did a very good job of refactoring your code for the most part. The only repetition that I can find is here:

var parentNode = message.parentNode;
parentNode.removeChild(message);
if (parentNode.children.length === 0){
    messageBlock.style.display = "none";
}

Perhaps it would be best to split this off into a deleteMessage function to keep things simple.

Refactoring message content checking

This conditional is fairly lengthy:

if (messageText.startsWith('sd') || (messageText.startsWith('!!/') && messageText !== '!!/blame' && messageText !== '!!/amiprivileged') || isSmokeyResponse)

Perhaps it would be cleaner to split this off into a separate function called isSDCommand.

Variable confusion

In the first part of hideSmokeyMessage, you have this:

var text = innerText(message, '.content');

In the second part, after the conditional, you have this:

var messageText = innerText(message, '.content');

Two variables, same exact content but with different names and in different scopes. That's a little confusing.

You should define the text variable above the first conditional so both parts of the function can use it, since they both need to use it anyway.

Simplifying argument checking

This is your innerText function:

function innerText(element, selector){
    if (!selector) return "";
    var foundElement = element.querySelector(selector);
    if (!foundElement || !foundElement.innerText) return "";
    return foundElement.innerText;
}

First off, if you are going to check for the existence of selector, why not also check for the existence of element? I personally think you could just drop the checking all together because

This isn't some standard function that you are reinventing
You always provide the second parameter

Another simplification you can make is removing the second part of the remaining conditional (the part after the ||). If there is no text, it's going to be "" anyway.

Now your function looks like this:

function innerText(element, selector){
    var foundElement = element.querySelector(selector);
    if (!foundElement) return "";
    return foundElement.innerText;
}

This can be even further simplified with a ternary operator now:

return foundElement ? foundElement.innerText : "";

Nitpick

You can merge the SmokeyIdsBasedOnSite map and the SmokeyUserId together to make it a bit cleaner in that section:

var SmokeyUserId = ({
    "chat.meta.stackexchange.com": 266345,
    "chat.stackexchange.com": 120914,
    "chat.stackoverflow.com": 3735529
})[document.location.host];


###Program only handles one testcase###
Your program reads in T but doesn't iterate T times, so it only handles the first test case.  This could be the cause of the "wrong result" error.
###Memory limit exceeded###
Your program solves the problem correctly, but it uses \$O(n^3)\$ memory, so on large inputs it will run out of memory (possibly giving you a wrong answer instead of a timeout).  For a string of size 100000 (which is the maximum according to the problem description), the total length of all substrings is:  166671666700000, or \$1.7 * 10^{14}\$, which would require 170 terabytes of memory.
###Solution using: Suffix array + LCP array###
In the problem description, you will notice on the "Need Help?" section on the right hand side that there are links to two topics:

Suffix array
LCP array

You probably will want to read those links later, because they will give useful information on how to generate the two arrays in the most efficient way possible.  But for now, I will explain how, if you have already generated the suffix array and LCP array, you can solve the rest of the problem in \$O(n)\$ time and no additional space other than the \$O(n)\$ space used for the two arrays.
###Definitions###
First, some quick definitions of my own (if you haven't read through those above links yet):

The suffix array for a string of length \$n\$ is just a sorted array of the \$n\$ suffixes of the string.  To save space, the array contains integers instead of strings, where the integer is the index of the starting character of the suffix in the original string.  For example, if suffix[3] = 5, that is equivalent to suffix[3] = original_string.substring(5).

The LCP array holds the length of the longest common prefix between two successive strings of the suffix array.  For example, if suffix[5] = "abcd" and suffix[6] = "abyz", then LCP[6] = 2 because the two strings have a common prefix of length 2.

###Generating substrings in order###
The key to finding the kth character in the concatenated substrings is that you can generate all substrings in lexicographical order by iterating across the suffix array.  Let's take an example of the string "abcd".  The suffix array for this string is:
suffix[0] = "abcd"
suffix[1] = "bcd"
suffix[2] = "cd"
suffix[3] = "d"

If you take each possible prefix string of each possible suffix string, you will have generated all possible substrings of the original string.  For example, if you take suffix[0] = "abcd", there are four possible prefix strings:
"a", "ab", "abc", "abcd"

If you take suffix[1] = "bcd", there are three possible prefix strings:
"b", "bc", "bcd"

Now, if you notice, the order in which I just generated the substrings are the first 7 substrings of the original string in correct lexicographical order.  If you continue through the suffix array like this, all of the strings you generate will be in the order that you are supposed to concatenate to the final string (except for duplicate substrings, which I will talk about later).
You will also notice that for a particular length suffix, it is easy to compute how long all of its substrings will be.  For example, if the length of the suffix is 4 (such as "abcd"), then the length of the substrings it generates is 1 + 2 + 3 + 4.  In general, if a suffix has length n, then the length of the substrings it generates is n * (n+1) / 2.
###Solving the problem (no duplicate substrings)###
This gives us the following code to find the kth character, assuming that there are no duplicate substrings.  For each suffix in the suffix array, we find out if K falls within the substrings for that suffix.  If it does, we find out which substring it is and print out the required character.  If it does not, we quickly move on to the next suffix.
    int     n         = s.length();
    Integer [] suffix = GenerateSuffixArray(s);

    for (int i=0;i<n;i++) {
        long len   = n - suffix[i];
        long count = len * (len + 1) / 2;

        // If K is not found within the substrings generated by this
        // suffix, then go on to the next suffix.
        if (K > count) {
            K -= count;
            continue;
        }

        // K must be found within this suffix.  Now iterate through its
        // substring to find the exact substring and character.
        for (long j=1;j<=len;j++) {
            if (K <= j) {
                System.out.println(s.charAt((int) (suffix[i] + j - 1)));
                break;
            }
            K -= j;
        }
        break;
    }

###Handling duplicate substrings###
Duplicate substrings are handled by skipping past them.  For example, suppose you had two suffixes in your suffix array like this:
suffix[0] = "abcd"
suffix[1] = "abxyabcd"

Notice that the substrings generated would be:
"a", "ab", "abc", "abcd"
"a", "ab", "abx", "abxy", "abxya", "abxyab", "abxyabc", "abxyabcd"

Because there is a common prefix of length 2, the first 2 substrings generated are the same.  So when we handle the second suffix, we should skip those because they were already handled previously.
###Sample solution###
Here is a sample solution to the problem, that can get the correct answer for a string of 100000 length, but not in the most time efficient manner.  The reason is that I generated the suffix array and the LCP array in the simplest way possible, requiring \$O(n^2)\$ time.  To really solve the problem, you should read those links above and generate the suffix array and LCP array in a more efficient manner.  I'll leave that as an exercise to the reader.
import java.util.*;

public class Solution {

    public static Integer[] GenerateSuffixArray(final String s)
    {
        int        len = s.length();
        Integer [] ret = new Integer[len];

        for (int i=0; i < len; i++) {
            ret[i] = i;
        }
        Arrays.sort(ret, new Comparator<Integer>() {
            public int compare(Integer i1, Integer i2) {
                return s.substring(i1).compareTo(s.substring(i2));
            }
        });
        return ret;
    }

    public static int[] GenerateLCP(String s, Integer [] suffix)
    {
        int    len     = s.length();
        int [] ret     = new int[len];
        String prevStr = s.substring(suffix[0]);

        ret[0] = 0;
        for (int i=1; i < len; i++) {
            String str  = s.substring(suffix[i]);
            int    j    = 0;
            int    jMax = Math.min(prevStr.length(), str.length());

            // Find the longest common prefix of prevStr and str.
            for (j=0; j < jMax; j++) {
                if (prevStr.charAt(j) != str.charAt(j))
                    break;
            }
            ret[i] = j;
            prevStr = str;
        }
        return ret;
    }

    public static void main(String[] args) {
        Scanner scanner =  new Scanner(System.in);
        int T = scanner.nextInt();

        while (T-- > 0) {
            String s = scanner.next();
            long K = scanner.nextLong();

            int     n         = s.length();
            Integer [] suffix = GenerateSuffixArray(s);
            int     [] lcp    = GenerateLCP(s, suffix);

            for (int i=0;i<n;i++) {
                long len    = n - suffix[i];
                long count  = len * (len + 1) / 2;
                long prefix = lcp[i];

                count -= prefix * (prefix + 1) / 2;

                // If K is not found within the substrings generated by this
                // suffix, then go on to the next suffix.
                if (K > count) {
                    K -= count;
                    continue;
                }

                // K must be found within this suffix.  Now iterate through its
                // substring to find the exact substring and character.
                for (long j=prefix+1;j<=len;j++) {
                    if (K <= j) {
                        System.out.println(s.charAt((int) (suffix[i] + K - 1)));
                        break;
                    }
                    K -= j;
                }
                break;
            }
        }
    }
}


Your code doesn't work like in real life. For example, when I play:

1|2|3
4|5|6
7|8|9

P1(X): Enter your Input:1

P2(O): Enter your Input:1

X|2|3
4|5|6
7|8|9

There is no error generated. Both players cannot request the same location. Also, playing a new game, this scenario:

P2(O): Enter your Input:5

X|O|3
X|O|6
7|8|9

P1(X): Enter your Input:7

P2(O): Enter your Input:

This scenario P2(O): should never have been reached. Player 2 doesn't get another move after Player 1 wins the game. Recommend fixing these problems.

Onto your code -

Firstly, you have an entry point - that's good, however it doesn't do anything other than call play().

You should move the control loop into the entry point, and remove duplicate code scattered amongst your code. In default_values(), you scatter those pieces across the code.

tot_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
p1 = 0
p2 = 0
p1_win = False
p2_win = False
tie = False

Yet you have them inside default_values(). Inside your play() function, you have play() in the loop, but the first time you call it, you specify default_values() - notice the inconsistency there?
You should have realized that when you were reviewing your code.

So, we fix that, and this is what we come up with:

if __name__ == '__main__':

    win_combinations = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
        [1, 4, 7],
        [2, 5, 8],
        [3, 6, 9],
        [1, 5, 9],
        [3, 5, 7]]

    while True:
        default_values()
        play()
        choice = input("Play Again? ('n' to exit):")
        if choice == "n":
            break

    print("Ciao")

You also have lots of other issues with your code, but let me give you a few pointers for the rest (I don't want to rewrite your entire code).

if p1_win == True:
You don't need to specify "True" as this is the same: if p1_win:

You have global statements all throughout your code. This is bad - and the reason is - you don't know 100% where your variables are being changed. The #1 source of all bugs when coding is when the state changes in variables and the change was unintended. Does that make sense? Please review it by googling.
What you should do is pass variables around. Having a piece of code like:

active_player = not active_player
player_input = get_player_input()
board_state = update_board(player_input, board_state)
if check_for_a_winner(board_state):
    print("We have a winner! {} wins!".format(active_player))

shows you how we inject the input as well as the current board status into the update_board function, and receive the updated board status back from it. We can then present the current board status into the winner check function.
This examples shows that state changes only in very specific places, and if you're hunting down a bug, you can find it quite simply.

Typically, with several pieces of related state, you'll need an object which can represent all of them at once. I recommend reading a book which explains about classes, for instance having multiple dog and cat classes and how you can represent their attributes.

Please attempt to incorporate these changes into you code and repost your updated solution (with a link to this page) and demonstrate your code working better, with those bugs removed.

Good Luck!


Variable names
I find the get_ prefixes unnecessary on these:
get_year = check_time_now.year
get_month = check_time_now.month
get_day = check_time_now.day

That makes them look like functions.
Boundaries
This:
working_hours = datetime.time(7, 0, 0)
after_hours_am = datetime.time(6, 59, 59)

should probably just use 7:00 for after_hours_am. Otherwise, the time 6:59:59 given your current usage will still be considered working hours.
Likewise, this:
check_time_now.time() > after_hours_pm

should use >=.
An easy convention to follow that makes your boundary checking consistent is to always use intervals that are closed at the beginning and open at the end, i.e. 7:00 <= time < 8:00.
Redundant else
This:
    return datetime.datetime(get_year, get_month, get_day, 7, 0, 0)

elif ...

can use an if instead of an elif due to the previous return.
Don't repeat yourself
This return:
    return datetime.datetime(get_year, get_month, get_day, 7, 0, 0)

shares many commonalities with the other returns in its function. Factor out a new_day and new_hour variable assignment, then at the end of your function,
return datetime.datetime(get_year, get_month, new_day, new_hour)

Note that 0 is the default for the remaining parameters.
Timespan division
Trying not to do your own time math, this would be one option that doesn't require knowledge of time position multiples:
days = clock_tick.days
rem = clock_tick - timedelta(days=days)
hours = rem // timedelta(hours=1)
rem -= timedelta(hours=hours)
mins = rem // timedelta(minutes=1)
rem -= timedelta(minutes=mins)
secs = int(rem.total_seconds())

I don't like it, but built-in Python time libraries are kind of bad. Third-party libraries will reduce this to a one-liner format call. This is educational:
https://stackoverflow.com/questions/538666/format-timedelta-to-string


List all possible permutations from a python dictionary of lists

The tool you need here is itertools.product:

>>> import itertools
>>> keys, values = zip(*config_overrides.items())
>>> experiments = [dict(zip(keys, v)) for v in itertools.product(*values)]
>>> len(experiments)
3234
>>> experiments[1034]
{'nhidden': 4, 'nodetype': 'lstm', 'loss': 'msle', 'opt': 'nadam', 'actfunc': 'sigmoid'}

Of course, if you are going to be iterating over the experiments one by one, then there is no point in allocating a list, and you could do this instead:

keys, values = zip(*config_overrides.items())
for v in itertools.product(*values):
    experiment = dict(zip(keys, v))
    # etc.

And depending on what you are doing with the experiments, you may not even need to build the dictionary:

keys, values = zip(*config_overrides.items())
for experiment in itertools.product(*values):
    for key, value in zip(keys, experiment):
        # etc.


Current user as a class-level property in Objective-C and Swift

(I am referring to the Swift code only.)

You can declare a property as

public private(set) var name: String?

to make it public read-only, but internally read-write. That makes
the additional accessor getName() obsolete.

If the property is only assigned in the init method and never
changed later, you can simply make it constant:

public let name: String?

Since the initializer ensures that both name and address are assigned
a value, you don't have to declare them as optionals.

The currentUser(), setCurrentUser(), removeCurrentUser()
methods can be replaced by a static property

public static var currentUser: User?

if you make the initializer public. static means class final,
i.e. it is a property of the type (and not an instance) and cannot
be overridden in subclasses.

The two guard statements can be combined into one.

The class then looks like this:

public class User {

    public static var currentUser: User?

    public let name: String
    public let address: String

    public init?(dictionary: [String : AnyObject]) {

        guard let name = dictionary["name"] as? String,
            let address = dictionary["address"] as? String
        else { return nil }

        self.name = name
        self.address = address
    }
}

The "current user" can now be set, retrieved, and unset like this:

User.currentUser = User(dictionary: ...)
if let user = User.currentUser {
    // ...
}
User.currentUser = nil

If you change the initializer to

public init?(dictionary: [String : Any])

then you can pass a native Swift dictionary without casting, e.g.

User.currentUser = User(dictionary: ["name": "Joe", "address": "San Francisco"])


I can't help a lot. Only some syntactic hints:

object Tabulator {

  def format(table: Seq[Seq[Any]]) =
    if (table.isEmpty) ""
    else {
      def cellSize(cell: Any) =
        cell.toString.length

      val cellSizes =
        table map { _ map cellSize }
      val colSizes =
        cellSizes.transpose map { _.max }
      val rows =
        table map formatRow(colSizes)

      formatRows(rowSeparator(colSizes), rows)
    }

  def formatRow(colSizes: Seq[Int])(row: Seq[Any]) = {
    val cells =
      for ((item, size) <- row zip colSizes) yield
        if (size == 0) "" else "%"+size+"s" format item
    cells mkString ("|", "|", "|")
  }

  def formatRows(rowSeparator: String, rows: Seq[String]): String = (
       rowSeparator
    :: rows.head
    :: rowSeparator
    :: rows.tail.toList
    ::: rowSeparator
    :: Nil
  ) mkString "\n"

  private def rowSeparator(colSizes: Seq[Int]) =
    colSizes map { "-"*_ } mkString ("+", "+", "+")
}

I deleted the null-check in cellSize because null is not familiar in Scala. If you definitely need null then restore the check.


public class PrintPermutations{

Classes are types of things, so they usually get noun names, e.g.

public class PermutationPrinter<T> {

You mention that you want this to work with generic types.  The way to do that is to add a generic parameter.

        public void printPermutations(String prefix,int[] arr){

Unfortunately, there are no generic arrays in Java, so you have to switch to a different data type.  You have a list of items, so let's switch to List.

    public void permuteAndPrint(String prefix, List<T> items) {

Your method actually does two things, not one.  Thus, the compound name.  This actually violates something called the Single Responsibility Principle, but I'm going to ignore that for now.

I prefer plural names for collections, so I changed the now inaccurate arr to items.

Side note:  you use eight column indent for the first two levels and then use smaller indents thereafter.  The usual suggestion is to always tab the same amount.  I switched to a consistent four column tab, as that's pretty common (standard) in Java programming.

                if(arr.length == 1){
                  System.out.println(prefix + arr[0]);
                }else{

Rather than use an if/else construct, it is common to return from the base case of a recursive function:

        if (items.size() == 1) {
            System.out.println(prefix + items.get(0));
            return;
        }

This allows the rest of the function to work without extra indent and makes it more recognizable as a base case.

                 for(int i=0;i<arr.length;i++){
                   printPermutations(prefix+arr[i]+",",taperedArray(arr,i));
                 }

There are several things that I don't like about this, starting with the index-based for loop.  I'd rather use the foreach format:

        for ( T item : items ) {
            List<T> remnants = new ArrayList<T>(items);
            remnants.remove(item);
            permuteAndPrint(prefix + item + ",", remnants);
        }

A useful feature of List is that it includes a remove function that replaces your taperedArray function.

Now rather than saying arr[i], we can say a more readable item.

So the whole class is now

public class PermutationPrinter<T> {

    public void permuteAndPrint(String prefix, List<T> items) {
        if (items.size() == 1) {
            System.out.println(prefix + items.get(0));
            return;
        }

        for ( T item : items ) {
            List<T> remnants = new ArrayList<T>(items);
            remnants.remove(item);
            permuteAndPrint(prefix + item + ",", remnants);
        }
    }

    public static void main(String[] args) {
        PermutationPrinter<Integer> printer = new PermutationPrinter<Integer>();
        List<Integer> data = Arrays.asList(1,2,3);
        printer.permuteAndPrint("", data);
    }

}

This does mostly the same steps as your original and still violates the Single Responsibility Principle.  Normally we'd write main something like

    public static void main(String[] args) {
        List<Integer> data = Arrays.asList(1,2,3);
        PermutationPrinter<Integer> printer = new PermutationPrinter<Integer>(data);
        printer.permute();
        printer.print();
    }

This has several advantages.  For one, it saves the caller from passing an empty string to the recursive function.  Instead, we can now write

public class PermutationPrinter<T> {
    List<T> items;
    List<List<T>> permutations = new ArrayList<>();

    public PermutationPrinter(List<T> data) {
        items = data;
    }

    private void _permute(List<T> permutation, List<T> data) {
        if (data.size() <= 0) {
            permutations.add(permutation);
            return;
        }

        for ( T datum : data ) {
            List<T> remnants = new ArrayList<T>(data);
            remnants.remove(datum);
            List<T> elements = new ArrayList<T>(permutation);
            elements.add(datum);
            _permute(elements, remnants);
        }
    }

    private void permute() {
        List<T> permutation = new ArrayList<T>();
        _permute(permutation, items);
    }

    private void print() {
        for ( List<T> permutation : permutations ) {
            T last = permutation.remove(permutation.size() - 1);

            for ( T element : permutation ) {
                System.out.print(element + ", ");
            }

            System.out.println(last);
        }
    }

}

Notice how this hides the details of how the recursive function works inside a public method.  This allows the recursive method to be private.  We could change its interface tomorrow with no impact outside this class.

Another advantage is that it is easier to unit test the state of variables than output.  So we may not be able to unit test print, but we can certainly unit test permute and _permute.

This also allows us to move main out of the class and into its own class.  This class shouldn't need a main method.

Note:  I haven't attempted to optimize the algorithm.  I just rewrote it in a new style.


Find all strings in list which have keywords in it from another list

Your general coding style is very readable.
You stick to PEP8 and your function and the variables are named reasonably.
You could optimize your code by using the built-in functions filter and all:

def string_search(strings, keys):
    return filter(lambda string: all(key in string for key in keys), strings)

Also do not use if var == True: but if var: instead.


Unfortunately I don't think there is much you can do here because of how the targets of your regexes are different. I was going to say you could change some of these to use groups, for example:

RewriteRule blog/(.*)/([0-9]+)-(.*)$ blogpost.php?brand=$1&blog_id=$2&titre=$3
RewriteRule brand/([0-9]+)-(.*) brand.php?id=$1&brand=$2
RewriteRule shop/brands/([0-9]+)-(.*) shopbrand.php?id=$1&brand=$2

These all end with the pattern ([0-9]+)-(.*) so you almost could extract the first part and use that file, like this:

RewriteRule (.*)/([0-9]+)-(.*)$ $1?id=$2&brand=$3

However you can't because e.g. shop/brands doesn't match shopbrand.php (and not everything has brand=). There just isn't enough commonality in the paths to make this sort of thing feasible.

If your goal is to simply get rid of .htaccess, using a script and using a dispatcher with PHP logic would be an alternative, as stated in the question comments. Personally I don't think that would be any simpler though, I think it would just be moving the "problem" into a different file--one that Apache needs to start up a PHP thread/process to solve, instead of doing it on its own.

The only way, IMHO, to improve this situation would be to architect the site differently and/or abandon the old URLs so you don't need to rewrite them. If you can change what the URLs are, then I would suggest switching to a single index.php dispatcher and MVC or REST pattern (or use a framework that handles this, like Symfony).


Simple palindrome function for single words

Firstly, your testing is insufficient. This code thinks that "defad" is a palindrome and that "deed" is not. You algorithm is completely broken.

def is_palindrome(w):

    if not isinstance(w, str):
        return "ERROR: input is not a string."

Don't check types. Just treat it like a string, and trust the caller to pass the right kind of object. Also don't return strings as errors, throw exceptions.

    elif len(w) > 2:
        if w[0] == w[-1]:
            while len(w) > 2:
                w = w[1:-1]
                is_palindrome(w)

You call the function but you don't do anything with the result.

        if len(w) == 1:
            return True

        else:
            return False

This is equivalent to: return len(w) == 1

    else:
        return "ERROR: input contains two or less characters."

Why can't palindromes be zero or one characters? Also, throw exceptions, don't return strings.


Retrieve the index of the first element using a predicate

For "easier readability" you could extern the lambda expression form the find_if():

auto pred = [](const char* line) { return strlen(line) <= 10; };
auto it = std::find_if(collection + startAt,
                       collection + COLLECTION_SIZE,
                       pred);

Also make use of std::begin() and std::end():

auto it = std::find_if(std::begin(collection) + startAt,
                       std::end(collection),
                       pred);

At least (but probably not last), don't use raw arrays. Rather change collection to a std::array:

std::array<const char*,COLLECTION_SIZE> collection
    { "time11,time2,time3"
    , "time12,time2,time3"
    , "time13,time2,time3"
    , "time14,time2,time3"
    , "time15,time2,time3"
    , "x\n"
    , ""
    };
// Note my formatting style above, which makes it easier to extend the array

Here's the fully refactored code:

#include <cstring>
#include <iostream>
#include <algorithm>
#include <array>

const size_t COLLECTION_SIZE = 250; // rather use a const variable than a macro

int main()
{
    std::array<const char*,COLLECTION_SIZE> collection
        { "time11,time2,time3"
        , "time12,time2,time3"
        , "time13,time2,time3"
        , "time14,time2,time3"
        , "time15,time2,time3"
        , "x\n"
        , ""
    };

    size_t startAt = 2; // care about the correct type. auto would leave you with int

    // replace the loop to search an index by calling to standard library
    auto pred = [](const char* line) { return strlen(line) <= 10; };
    auto it = std::find_if(std::begin(collection) + startAt,
                           std::end(collection),
                           pred);
    auto posEmptyItem = std::distance(std::begin(collection), it);
    std::cout << posEmptyItem << std::endl;

    return 0;
}

See Live Demo


These critiques are mostly style and syntax related, and do not address your algorithm (you could probably find the simplest possible algorithm with Google anyway).

make decode and decodeMessage static
explicitly hide the constructor for BinaryCode, e.g.

// hide constructor
private BinaryCode() {}

remove unneseccary - 0 from encodedDigit and decodedDigit declarations
let decodeMessage calculate messageLength (fewer parameters are nearly always better)
avoid using magic numbers and string literals (-1, -2, "NONE", etc...)
create method lastChar and call it instead of messageLength - 1 e.g. int checkValue = lastChar(decodedMessage) - '0';

private static char lastChar(CharSequence sequence) {
    int lastIndex = sequence.length() - 1;
    return sequence.charAt(lastIndex);
}

replace decodedMessage.charAt(messageLength - 2) and decodedMessage.charAt(i - 1) with previouslyDecodedChar e.g.

char previouslyDecodedChar = '\0';
for (int i = 0; i < messageLength; i++) {
    // ...
    if (i > 0) {
        nextDecodedDigit -= previouslyDecodedChar - '0';
    }
    previouslyDecodedChar = decodedMessage.charAt(i);
}
int checkValue = lastChar(decodedMessage) - '0';
if (messageLength > 1) {
    checkValue += previouslyDecodedChar - '0';
}


Function which takes a string as input and returns the most frequent character

Here’s how I’d write this using the standard library:

#include <algorithm>
#include <unordered_map>
#include <string_view>

char most_frequent_char(std::string_view str) {
    std::unordered_map<char, int> counts;
    for (auto c : str) counts[c] += 1;
    return std::max_element(
        begin(counts), end(counts),
        [](auto a, auto b) {return a.second < b.second;}
    )->first;
}

But to be honest I’m not happy with manually iterating over the string to counts its characters. In actual code I’d probably abstract away the creation of a frequency table, which would presumably also have a max function. In Python this directly corresponds to the collections.Counter class. If we assume the existence of this utility class (left as an exercise to the reader), the implementation becomes

char most_frequent_char(std::string_view str) {
    return max(freq_table{str}).first;
}

Incidentally, in statistics this property is known as the “mode” of a distribution.


Compare large text File in java line by line

Your program's time complexity is \$O(n*m)\$ and space complexity is \$O(n + m)\$ where 'n' is no. of lines in the first file and 'm' is no. of lines in second file.

Here is an optimised version of the above program, with time complexity \$O(n + m)\$ and space complexity \$O( min(m,n) )\$. I have not tested this program, but it should be able to present output on the screen within few seconds :)

import java.io.*;
import java.util.*;

class Main{
   public static void main(String args[]){
      try ( BufferedReader reader1 = new BufferedReader(new FileReader("file1.txt"));
            BufferedReader reader2 = new BufferedReader(new FileReader("file2.txt")) ){

            //assuming file1.txt is smaller than file2.txt in terms of no. of lines
            HashSet<String> file1 = new HashSet<String>();

            String s = null;
            while( ( s = reader1.readLine()) != null){
               file1.add(s);
            }

            while( (s = reader2.readLine()) != null ){
               if(file1.contains(s))
                  System.out.println(s);
            }
      }
      catch(IOException e){
         System.out.println(e);
      }

   }
}

Note: Only one file is in memory at a time and HashSet<> instead of nested loops for comparison.


Parser for STL stereolithography data files

Well, it's not much of a mystery.  Your code is simple and pretty. Their code is ugly because it performs exactly what it needs to do, and no more:

} else if (!strncmp(sz,"vertex",6) && ::IsSpaceOrNewLine(*(sz+6))) { // vertex 1.50000 1.50000 0.00000
    if (faceVertexCounter >= 3) {
        ASSIMP_LOG_ERROR("STL: a facet with more than 3 vertices has been found");
        ++sz;
    } else {
        if (sz[6] == '\0') {
            throw DeadlyImportError("STL: unexpected EOF while parsing facet");
        }
        sz += 7;
        SkipSpaces(&sz);
        positionBuffer.push_back(aiVector3D());
        aiVector3D* vn = &positionBuffer.back();
        sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->x );
        SkipSpaces(&sz);
        sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->y );
        SkipSpaces(&sz);
        sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->z );
        faceVertexCounter++;
    }

A few differences in the amount of work it does:

There's no regex that needs to be compiled.
It's not splitting tokens into a list.  So, no list needs to be allocated and filled.  More importantly, no strings need to be allocated, copied, and destroyed.
The aiVector3D is allocated first, then each of the three numbers is parsed and written directly into the memory location of the coordinate, with no temporary variable assignments.

I'll also point out that your use of assert is improper.  You should only assert conditions that you know must be true due to logic.  You should not assert conditions that you hope to be true about the input.  If you compile with assertions disabled, then the validation code goes away!  That would introduce a bug, and possibly a security vulnerability.


For such a simple parsing job, I'd use a regular expression and re.findall()` to split the string into a list of tokens.  It's just one line instead of over 20 lines. The tokens are an element (an upper case letter possibly with a lower case letter), a repeat count (1 or more digits), or a bracket. The "{}[]" matches any of the brackets.
    tokens = re.findall(r"[A-Z][a-z]|[0-9]+|[](){}[]", string)

collections.Counter() is useful for counting the elements. Lists used as simple stacks help keep track of bracketed sub-compounds.
    composition = Counter()
    match = []
    stack = []

Using a list of tokens may be less optimal for large parsing tasks, but is sufficient for this command line calculator.  Plus, it lets you "peek" at the next token to see if its a number, greatly simplifying the handling of the numbers in a formula.  (I used an if-expression in the final code)
        if tokens[0].isalpha():
            element = tokens.pop(0)

            if tokens[0].isdigit():           # <-- peek at next token to see if
                repeat = int(tokens.pop(0))   #     there is a count
            else:
                repeat = 1

            compound[element] += repeat

When an opening bracket is encountered, save the current state (the Counter) on a stack and start a new state.  Save the matching bracket on a stack too.
        elif tokens[0] in ('(', '[', '{'):
            match.append(MATCH[tokens.pop(0)])
            stack.append(composition)
            composition = Counter()

When a closing bracket is encountered, see if it matches the one on top of the bracket stack.  Pop the saved state from the stack and combine it from the one for the bracketed sub-compound.
        elif tokens[0] == match[-1]:
            tokens.pop(0)
            match.pop()

            repeat = int(tokens.pop(0)) if tokens and tokens[0].isdigit() else 1
            for element in composition.keys():
                composition[element] *= repeat

            composition.update(stack.pop())

Any other token is an error.
        else:
            if token in (')', ']', '}'):
                raise ValueError(f"Error, mismatched bracket: "
                                 f"expected {match[-1]} got {tokens[0]}.")

            else:
                raise ValueError(f"Error, unrecognized token "
                                 f"in formula: '{tokens[0]}'.")

If there are any brackets left on the stack at the end, then there are mismatched brackets.
    if match:
        brackets = ', '.join(f"'{b}'" for b in match[::-1])
        raise ValueError(f"Error, missing bracket(s): {brackets}.")

The full parser:
import re

from collections import Counter

MATCH = {'(':')', '[':']', '{':'}'}

def parse(molecule):

    tokens = re.findall(r"[A-Z][a-z]?|[0-9]+|[]{}()[]", molecule)

    composition = Counter()
    match = []
    stack = []

    while tokens:
        # element with optional count
        if tokens[0].isalpha():
            element = tokens.pop(0)
            count = int(tokens.pop(0)) if tokens and tokens[0].isdigit() else 1
            composition[element] += count

        # start a sub-compound
        elif tokens[0] in ('(', '[', '{'):
            match.append(MATCH[tokens.pop(0)])
            stack.append(composition)
            composition = Counter()

        # matching close bracket ends a sub-compound with an optional count
        elif tokens[0] == match[-1]:
            tokens.pop(0)
            match.pop()

            repeat = int(tokens.pop(0)) if tokens and tokens[0].isdigit() else 1
            for element in composition.keys():
                composition[element] *= repeat

            composition.update(stack.pop())

        # "syntax" error in the formula
        else:
            if token[0] in (')', ']', '}'):
                raise ValueError(f"Error, mismatched bracket: "
                                 f"expected '{match[-1]}' got '{token[0]}'.")

            else:
                raise ValueError(f"Error, unrecognized token in "
                                 f"formula: '{token[0]}'.")

    # left over, unmatched brackets
    if match:
        brackets = ', '.join(f"'{b}'" for b in match[::-1])
        raise ValueError(f"Error, missing bracket(s): {brackets}.")

    return dict(composition)


This is based on the Luhn-algorithm, see this answer.

Those solutions are generic, i.e. for any input length, but for a specific length string I prefer a brute-force approach, no variables/loops/etc., just cut&paste&modify:

select -- luhn check digit
   (10-
     ( -- sum of all digits after doubling the odd digits
        Substring(inputString, 1,1)*2 % 10
      + Substring(inputString, 1,1)*2 / 10
      + Substring(inputString, 2,1)
      + Substring(inputString, 3,1)*2 % 10
      + Substring(inputString, 3,1)*2 / 10
      + Substring(inputString, 4,1)
      + Substring(inputString, 5,1)*2 % 10
      + Substring(inputString, 5,1)*2 / 10
      + Substring(inputString, 6,1)
      + Substring(inputString, 7,1)*2 % 10
      + Substring(inputString, 7,1)*2 / 10
      + Substring(inputString, 8,1)
      + Substring(inputString, 9,1)*2 % 10
      + Substring(inputString, 9,1)*2 / 10
     ) % 10 -- subtract the last digit
   ) % 10   -- in case last digit is a zero: 10 -> 0

Put it in a CASE to get 0/1:

case when previous calculation = Substring(inputString, 10,1)
     then 1
     else 0
end


Replacing MySQL's AUTO_INCREMENT with Postgres' SERIAL

The MySQL syntax for a CREATE TABLE command is, in part:

column_definition:
    data_type [NOT NULL | NULL] [DEFAULT default_value]
      [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
      [COMMENT 'string']
      [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]
      [STORAGE {DISK|MEMORY|DEFAULT}]
      [reference_definition]
  | data_type [GENERATED ALWAYS] AS (expression)
      [VIRTUAL | STORED] [UNIQUE [KEY]] [COMMENT comment]
      [NOT NULL | NULL] [[PRIMARY] KEY]

data_type:
    BIT[(length)]
  | TINYINT[(length)] [UNSIGNED] [ZEROFILL]
  | SMALLINT[(length)] [UNSIGNED] [ZEROFILL]
  | MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL]
  | INT[(length)] [UNSIGNED] [ZEROFILL]
  | INTEGER[(length)] [UNSIGNED] [ZEROFILL]
  | BIGINT[(length)] [UNSIGNED] [ZEROFILL]
  | REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]
  | DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]
  | FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]
  | DECIMAL[(length[,decimals])] [UNSIGNED] [ZEROFILL]
  | NUMERIC[(length[,decimals])] [UNSIGNED] [ZEROFILL]
  | DATE
  | TIME[(fsp)]
  | TIMESTAMP[(fsp)]
  | DATETIME[(fsp)]
  | YEAR
  | CHAR[(length)] [BINARY]
      [CHARACTER SET charset_name] [COLLATE collation_name]
  | VARCHAR(length) [BINARY]
      [CHARACTER SET charset_name] [COLLATE collation_name]
  | BINARY[(length)]
  | VARBINARY(length)
  | TINYBLOB
  | BLOB
  | MEDIUMBLOB
  | LONGBLOB
  | TINYTEXT [BINARY]
      [CHARACTER SET charset_name] [COLLATE collation_name]
  | TEXT [BINARY]
      [CHARACTER SET charset_name] [COLLATE collation_name]
  | MEDIUMTEXT [BINARY]
      [CHARACTER SET charset_name] [COLLATE collation_name]
  | LONGTEXT [BINARY]
      [CHARACTER SET charset_name] [COLLATE collation_name]
  | ENUM(value1,value2,value3,...)
      [CHARACTER SET charset_name] [COLLATE collation_name]
  | SET(value1,value2,value3,...)
      [CHARACTER SET charset_name] [COLLATE collation_name]
  | JSON
  | spatial_type

To handle the general case is a non-trivial task!  I highly recommend writing your parsing regexes such that they are recognizably based on the documentation.  (One question I have is why you look for BOOL(EAN)* when MySQL has no boolean type.)

According to the PostgreSQL documentation:

  The data types smallserial, serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTO_INCREMENT property supported by some other databases). In the current implementation, specifying:

CREATE TABLE tablename (
    colname SERIAL
);

  is equivalent to specifying:

CREATE SEQUENCE tablename_colname_seq;
CREATE TABLE tablename (
    colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;

Note that the equivalent MySQL syntax for that would be

CREATE TABLE tablename (
    colname integer NOT NULL AUTO_INCREMENT
);

If I were trying to machine-translate a database schema specification, I would prefer to independently translate the size-and-range aspect of the numeric type and the auto-incrementing nature of the column.  Otherwise, trying to handle the column name, the data type, any NOT NULL constraints, primary and foreign keys, etc. all at once will result in a mess.

Specifically, I would say that MySQL's AUTO_INCREMENT keyword translates directly to PostgreSQL's DEFAULT nextval(…), with a CREATE SEQUENCE … preamble and an ALTER SEQUENCE … OWNED BY … postamble.

Such a translation might not result in pretty and idiomatic PostgreSQL code, but the translation code would be more robust and maintainable.


Generating the pretty bit at the end of a URL

F# does have a String module, but it's almost empty. If you want to make string manipulations look more idiomatic, you'll have write functions that wrap System.String methods yourself (quick search didn't find anything existing):

let trim (input:string) =
    input.Trim()

let regexReplace (pattern:string) (replacement:string) (input:string) =
    Regex.Replace(input, pattern, replacement)

let replace (pattern:string) (replacement:string) (input:string) =
    input.Replace(pattern, replacement)

let toLower (input:string) =
    input.ToLower()

…

let parsed =
    x
    |> trim
    |> regexReplace "[^0-9a-zA-Z ]" ""
    |> replace " " "-"
    |> toLower

match String.length parsed with
    | m when m > 30 -> …
    | _ -> parsed

You don't need to try to differentiate from C# so hard. if would be more appropriate here:

if String.length parsed > 30 then …
else parsed

match parsed.IndexOf("-",30-1) with
    | p when p < 0 -> parsed
    | p -> parsed.[..p]

You can rewrite this to avoid having to reference p in both branches:

match parsed.IndexOf("-",30-1) with
    | p when p >= 0 -> parsed.[..p]
    | _ -> parsed

Also, use more descriptive names than p, like index or maybe pos.

Also, this code usually returns a string that's over 30 characters and ends with -. Is that what you intended?


Embedding a Text -> Maybe MyDataType function in a Parser to parse JSON into a custom data type

Modern functional programming and pizza are best friends, so I commend the usage of Haskell here.

As  PizzaType is already its own type, it's probably easiest to implement a FromJSON PizzaType instance. We know Parser is a monad, so we can use >>= to sequence parser computations together.

instance FromJSON PizzaType where
  parseJSON (String s) =
    maybe err pure (convertPizzaType s)
    where
      err = (fail . unpack) ("PizzaType: unknown type " <> s)
  parseJSON invalid =
    typeMismatch "PizzaType" invalid

instance FromJSON PizzaOrder where
  parseJSON (Object v) =
    PizzaOrder <$> (v .: "type" >>= parseJSON) <*> v .: "specialInstructions"
  parseJSON invalid =
    typeMismatch "PizzaOrder" invalid

I also recommend using two helpers:

typeMismatch to make the Aeson errors a little better. It's easy, with large JSON input, to quickly run into error hell where you have no idea where an error is coming from. Best to be specific early on.
maybe to convert values from Maybe a to Parser a.


Reading and printing a text file in Java

import java.io.*;

Never import the full package. It is considered bad practice to do so. Instead, import what you need and only what you need.

Instead of just reading a file then printing it, why don't you create a method that reads all line of a file and returns a list of all the lines? This way, you can do more with the result:

public static List<String> getAllLines(File file) throws FileNotFoundException, IOException {
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String buffer;
    String fulltext="";
    while ((buffer = br.readLine()) != null) {
        System.out.println(buffer);
        fulltext += buffer;
    }
    br.close();
    fr.close();
}

  I am especially concerned with resource leaks.

Since Java 7, there is such thing as a try-with-resources statement, which automatically closes the reader when an exception occurs, which you are not doing here. Your current code has memory leaks!

With some other improvements:

public static List<String> readAllLines(File file) {
    List<String> result = new LinkedList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
        for (String current = reader.readLine(); current != null; current = reader
                .readLine()) {
            result.add(current);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

By the way, this is actually the code I use often to read all lines of a file.


I do not understand why val was introduced in addition to value – it isn't even a copy of the contents.

On the other hand h does make sense once you consider thread safety. Assume we have two threads which calculate the hash of the string at nearly the same time – to trigger this, have both threads sleep for a moment when they enter the if branch. At the beginning, both threads will have hash == 0, so they will calculate the hash anew. With the original implementation, only a local variable is mutated, and then atomicaly committed to the hash variable. With your code, both threads mutate the same hash directly and will thus compute an invalid result. Your solution would be OK iff all accesses to the hash were synchronized (by locking the whole string object for each such method which is silly when using immutable strings).

As this is Code Review, I will also suggest to return early in both implementations, instead of putting the whole calculation into an if branch. It is also nicer to use a foreach loop than to use indices.

public int hashCode() {
    int h = hash; // copy for thread safety
    if (h != 0 || value.length == 0) return h;

    for (char c : value) {
       h = 31 * h + c;
    }

    hash = h; // commit the change
    return h;
}

On the other hand, a foreach-loop might not be as optimized as looping over the indices, and an early return could also impact what code is generated.

Edit: The value.length > 0 test in the original avoids committing the old value when no change of the hash is required (for the empty string). This can be relevant in cache-sensitive applications (remember that writing to shared memory can invalidate caches for other processors as well – we want to avoid this if possible. The condition also provides the guarantee that the loop will execute at least once if that branch is taken. Code ought to be generated in a way that this prior check does not reduce performance – on the contrary.


There's not much to say. Overall, the code is small and quite readable.

Just a small nitpick:

if (getUTF8CharCode($currChar) < 256 && //Character value is less than 256
    !preg_match("/^\w$/", $currChar) && //Character is not alphanumeric (underscore is considered safe too)
    !in_array($currChar, $immuneChars)  //Character is not immune

These comments say the what, not the why. They're akin to:

$i++; // increments i by one

Your if condition should be commented, but not like this.

I can't comment on the security-side of things.


Conversion of an array of integers to string

If you are going to be playing with string representations of native types, you probably want to take a look at the struct standard library package.

With it, you can quickly process your r as follows:

>>> import struct
>>> ''.join(struct.pack('i', rr) for rr in r)
'012345678\x00\x00\x00\x00\x00\x00\x00'

And you can play with the ordering of the characters by explicitly describing the endianess of your input:

>>> ''.join(struct.pack('>i', rr) for rr in r)  # big endian
'32107654\x00\x00\x008\x00\x00\x00\x00'


Python3 - Determing if a PDF is scanned or "searchable"

How about the PDF metadata check on '/Resources' ?!

I believe for any text in a PDF (electronic document) there are more chances of having a font, especially the PDF, whose objective is to make a portable file, so, it maintains the font definition.

If you are a PyPDF2 user, try

pdf_reader = PyPDF2.PdfFileReader(input_file_location)
page_data = pdf_reader.getPage(page_num)

if '/Font' in page_data['/Resources']:
    print("[Info]: Looks like there is text in the PDF, contains:", page_data['/Resources'].keys())
elif len(page_data1['/Resources'].get('/XObject', {})) != 1:
    print("[Info]: PDF Contains:", page_data['/Resources'].keys())

for obj in x_object:
    obj_ = x_object[obj]
    if obj_['/Subtype'] == '/Image':
        print("[Info]: PDF is image only")


Optimizing Java SHA-512 String-to-Hash Generator

You should extract the hex encoding into its own method.

See How to convert a byte array to a hex string in Java? for various implementations.
input.getBytes() uses the locale dependent legacy encoding. So you won't get reproducible results on different systems. Specify an encoding explicitly, I recommend utf-8.


Separate models for rest API POST and GET

I would not over-complicate the matter by splitting it up in several models. But if you want to stick to the choice of splitting it up, I would define an abstract base class and create a Create and Read model.

Because in the current situation I find the naming not 100% clear. Certainly because EmailModel (which sounds generic/basic) derives from CreateEmail (which is specific). It should be the other way around, a specific class should inherit from a generic/basic class.

Here's a rough implementation:

public abstract class EmailModel
{
    public string Subject {get; set;}
    public string Body {get; set;}
}

public class CreateEmailModel : EmailModel { }

public class ReadEmailModel : EmailModel
{
    public int Id {get; set;}
    public List<AttachmentModel> Attachments {get; set;}
}


you should use an abstract class and an interface. also define the doPrint method as static when you want to call it static.

abstract class worker {

    /*...*/

    public static function doPrint(worker_interface $who) {

        /*...*/
    }
}

interface worker_interface {

    public function isWhat();
    public function setName($name);
}

class boss extends worker implements worker_interface {

    public function isWhat() {

        return 'the boss';
    }
}

class bee extends worker implements worker_interface {

    public function isWhat() {

        return 'not the boss';
    }
}

define the type for all methods you are passing worker instances to like in doPrint

EDIT:

alternatively you could also just add an abstract function instead of using an interface

abstract class worker {

    /*...*/

    public static function doPrint(worker $who) {

        /*...*/
    }

    public abstract function isWhat();
}

class boss extends worker {

    public function isWhat() {

        return 'the boss';
    }
}

class bee extends worker {

    public function isWhat() {

        return 'not the boss';
    }
}


I'd suggest taking a look at jquery-boilerplate, especially the jqueryUI widget portion.

I started refactoring your code in a true $widget manner. It's not completely functional but should point you in the right direction.

;(function ( $, window, document, undefined ) {
  $.widget("yourCustomNamespace.slider", {

    /*
     * Options to be used as defaults:
     */

    options: {
      autoplay: true,
      controls: true,
      duration: 750,
      slideSize: '100%',
      selectors: {
        slideRail: '[data-function~="slide-rail"]',
        slide: '[data-function~="slide"]',
        next: '[data-function~="next"]',
        prev: '[data-function~="prev"]',
        play: '[data-function~="play"]',
        pause: '[data-function~="pause"]',
        stop: '[data-function~="stop"]'
      }
    },

    /*
     * Private Methods:
     */

    _create: function() {
      this._setOption("current", 0);
      this._setOption("total", this.element.children().length);
      this._on(this.element, {
        "hover " + this.options.selectors.slideRail: $.proxy(this.stop, this),
        "click " + this.options.selectors.next: $.proxy(this.next, this),
        "click " + this.options.selectors.prev: $.proxy(this.prev, this),
        "click " + this.options.selectors.stop: $.proxy(this.stop, this),
        "click " + this.options.selectors.pause: $.proxy(this.pause, this),
        "click " + this.options.selectors.play: $.proxy(this.play, this)
      });
      if(this.options.autoplay) {
        this.start();
      }
    },
    _destroy: function() {
      this._off(this.element, "click hover");
    },
    _setOption: function(key, value) {
      switch (key) {
        case "current":
          // Update internal object ...
          this.options[key] = value;
          // Update DOM ...
          // this.element.find(this.options.selectors.slideRail.animate({...}, this.options.duration) ...
          break;
        default:
          this.options[key] = value;
          break;
      }
      return this._super("_setOption", key, value);
    },

    /*
     * Public Methods:
     */

    next: function() {
      // TODO: Account for overflow, this.options.total
      this._setOption("current", this.options.current + 1);
    },
    prev: function() {
      // TODO: Account for underflow, this.options.total
      this._setOption("current", this.options.current -1);
    },
    restart: function() {
      this._setOption("current", 0);
    },
    start: function() {
      this.interval = window.setInterval($.proxy(this.next, this), this.options.duration);
    },
    stop: function() {
      window.clearInterval(this.interval);
    },
    getCount: function() {
      return this.options.total;
    }
  });
})( jQuery, window, document );

Reference

There are a couple of things regarding reusability going on in here:

options are your default parameters that can be overwritten on initializing a new widget instance, e.g. $('[data-widget~="slider"]').slider({autoplay: false}); would overwrite the default of autoplay: true
Event binding is handled internally via this._on()
Ideally the widget would manage its own application state logic via this._setOption(). That way you can distinguish between logic and DOM interaction. Whenever a value changes, you update the DOM accordingly.
You can call public methods from other places via the automatic interface the widget provides, e.g. $('[data-widget~="slider"]').slider("next")


Send parameter to server and reload page

To get the current page you could use this (as long as the javascript is in your layout file or other view, this will not work if in an external js file):

<%= Request.Url.PathAndQuery %>

I would suggest using ajax to call an api that returns json with a success status since you sound like you are using jquery quite a bit. If the call is successful, then set the window.location to the current page, if it fails, then you can gracefully handle the error.  Here is an example of the controller:

public JsonResult UpdateLanguage(string language)
{
   var languageUpdated = LanguageEngine.UpdateLanguage(language);  // Your code to update db

   var json = new
   {
       success = languageUpdated,
       newLanguage = language
   };
   return Json(json);
}

Then you can use a regular ajax call or something like jQuery getJSON function:

$.getJSON("../UpdateLanguage", { language: "Chinese" },
    function (data) {
        if (data.success === true) {
            window.location = currentPageUrl;
        }
        else {
            alert("Sorry, we failed to update the language to '" + data.newLanguage + "'.  Please try again.");
        }
    }
};

Is this way much better?  That I am not so sure.

Another strategy would be to include a base model that all your view models inherit from that contains a property for language and current page (with query results if you use them), then set this when then they change the drop down and call a controller to update the language which should take the base model object as a param, after the controller finishes the update, it can then redirect you back to that page.  The nice thing about this strategy is you can include other information that is typically useful on every page, such as the logged in user object.  This is also more "MVC-y" in my opinion, but probably a lot more work depending how far your project is.


Expect script that tests if a passwordless connection is setup

A couple of notes:

expect is an extension of Tcl, so you can use any Tcl command: http://www.tcl-lang.org/man/tcl8.6/TclCmd/contents.htm

specifically, you could write
lassign $argv user server

which is arguably a bit less readable, but is only one command.

You can speed up the timeouts: the default is 10 seconds, and you probably don't want to wait for 20 seconds to get the final exit status:
set timeout 1   ;# in seconds

you never reset the rc variable, and the default exit status is zero already, so you can remove set rc 0 and exit $rc

expect is not bash: you don't need to quote all the variables.

you don't need to reset log_user just before exiting the script.

expect code written in this style can get pretty deeply nested: The last pattern in an expect command does not need an action block
expect {
  $pwd_prompt  { exit 1 }
  eof          { exit 2 }
  timeout      { exit 3 }
  $prompt
}
send "hostname\r"
expect {
  *$server*    { exit 0 }
  eof          { exit 4 }
  timeout      { exit 5 }
}

If $prompt is seen, then that expect command ends, and the script continues with send


Your code has a few problems.

You should learn to not use using namespace std;. It's generally frowned upon.
You should never use while(!inFile.eof()). It's pretty much a guaranteed bug.
You should use standard algorithms when they're applicable (as they are here).
Prefer to fully initialize variables at creation (e.g., pass file name when you create a filestream object).
Generally let the destructor handle destruction (e.g., let the filestream object close when it goes out of scope)1.

I'd also strongly prefer to take command line arguments over prompting for input at run time.

I'd write the code using the standard distance algorithm, something like this:

#include <fstream>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <string>
#include <cstdlib>

int main(int argc, char **argv) {
    if (argc < 2) {
        std::cerr << "Usage: count_words <infile>\n";
        return EXIT_FAILURE;
    }

    std::ifstream infile(argv[1]);

    std::istream_iterator<std::string> in{ infile }, end;

    std::cout << "Word count: " << std::distance(in, end);
}

There are a few cases where it makes sense to manually close a file. For example, if you're moving a file between file systems by copying its content, then deleting the original, you want to do everything you can to ensure the copy completed successfully (including successful closing) before you remove the original. Anything that might destroy the user's data calls for extraordinary measures to assure safety. This isn't one of those cases though.