Implementation issues

using namespace std; is frowned upon, especially in header files. Assuming MyStack is intended to be included elsewhere, this might cause name collisions in other unrelated code.

There's a superfluous (and possibly confusing) semicolon after default constructor.

Memory leak: If something inside the copy constructor were to throw an exception (e.g. one of those calls to new), already created nodes will not be deleted.

Another memory leak/bug in the copy constructor: pre doesn't get advanced during the while loop, so it's always pointing to top_node. Every assignment pre->next = cur overwrites the current value of top_node->next, resulting in a stack of depth 2.

Also, since the copy constructor doesn't modify st, it could be made const MyStack&.

Memory leak: MyStack<T>::push leaks temp in case the Node constructor throws an exception (e.g. because Ts copy constructor throws one).

Wrong return type: MyStack::top() is declared to return an int, but actually returns MyStack<T>::Node::val, which is of type T.

No need for top_node = nullptr inside the destructor: Nobody is going to read that value again.

The whole destructor body could be extracted into a clear member function, which the destructor then calls.

A lot of the member functions (basically everything not calling new) can be marked noexcept. Doing so allows for better code generation and allows others to use MyStack to its fullest.

pop doesn't decrease count.

Design issues

MyStack::print might be helpful with debugging, but likely shouldn't be in the final product (unless there is a specific requirement for it).
print can likely be very easily implemented using an iterator interface if one is provided.

MyStack is unable to contain types that cannot be copy-constructed. Think about splitting push(T) into two functions push(const T&) and push(T&&), and maybe add an emplace member function that forwards its arguments in order to construct the T in place.

top could return a referene instead of a copy. This prevents issues with non-copyable types. Might require two overloads, though (const T& top() const and T& top()), to accomodate for constness of this.

Technically, MyStack<T> can be copied only if T is copy-constructible. This can be asserted at compile time using some template metaprogramming (which might be too advanced at the moment), but at the very least I'd expect this behavior to be documented.

C++11 features
C++11 introduced smart pointer like std::unique_ptr and std::shared_ptr into the standard library. You might want to read up on them, as they come in quite handy and help a lot to prevent memory leaks. Just know their limits (recursive destruction/cycles).
Using them would have prevented a lot of the memory issues mentioned above. For more information on the topic I can recommend this talk by Herb Sutter.

Also, C++11 introduced {} for object initialization, in order to "fix" the so-called most vexing parse: What is foo in the following snippet?
int foo(A);

That answer depends on what A is:

If A can be interpreted as a type then foo is declared as a function taking an A as parameter and returning an int.

If A is a value then foo is a local int variable that gets initialized to the value of A.

In order to prevent this ambiguity (and a huge list of similar ones) prefer to use brackets {} for object initialization instead of () if possible.

There are some cases where this isn't possible; however, those cases are rare (I can only think of one off my head, and that's the std::vector<T>::vector(size_t, T) constructor where T is some arithmetic type like int or float, as the initializer-list constructor takes precedence there).

Q&A

What should top() return if the stack is empty?

What can it meaningfully return? Nothing!
The precondition of calling top is that the stack must not be empty. If top is called while the stack is empty, that operation is meaningless. You can be nice and throw an exception to signal that this function was called erroneously, or not be nice and force checking upon the caller in order to avoid internal nullptr dereferences.

Usually, stack implementations throw an exception, unless the environment forbids those or safety is sacrificed to gain some minimal performance.

Why it’s better to use size_t for count?

This point has been up for debate quite a lot, and most often the consensus is: Don't use unsigned values for sizes, as it can cause unexpected interactions with signed values.

It got into the standard library as "the" size type because they wanted to use another bit for size (in order to use up to 4 GiB RAM on 32-bit machines), but in hindsight (and with modern 64-bit processors) the unexpected interactions with signed values tipped the scale towards that conclusion.

I didn’t use new to create the stack in main(). Do I need to call the destructor? If no, why? If yes, how should I do it?

sasa and sec in main have automatic storage duration, which means that they get automatically destructed once they fall out of scope (at the closing } of main) in reverse order of construction.

According to the rule of three, how will I define the assignment operator for stack? Can you give one example?

The "Rule of Three" got extended to "Rule of Five" in C++11 and onwards in order to accomodate for move constructors and move assignment operators. So, let's get started with those additions (as they are fairly easy to implement):
MyStack(MyStack&& other) noexcept : top_node{other.top_node}, count{other.count} {
    other.top_node = nullptr;
    other.count = 0;
}

MyStack& operator=(MyStack&& other) noexcept {
    if(this != &other) {
        // destroy current list
        clear();

        // move others list
        top_node = other.top_node;
        count = other.count;

        // leave other in a valid state
        other.top_node = nullptr;
        other.count = 0;
    }

    return *this;
}

One way to do the copy assignment operator is to use the copy-and-swap idiom:
MyStack& operator=(const MyStack& other) {
    auto copy = other;
    swap(other);
    return *this;
}

But this requires a swap function, which might look like this:
void swap(MyStack& other) noexcept {
    using std::swap;
    swap(top_node, other.top_node);
    swap(count, other.count);
}

Most implementations also provide a freestanding swap(MyType& a, MyType& b) function (which basically forwards to a.swap(b)) to allow their types to be used in this fashion.

I feel I have some misunderstanding about private. I put top_node in the private section, but why I am able to access top_node in the copy constructor?

You can access st.top_node and st.count inside the copy constructor because you are still inside the same class!
private just means "nobody outside of this class (or its friends) can see this" - but the copy constructor is obviously inside. (Otherwise, how could it initialize this->top_node?)
This level of access can also be granted to other classes or functions by making them a friend of the class:
class A;
void foo(B b);

class B {
    friend class A;
    friend void foo(B b);

    int c;
};

Now B::c is visible inside A or foo, too.

Use this sparingly, though, as it breaks encapsulation. Sometimes it is needed, but more often than not there is a better alternative available.


Correctness

In createOrders(passenger) you use an if-else statement. This has a major issue when you misspell a ticket name.

Extensibility

I would say that your code has 2 major issues that prevent it from being easily extendible:

Ticket names are arbitrary strings. They are easily mistyped, and would lead to all kinds of funky business. While javascript does not have something like enum, you could create your own and use something like this:

var TicketTypeEnum = {
  "COUCH" : "couch",
  "FIRSTCLASS" : "firstclass"
};
if( Object.freeze ) {
  Object.freeze( TicketTypeEnum );
}

This has two benefits. First of all it is immediately clear which ticket types are available. The second benefit is that if you now try to set it to something mistyped, it is undefined. If you would implement something like addPassenger(..) this is easily enough detected.

Similarly, you can have an Object of possible services.
createOrders(..) will become a giant mess when adding more services or more ticket types. There are various ways in which you could improve that:

It is possible to create an Object containing Objects, then retrieve services[ticketType][serviceType] if you want to get the handler for a service given a particular ticket type.
You could have just an Object of services, and assign functions to each of them. Each of these functions switch for ticket type if needed.
You can have a Service class which you can feed a ticket type when called. The difference here being that you can have more advanced logic inside this "Service" abstraction.

I personally would prefer the first option or the third option. In both cases you probably should create a function that adds handlers per ticket type, or adds a Service object to your collection of possible services. You can then easily check if a service or ticket type is forgotten when calling that function, and output an error before you try to serve your customers. In other words: It breaks when setting up the program instead of after an unknown amount of runs.

Note: Your stewards and stewardesses are angry at you for not being called cabin crew. Then again, they are virtual, so you probably don't have to care about this.


Python Find the N adjacent digits in the 1000-digit number that have the greatest product

Review

Yes the first option would be better as memory might become an issue with really long numbers (say you have a 10 million length number). But that implementation could be improved as well

Your first solution does not return the max product but rather a list generator of products. This is confusing!
Chop up your code into functions, as it makes it easier to test/change things

The problem can be divided into to 3 seperate functions:

Cut a big number into evenly sized chunks of adjacent digits
Sum the product of the chunks
A main function that returns the largest adjecent product

Alternative Code

from functools import reduce
import operator

def cut_adj_chunks(iterable, chunk_size):
    for i in range(len(iterable) - chunk_size):
        yield iterable[i:i+chunk_size]

def sum_prod(num_str):
    num_list = map(int, num_str)
    return reduce(operator.mul, num_list, 1)

def largest_prod(adj_digits, big_num):
    return max(sum_prod(chunk) for chunk in cut_adj_chunks(str(big_num), adj_digits))


First problem you'll face is that IE, Opera, Firefox, Chrome and Safari aren't the only browsers in town. There are a lot of other browsers! Even the Steam app is just a browser. Anything that uses a form of WebView, or embedded browser (like game client patcher news sections) is also a browser. That equates to a lot of UA strings to account for.

The next problem is the most common problem with this approach: UA strings can be spoofed. Making it worse, browsers up to this day still spoof their UA to pretend like some other browser. For instance, Chrome 45 has the "Safari" and "AppleWebKit". With your code up there, you can easily mistake it for Safari or some other WebKit browser, even when Chrome 45 isn't Safari nor WebKit.

Now if you do want to do it in this approach and not mind the problem of playing catch-up with the latest browsers, then your first problem would be the use of jQuery. You seem to use it just to add and remove classes. Why not construct your determinations in an array, then just form a string afterwards?

var determination = [];

if(chrome) determination.push('isChrome');
if(webkit) determination.push('isWebkit');

var classes = determination.join(' ');

Another thing I notice is that you add your classes on the element you're attaching the plugin to. This also means your script runs every time you attach it, which is unnecessary. Why not run this script just once, during page load? For CSS purposes, you can attach your determinations as a class of <html> and prefix your styles with the class. If you use it for conditional scripts, you can store your determinations in a global variable and use indexOf.

// Put classes to <html>
document.documentElement.className = document.documentElement.className + ' ' + classes;

// Hide all inputs on all non-ie browsers
.not-ie input{
  display: none;
}

// Checking if IE with JS
if(~determinations.indexOf('lt-ie11')) alert('Y U NO USE NEW BROWSER???');

Now for your tests. As mentioned earlier, you might want to be more specific on your tests so that you won't be confusing a browser with another. Also, your tests are tied to each other. I don't know where the IE tests start and end. Everything's all over the place. Try breaking them apart into "plugins" so that you can easily just add in new tests.

BrowserTester.addTest('IE test', function(ua){
  // Add to this array all the classes you want to be put for this browser
  var classes = [];

  // do comparisons to check for IE

  // Return a string of classes for this test.
  return classes.join(' ');

});

// Do the same for other browsers
BrowserTester.addTest('Chrome', function(ua){...});
BrowserTester.addTest('Safari5', function(ua){...});
BrowserTester.addTest('Safari6', function(ua){...});

// Run tests. Add classes to <html>, expose an API to check which browser.
BrowserTester.run();


Merging, sorting and limit Map streams using Java 8

The question for a "better" solution is bound to be quite opinion-based. As far as the actual code goes, I think you are quite close to the optimum. As for readability... well, Roland already shared his initial thoughts and I totally agree. This is bound to be a nightmare for the poor maintenance programmer.

Thus: a suggestion which is nothing new, but just a little rearangement:

private Map<String, Long> getHistogramTopFive(Map<String, Long> map1, Map<String, Long> map2) {
    Map<String, Long> mergedMap = (Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Long::sum)));

    Map<String, Long> topFive = mergedMap.entrySet().stream()
        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .limit(5)
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (v1,v2) -> v1,
                LinkedHashMap::new));

    return topFive;
}

By putting it into a method and naming this method, you document your business intention. Furthermore, by breaking up the long command chain with a new mergedMap variable in between, the code gains much in readability.

The additional line-breaks in the second part are what I consider best practices in streaming API: each new operation on a new line.


There are many changes to the css through jquery that could just be handled by adding a class to devInfo.

I...

Changed some variable names for readability
Created some variable constants for readability
Created single responsibility functions for clean code
Only transformed elements to jQuery once and stored in a variable starting with '$'
Extracted out the style from js and put it in css
Prevented the link's default action from going
Added functionality to add/remove the 'expanded' class

The code is completely untested. So there is probably some syntax issues, but let me know what you think.

CSS

.devInfo a.more img {
    margin-bottom:.25em;
    margin-left:1.25em;
    vertical-align:middle;
}

.devInfo.expanded a.more {
    background-color: #d6e5f4;
}

.devInfo.expanded {
    background: url();
}

.devInfo.expanded .span {
    text-indent: 1000px;
    text-overflow: clip;
}

JS

$(function () {
    var ExpandedChar = "-",
        ColapsedChar = "+",
        ExpandClass = 'expanded';

    var toggleDetails = function(event) {
        event.preventDefault();

        var $moreLink = $(this),
            $details= $moreLink.next('.details'),
            $devInfo = $moreLink.closest('.devInfo');

        var displayLoading = function() {
            $devInfo.prepend(buildLoadImage()).fadeIn(400);
        };

        var hideLoading = function() {
            $devInfo.children("img").fadeOut(600);
        };

        var insertDetails = function(html) {
            $details.prepend(html).slideDown(500);
        };

        var getDetailsFor = function(deviceId) {
            $.ajax({
                 type: "POST",
                 url: "helpers/getDetails.php",
                 data: {deviceId: deviceId},
                 cache: false,
                 beforeSend: displayLoading,
                 success: insertDetails,
                 completed: hideLoading
             });
        }

        if (isColapsed()) {
            expand();
            getDetailsFor($moreLink.attr("data-name"));
        } else {
            colapse();
        }

        function expand() {
            $devInfo.addClass(ExpandClass);
            $moreLink.text(ExpandedChar);
            showDetails();
        }

        function showDetails() {
            $details.slideUp(1000);
        }

        function colapse() {
            $devInfo.removeClass(ExpandClass);
            $moreLink.text(ColapsedChar);
            hideDetails();
        }

        function hideDetails() {
            $details.slideUp(700);
        }

        function isColapsed() {
            return $moreLink.text() == ColapsedChar;
        }

        function buildLoadImage() {
            return $('<img />').attr('src', '/images/css/loader_small.gif');
        }
    }

    $(".more").live("click", toggleDetails);
});


Some notes:

find_deviation(v, d): Try to write more meaningful names for variables. Specially, I'd give a plurar name to v, since it's a collection.
max = 0, each, inline if: All of this denote you think in imperative terms. Some notes on functional programming with Ruby.

I'd write, with a functional approach:

def find_deviation(values, m)
  values.each_cons(m).map { |xs| xs.max - xs.min }.max
end

Now, this function has exactly the same time complexity than yours (though it may be faster or slower depending on how Ruby works). The complexity is: len(values) = n -> O(n*m). Note that you can use Enumerable#minmax to avoid one traversal, but it's still the same complexity.

To make it faster here's an idea, even though it's not trivial to implement: use a structure with O(log n) times for insertion/deletion/max/min (a binary search tree is ideal for this) to hold values of the sliding window, this way the overall complexity is O(nlog m). I guess some of the tests have big values of m so the trivial approach O(nm) is too slow.

[edit] Just for fun, I wrote a O(n log m) implementation in Haskell (I found no BST gem for Ruby):

deviation :: (Num a, Ord a) => [a] -> Int -> a
deviation [] _ = 0
deviation xs m = maximum $ [Tree.maximum w - Tree.minimum w | w <- windows]
  where
    windows = scanl shift (Tree.fromList $ take m xs) (zip xs (drop m xs))
    shift window (old, new) = Tree.insert (Tree.delete window old) new


C++ - algebraic expressions calculator by addition

Namespaces

You almost never want to write using namespace std; - this is a very common code complaint on this site with C++. The two main reasons are:

it's good to know when you're using stuff from the standard library explicitly,
standard library names can collide with your own since they've picked the best names!

auto

Consider also using return type deduction here as your functions are fairly trivial, and the following would work:

auto addition(int a, int b) { return a + b; }

The compiler has no trouble working out the return type is clearly an integer, and this will apply to other cases. Another use of auto is in your copy in the multiplication function, for example,

auto multiplication(int a, int b){
    auto result = a;
    // rest of code
}

You can apply this to a lot of other statements in your code. Depending on your style preference and the importance you place on uniformity, you can use the uniform initialisation syntax, auto result{a}.

Division

There's a problem in your division function. It returns counter which is an integer, and the return type is an integer - that's fine. But it can return false.

This compiles, and returning false will be like returning zero, but just do that explicitly, your return type isn't bool.

I would also move the declaration of the counter variable to inside the if statement, since if that statement fails, you don't need it.

So, if the integers don't exactly divide each other, you don't want to handle that case and you return zero. But you don't check this when outputting to the user. They'll get zero, so I'd opt for an explicit message, since that can have multiple interpretations.

In C++, return 0 is not required explicitly in main, so omit it. There's also an argument against it along the lines of, if you do include it, it's suggesting main can fail and that there are potentially other error codes that one must check for.


Convert rows with multiple values to row with single value

It is probably easier to work with the underlying Numpy array directly
than through Pandas. Ensure that all factor columns comes before all
data columns, then this code will work:

import pandas as pd
import numpy as np

np.random.seed(seed=1234)

n_rows = 100
n_cols = 6
n_factor_cols = 2
n_data_cols = n_cols - n_factor_cols
arr = np.random.randint(0, 100, size=(n_rows, n_cols))
factor_cols = arr[:,:n_factor_cols]
data_cols = [arr[:,i][:,np.newaxis] for i in range(n_factor_cols, n_cols)]
stacks = [np.hstack((factor_cols, data_col)) for data_col in data_cols]
output = np.concatenate(stacks)

The above code assumes that order is not important. If it is, then use
the following instead of np.concatenate:

output = np.empty((n_rows * n_data_cols, n_factor_cols + 1),
                  dtype = arr.dtype)
for i, stack in enumerate(stacks):
    output[i::n_data_cols] = stack

This is the best I can do, but I wouldn't be surprised if someone
comes along and rewrites it as a Numpy one-liner. :)


To code in a more functional style, break it down starting with the smallest pieces.  I would do it like this:

(defn head-accum [n coll]
  (reduce + (take n coll)))

(defn tail-accum [n coll]
  (reduce + (drop n coll)))

(defn pair-accum [n coll]
  [ (head-accum n coll)
    (tail-accum n coll) ] )

(defn all-pair-accum [coll]
  (let [n-vals (count coll) ]
    (for [split-val (range 1 n-vals) ]
      (pair-accum split-val coll))))

(println (all-pair-accum (range 11)))

;=> ([0 55] [1 54] [3 52] [6 49] [10 45] [15 40] [21 34] [28 27] [36 19] [45 10])


#include <string.h>

We don't use any of the definitions of this header, so it can safely be omitted.

#define MAXLEN 100

Why 100?  More importantly, what happens when we reach this maximum length?  We probably need to add some code to stop producing output when it's reached.  The provided interface expand(s1,s2) doesn't allow us to tell the function how much space is available to write into s2, so that's probably out of scope for the exercise, but consider implementing expand(s1,s2,max_len) as a further exercise (and a good one, that will be useful in your future C coding).

What should the output be for a-b-c?  Your program produces abbc, but I don't know if that's expected.  At least add a comment to document your assumptions.  Other possible interpretations include abc and ab-c, so explain why you've chosen abbc for this input.

Another problematic test case: --5.

Use const for the input string.  If we also return the start of the output, we can use the function more naturally:
char *expand(const char *s1, char *s2) {
    char *const s2_start = s2;

    /*...*/

    return s2_start;
}

int main(void) {
    char s2[MAXLEN];
    puts(expand("--5", s2));
}

Note that I've used puts() as a simpler alternative to sprintf("%s\n", ).

Your indexing is odd and inconsistent.  I see s1[0] mixed in with *s, and *(s1 + 1) in place of the simpler s1[1].  You can also make use of the value of increment expressions, like this:
if (*s1 == '-') {
    *s2++ = *s1++;
}

            char i = prev;
            if (prev < next)
                while (i <= next)
                    *s2++ = i++;
            else
                while (i >= next)
                    *s2++ = i--;

Improved code
I've completely re-written, observing the above changes:
#include <stdio.h>

char *expand(const char *s1, char *s2, int max_len) {
    char *const s2_start = s2;
    char *const s2_end = s2_start + max_len - 1;

    while (*s1 && s2 < s2_end) {
        if (*s1 == '-' && s2 != s2_start && s1[1]) {
            /* spotted hyphen not at beginning or end */
            char first = s1[-1];
            char last = *++s1;
            /* produce a range first..last,
               exclusive (we've already written first) */
            if (first == last) {
                ++s1;
            } else if (first < last) {
                /* ascending */
                for (char i = ++first;  i < last && s2 < s2_end;  ++i)
                    *s2++ = i;
            } else {
                /* descending */
                for (char i = --first;  i > last && s2 < s2_end;  --i)
                    *s2++ = i;
            }
        } else {
            /* copy to output */
            *s2++ = *s1++;
        }
    }
    *s2 = '\0';

    return s2_start;
}

#define MAXLEN 100
int main(void) {
    char s2[MAXLEN];
    puts(expand("a-z-a-z-a", s2, MAXLEN));
}


If the input with the placeholder="Email" is actually an email address, then the type attribute should be set to email, not text.  (Reference: http://www.w3.org/TR/html-markup/input.email.html)
Declare an id attribute and a name attribute on the email field.  This will be necessary if you want to access the elements or their posted values explicitly. (Reference: http://reference.sitepoint.com/html/input/name , http://reference.sitepoint.com/html/core-attributes/id)
Once you have declared an id on the input, set the for attribute on the label equal to that id.  This will enable a behavior such that clicking on the label will focus on the input for the corresponding field.  (Reference: http://reference.sitepoint.com/html/label)
Use descriptive, semantic class names.  Good class names should indicate the nature of the content, not the format of the layout.  Instead of fieldwrapper try sender-email. (Reference : http://www.w3.org/QA/Tips/goodclassnames )
This depends on what HTML version you are using, but the HTML5 spec says that form elements should be wrapped in p tags, not divs.  (Reference: http://dev.w3.org/html5/spec/forms.html#writing-a-form's-user-interface)

The code that would correspond to my comments might look like :

    Sender email address:
    <input id="sender" name="sender" type="email" placeholder="Email" class="r2">

This is just me explaining how to use this particular field. It is very interesting, don't you know...

One thing you'll notice is that there are less CSS classes.  I have replaced the field-wrapper with email-input and completely removed the field class.  You can migrate the .field-wrapper CSS to the .email-input selector, and the field CSS to the .email-input > input selector.


Present database results based on form submission

Well... First we can shorten your if-construct a lot:

$sql = 'SELECT * FROM artikel_tbl';
if ($_POST['type'] == 'Info' || $_POST['type'] == 'Berita')
  $sql .= " WHERE type = '{$_POST['type']}'";
$sql .= ' ORDER BY id';

In my opinion this also increases readability, because it is clear that the query is basically everytime the same, you are just including a condition in one case.

Next thing the if(($no%2)==0)-part. Do you know about the nth-child of css? Here is an example for that: http://jsfiddle.net/2ZR2U/

For these things: <?php echo $show['judul']; ?> change this to read <?php echo htmlspecialchars($show['judul']); ?>. Unless you are very sure that the input is just a number or something that is guaranteed to not contain any of [<>"] this is very important to prevent display bugs or in worst case cross site scripting attacks.


PHP function to obtain model_name from Namespace\To\ModelName

You tagged laravel, so this answer assumes you are using Laravel.

Laravel has two built in helper functions that will help you do this. class_basename() will return the name of the class with the namespace stripped off, and snake_case() will convert a string to snake case.

Combine them, and you get:

public function getModelName()
{
    return snake_case(class_basename(__CLASS__));
}


Fetch StackOverflow questions and save them to a markdown table

Things look good and well organised at first glance. However, there are a few things you can make use of.

Use f-string over using str.format. The former is more performant.
You can group the columns and iterate over them, instead of having multiple lines for each section. This way, you can add/remove to this iterable without having to change much of the code itself.
When using raw strings, you do not need to escape the - character, unless they are being used inside a character set (for regex).
The build_table can be split to another separate function.
Use type hinting.
If you're not using kwargs, no need to declare them.

Rewritten snippets (you might need to fit them in your code accordingly):
sections = (
    {'tag': "pandas", "marker": "pandas"},
    {'tag': "beautifulsoup", "marker": "bs"},
    {'tag': "python", "site": "codereview", "marker": "code_review"},
)
for section in sections:
    questions_list = fetch_questions(start, end, **section)
    # Using `**section` might throw an error for the unknown kwarg: `marker`.
    # But it is trivial to handle that.
    .
    ...

def replace_chunk(content: str, marker: str, chunk: str, inline: bool = False):
    """ Replace chunks of README.md """
    r = re.compile(
        rf"<!-- {marker} starts -->.*<!-- {marker} ends -->",
        re.DOTALL,
    )
    if not inline:
        chunk = "\n{}\n".format(chunk)
    chunk = f"<!-- {marker} starts -->{chunk}<!-- {marker} ends -->"
    return r.sub(chunk, content)

def get_item_string(item):
    # to prevent code from breaking if special characters are present
    title = re.sub(r'[^\w\s]', '', item["title"])
    return f"* [{title}]({item['link']}) - {item['score']} votes"

def build_table(*args):
    """ Build a markdown table from a list of entries. """
    columns = [
        "\n".join(
            map(get_item_string, chunk["items"][:8])
        )
        for chunk in args
    ]
    return columns


JPEG compression and DCT algorithm verification

I'll comment on readability as it could use some serious improvements.

Your indentation is very inconsistent.  Sometimes you indent two spaces, four spaces, eight spaces, or no spaces.  Choose a style and keep it consistent throughout the program.

Two common styles (using four spaces):

void func()
{
    if (isTrue)
    {
        // ...
    }
}

void func() {
    if (isTrue) {
        // ...
    }
}

Your use of whitespace is also inconsistent.  It'd be more readable to separate all operators and operands with one space and keep those consistent throughout the program.

Don't do this:

int number=1+2+3;

Do this:

int number = 1 + 2 + 3;

This comment:

//where n is the multi-decimal float

can just be placed above the function.  There's no need to put it in multiple places.
The comment next to applyDCT() should probably be placed on top of the function instead.  A comment that long should either be relocated or broken up into separate-lined comments.
These:

if (u == 0) *Cu = sqrt(1.0 / 8.0); else *Cu = sqrt(2.0 / 8.0);
if (v == 0) *Cv = sqrt(1.0 / 8.0); else *Cv = sqrt(2.0 / 8.0);

are not very readable nor maintainable.  Prefer to apply curly braces, especially if you'll need to add to any of the conditions:

if (u == 0)
{
    *Cu = sqrt(1.0 / 8.0);
}
else
{
    *Cu = sqrt(2.0 / 8.0);
}

// the same applies to the second aforementioned line

Do not declare/initialize variables on the same line:

double Cu=0,Cv=0,cos_x=0,cos_y=0, DCT_value = 0;

This is also not very readable nor maintainable, especially if you'll ever need to add comments or modify individual variables.

Instead, have them on their own line:

double Cu = 0;
double Cv = 0;
double cos_x = 0;
double cos_y = 0;
double DCT_value = 0;

Moreover, in C++, you should try to use variables as close in scope as possible (next to where they will first be used).  This will reduce the need for long lists of variables like above.


Repetition

Except the additional list these lines are identical:

shoes = map(int, input().strip().split())

query = list(map(int, input().split()))

You can write a function:

def read_integers_from_line(line):
    """
    >>> list(read_integers_from_line("12 3 7"))
    [12, 3, 7]
    """
    return map(int, line.strip().split())

That you can use twice.

Tuple unpacking

Instead of query = read_integers_from_line(input()) you can use: shoe, price = read_integers_from_line(input()) so that the code becomes more self-descriptive.

Skipping the first line

The first line contains useless information, you skip it weirdly using a range but I would suggest a more explicit skip by using instead _ = input()


I'd write:

def gesture(klass, item, text, desc)
  element_class = [klass.to_s, "gesture"]
  url = case klass
  when :sell
    new_reply_path(item_id: item.id)
  when :alternative
    new_reply_path(item_id: item.id, alternative: true)
  when :join
    new_item_affiliation_path(item)
  else
    fail("Unsupported klass: #{klass}")
  end

  content_tag(:li) do
    link_to(url, title: desc, data: {qtip: desc}, class: element_class) do
      content_tag(:div, nil, class: element_class) +
        content_tag(:span, text, class: 'gesture-text')
    end
  end
end


You can build it faster and use it faster if you use a flat hash instead of cascading hashes.

Here's a simple implementation using a "flat" hash:

class QuickerIndex

  def initialize(array)
    @index = {}
    array.each_with_index do |item, i|
      (@index[item.to_s] ||= []) << i
    end
  end

  def index(item)
    @index[item.to_s]
  end

end

and a benchmark to compare the two:

require 'benchmark'
floats = 10_000.times.map{rand}
Benchmark.benchmark('', 20) do |x|
  index = nil
  x.report('cascading create:') {index = QuickIndex.new(floats)}
  x.report('cascading access:') do
    floats.each do |float|
      index.index(float)
    end
  end
  x.report('flat create:') {index = QuickerIndex.new(floats)}
  x.report('flat access:')  do
    floats.each do |float|
      index.index(float)
    end
  end
end

CPU

No duplicate items

Without duplicate items, the CPU time needed to create and access various sizes of indices were:

                    ------CREATE--------     -----ACCESS------
NUMBER OF FLOATS    CASCADING       FLAT     CASCADING    FLAT
    10,000             0.27         0.05          0.20    0.03
   100,000             3.98         0.45          2.42    0.43
 1,000,000           140.75        14.13         69.72    4.84

With no duplicate items, flat hash scales a little better than cascading hash in create, but much better in access.  Flat hash is faster for create and access.

Duplicate items

Now, what about repeated items?  You indicate that there is some likelihood that two items will share the same key (that is, have the same #to_s).  Let's assume that each number is duplicated 10 times.  That is, in a list of 10,000 floats, there are really 1,000 unique floats; in a list of 100,000 floats, there are 10,000 unique floats:

                    ------CREATE--------     -----ACCESS------
NUMBER OF FLOATS    CASCADING       FLAT     CASCADING    FLAT
    10,000              0.23        0.02       0.20       0.02
   100,000              2.20        0.26       2.12       0.21
 1,000,000             27.70        3.56      26.29       2.62
10,000,000            364.14       25.16     341.66      23.44

Both flat and cascading hash perform better with duplicate items than without.  Flat hash still scales better, and is always faster.

Memory

Unless compiled with the right switch, Ruby lacks an effective way to tell how much memory is in use by its objects.  As a proxy, we can use "ps", which reports the total process size in kilobytes.  It's an imperfect proxy, but it's the best we have.

Here are the numbers for various numbers of floats.  The number of unique floats was always kept at 1/10th the total number of floats.  The memory size reported is the amount that memory usage went up after creating the instance of the index class:

NUMBER OF FLOATS    CASCADING        FLAT
    10,000             2,048k         52k
   100,000            32,952k      1,664k
 1,000,000           232,868k     28,596k
10,000,000         2,232,568K    229,512k


Express middleware to validate URL and tags

export async function validateSubmitScreencastReq (req, res, next) {
  try {
    const errors = [
        {field: 'url', message: await validateUrl(req.body.url)},
        {field: 'tags', message: validateTags(req.body.tags)}
    ].filter((obj) => obj.message !== undefined);

    if (errors.length !== 0) {
      res.status(400).json({errors})
    } else {
      next()
    }
  } catch (error) {
    next(error)
  }
}

This removes any non-errors from the originally constructed array and should give the same end-result as your code.

You can also improve your validate url/valide tag functions:

const assert = require("assert");//common nodejs package

async function validateUrl (url) {
  try {
    assert(url, "url can not be undefined");
    assert(youtubeUrl.valid(url), 'url must be a valid YouTube URL');

    const client = youtubeClient.create(config.youtubeApiKey)

    assert(await client.videoExists(url), 'url must link to an existent, public YouTube video');
    assert(!(await db.models.screencast.findOne({where: {url: url}})), 'url has already been submitted');
  } catch (error) {
    /* remove the if, if you want to also return whatever those functions may
       have thrown as an error */
    if (error instanceof AssertionError) {
      return error.message;
    }
  }
  //No return needed if you want to return undefined
};


Chaining method calls and "bubbling" the results

How about making inMem & co "bracket" functions? Like follows:

import Control.Monad.Writer

type M a = Writer String a
type LoadFunc a b = (a -> M b) -> a -> M b

type Query = String
type Result = ()

inMem :: LoadFunc Query Result
inMem _ "hi" = tell "Found in mem. "
inMem f q    = f q >> tell "Added to mem. "

renDisk :: LoadFunc Query Result
renDisk _ "foo" = tell "Found rendered. "
renDisk f q     = f q >> tell "Added rendered. "

onDisk :: LoadFunc Query Result
onDisk _ "bar" = tell "Found on disk. "
onDisk f q     = f q >> tell "Now on disk. "

tester :: [LoadFunc Query Result] -> Query -> M Result
tester = foldr ($) notFound
  where notFound q = tell "Not found!"

Run using runWriter $ tester [inMem,renDisk,onDisk] "bar"

This should give you the control flow you seek - as well as enough room for extension by replacing the monad as required. You could for example have notFound throw an exception using an Error monad instead (which would probably make sense).


improving speed of this numpy-based diffraction calculator

I managed to make your script a bit faster. See the comments in the
source code:

import numpy as np
import matplotlib.pyplot as plt
import time

# Makes it so numpy always outputs the same random numbers which is
# useful during development. Comment out the line in production.
np.random.seed(1234)

def main():
    twopi, img = 2*np.pi, np.complex(0, 1)

    wavelength = 0.08
    k0  = twopi/wavelength

    z_noise = 0.05 * wavelength

    N, M = 100, 50
    x = np.arange(-N, N+1)

    # Use random Z noise for now
    Z = z_noise * np.random.normal(size = (x.shape[0], x.shape[0]))

    A = np.linspace(0, 0.2, M)

    tstart = time.time()
    answers = []

    # X and Y with shapes (x, 1) and (1, x) contains the same data.
    X = x[np.newaxis,:]
    Y = x[:,np.newaxis]

    # Compute squared Euclidean distances with shape (x, x).
    Rsq = X**2 + Y**2

    # Compute other distances with shape (M, M).
    a = A[:,np.newaxis]
    b = A[np.newaxis,:]
    SQ = 1 + np.sqrt(1 - a**2 - b**2)

    # Add noise thing (M, M, x, x).
    SQ_Z = SQ[:,:,np.newaxis,np.newaxis] * Z

    # Gets shape (M, 1, x) and (M, x, 1).
    A_X = A[:,np.newaxis,np.newaxis] * X
    A_Y = A[:,np.newaxis,np.newaxis] * Y

    # Calculates A*X + A*Y with shape (M, M, x, x).
    A_X_Y = A_X[:,np.newaxis] + A_Y[np.newaxis,:]

    # e^{-j*phases} with shape (M, M, x, x).
    A_stuff = np.exp(-img * k0 * (A_X_Y + SQ_Z))
    for w_beam in (1, 2, 4, 8):
        coeff = np.exp(-Rsq/w_beam**2)
        # Sums over the last two dimensions, shape becomes (M, M).
        E = np.sum(A_stuff * coeff, axis = (2, 3)) / w_beam**2
        answers.append(E)

    print(f'Time: {time.time() - tstart:.3}')
    # Print checksum. Useful for debugging.
    print(sum(np.sum(E) for e in answers))
    if True:
        plt.figure()
        for i, E in enumerate(answers):
            plt.subplot(2, 2, i+1)
            plt.imshow(np.log10(np.abs(E)), vmin=0.0001)
            plt.colorbar()
        plt.show()

main()

I have wrapped all your code in a main function. It is good practice
to do so, even for small scripts, but it makes it easy to see if
there's any dependencies on global variables.

The script runs about four times faster. Most of the speedup comes
from replacing your explicit loop with vector functions. So instead of

for i, a in enumerate(A):
    EE = []
    for b in A:
        e = E_ab(a, b, positions, w_beam, k0)
        EE.append(e)
    E.append(EE)

those lines now read

coeff = np.exp(-Rsq/w_beam**2)
E = np.sum(A_stuff * coeff, axis = (2, 3)) / w_beam**2
answers.append(E)

To get the data in a format that vector functions can handle I've
added a lot of
broadcasting. It
can be used to compute, for example, the cartesian
product
of arbitrary numpy arrays.

I think someone who understands the math (which I don't) could
optimize your script even more. Some of the calculations seem
redundant to me, but I have no idea how to factor them out.


Finding the greatest number from three numbers

I see a number of things that could help you improve your program.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Fix the formatting

I don't know if the indentation problems are a cut-and-paste error or really how your code looks, but it should be fixed.

Avoid using C++ keywords as variable names

The keyword final is being used here as a variable name.  While that's technically not an error, it's not good practice.  I'd suggest using some other name for that.

Simplify your code

The maxNumber function is more complex than it needs to be.  Here's an alternative that minimizes the number of comparisons made:

int maxNumber(int num1, int num2, int num3) {
    if (num1 > num2) {
        return num1 > num3 ? num1 : num3;
    }
    return num2 > num3 ? num2 : num3;
}

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


host = input(str("Please enter the hostname of the server : "))
...
message = input(str("Please enter your message: "))

can be changed to simply:

message = input("Please enter your message: ")
...
host = input("Please enter the hostname of the server : ")

since there is no need to cast a string to a string.

while 1:

is fine, but is more readable as:

while True:

Having print statements like the following:

print("")

is redundant. If you want an extra newline after a print statement; Add "\n" to the end of the preceding print statements to remove a function call, and reduce code clutter. E.G:

print("Sent\n")

This is more of a personal preference, but fstring formatting is more readable  than the following:

print(s_name, ":" ,message)

should be:

print( f"{s_name}: {message}" )


Print the sum of corresponding elements in two arrays

You don't need to store the intermediate result.
You don't need to give the length of the arrays.
This assumes that the arrays are allways of equal length.

for(int i = 0; i < firstArray.length; i++){
    System.out.print((firstArray[i] + secondArray[i]) + " ");
}


Function returning higher order function

That's a pretty good solution to a tricky exercise.  I recommend two simplifications:

The definition of tple can be lifted out of f into cycle itself, as it never changes.
The code would be simpler if you count up instead of down.

def cycle(f1, f2, f3):
    tple = (f1, f2, f3)
    def f(n):
        def g(x, count = 0):
            if count == n:
                return x
            else:
                return g(tple[count % 3](x), count + 1)
        return g
    return f

As you observed, your g function is a leaky abstraction: it is supposed to take just an x argument, but it's possible to interfere with its proper behaviour by also passing it a count.  Here is one solution that avoids that problem ("apply f1, then move f1 to the end of the queue").

def cycle(f1, f2, f3):
    def f(n):
        def g(x):
            if n == 0:
                return x
            else:
                return cycle(f2, f3, f1)(n - 1)(f1(x))
        return g
    return f


The first thing that strikes me as odd about your code is having the four single-character variables to represent color components.  I would rather see a single drawColor variable with the UIColor type.  Not only does this eliminate the need for the setColor method, but it also more easily lets us pull that color out for numerous reasons (make some other thing the same color as our DrawView's current drawColor, or see if the DrawView's drawColor is the same shade as something else, etc.  There are plenty of reasons. Then only internal to the specific necessary methods do we break that color down into its components for the necessary Core Graphics function call.

Our code has no sense of organization.  We should put our event-handling methods together, rather than separate them by the big drawLine method.

Our drawLine method isn't very nicely named.  First of all, we can inspect the method to know that it expects points, and the "from" outside of the parenthesis looks and feels very odd.  I'd prefer the method be declared something more like this:

drawLine(from fromPoint: CGPoint, to toPoint: CGPoint)

Which means when it's called by an end user, the call looks like this:

drawView.drawLine(from: pointA, to: pointB)

But internally, we refer to the points as the fromPoint and the toPoint.

mainImageView.frame = self.frame
tempImageView.frame = self.frame

This bit isn't really going to work.  If these two views are subviews of the DrawView and we intend for them to be in the same spot, we need to better.

For a start, their frame property should be set to self's bounds property.  For any UIView, the frame describes its position in its superview, so the X and Y will be how far it is from the top left corner.  Meanwhile, its bounds property will always have an X and Y of zero.  So if I set my subview's frame to be equal to its parent's bounds property, it will be the same size, but it will be positioned to the parent's top left corner--and I think this is what we're actually trying to achieve right?

But even this isn't enough.  What happens when self is resized by something?  Now our manually sized subviews are no longer the correct size.  We need to programmatically add autolayout constraints so that the four edges of these subviews are pinned to its parent view, so they will always be the same size.

Ultimately, there's no real reason to use our image view subviews.  Using Core Graphics, we can add lines like this directly to any view.  This Code Review question shows an example of drawing lines directly on a view.  The only reason we need an image view is if we want to display a UIImage.  And there's no need to do so here.

Even if we want to be able to generate a UIImage from what the user has drawn on our DrawView, there are means for doing that in iOS (that question is Objective-C, but it can be done in Swift too).  So there really is no reason to be using the image views here at all.


I see some things that I think could help you improve your code.

Decompose your program into functions

All of the logic here is in main in one rather long and dense chunk of code.  It would be better to decompose this into separate functions.

Check return values for errors

The call to scanf can fail.  You must check the return values to make sure they haven't or your program may crash (or worse) when given malformed input or due to low system resources.  Rigorous error handling is the difference between mostly working versus bug-free software.  You should strive for the latter.

Use more whitespace to enhance readability of the code

Instead of crowding things together like this:

for (i=0;i<n;i++)

most people find it more easily readable if you use more space:

for (i=0; i < n; i++)

Eliminate "magic numbers"

Instead of hard-coding the constants 26 and 4 in the code, it would be better to use a #define or const and name them.

Avoid scanf if you can

There are so many well known problems with scanf that you're usually better off avoiding it.

Don't recursively call main

The main() function can be called recursively in C, but it's a bad idea.  You could blow up your stack and there's really no good reason to do that here.  Just use a loop. See https://stackoverflow.com/questions/4238179/calling-main-in-main-in-c for details.

Use a better random number generator

You are currently using

password[i] = numbers[rand() % 10];

There are a number of problems with this approach. This will generate lower numbers more often than higher ones -- it's not a uniform distribution.  Another problem is that the low order bits of the random number generator are not particularly random, so neither is the result.  On my machine, there's a slight but measurable bias toward 0 with that.  See this answer for details, but I'd recommend changing that to the rand_lim in that link and also duplicated below.

Results

Here's an alternative that uses all of these ideas.  It also gets a length from the command line so there's no need for a prompt or scanf.  It eliminates the need for counting characters and uses the better random number generator mentioned above:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int rand_lim(int limit) {
/* return a random number between 0 and limit inclusive.
 */

    int divisor = RAND_MAX/(limit+1);
    int retval;

    do {
        retval = rand() / divisor;
    } while (retval > limit);

    return retval;
}

char picker(const char *charset) {
    return charset[rand_lim(strlen(charset)-1)];
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        puts("Usage: pwgen len");
        return 1;
    }
    int len = atoi(argv[1]);
    if (len <= 0) {
       puts("Length must be a positive non-zero integer");
       return 2;
    }
    const char* groups[] = {
        "1234567890",  // numbers
        "abcdefghijklmnoqprstuvwyzx",  // lowercase
        "ABCDEFGHIJKLMNOQPRSTUYWVZX",  // uppercase
        "!@#$%^&*(){}[]:<>?,./",    // symbols
    };
    const size_t numGroups = sizeof(groups)/sizeof(groups[0]);
    srand((unsigned int)(time(NULL)));

    // only proceed if we got a number
    for ( ; len; --len) {
        unsigned group = rand_lim(numGroups-1);
        putchar(picker(groups[group]));
    }
    putchar('\n');
}


Probably the best improvement would be to allocate extra storage space and also store how many elements your list contains. Right now you allocate a new array and copy all existing values on each add operation, and this results in O(n) time complexity for adding items. Instead you could increase inner array twice each time, this would result in amortized O(1). Also, with this approach you wouldn't need to allocate new arrays on removal operations, as you could just leave empty space at the end.


Implementation of Set data type in Haskell

module Set where

Self-contained reusable chunks of code should be organized into modules.

data Set a = Empty | Set a (Set a)
  deriving (Read, Show)

All-caps types are not a thing, just Set is fine. Single letter constructors are uncommon too, so instead of E use a meaningful name like Empty. Constructors can take multiple arguments, so don't use tuples where you don't have to. I'll also point out that this data type you've defined is isomorphic to [a]. Besides the magic square brackets, Haskell lists are a data type like any other, i.e. data [a] = [] |  (:) a [a]. Notice the similarity? Is this a situation where you need a new datatype or might it make sense to use a newtype?

-- Test data
setx, setx2, sety, setys :: Set Int
setx = listToSet [1,2,3,4]

All top-level bindings should be given a type signature, get into the habit now and you'll save yourself the frustration of a lot of cryptic misplaced error messages later. These names are all over the place too, they should be more consistent, e.g. exampleSetA, exampleSetB, exampleSetC. Don't crowd together functions and their arguments, leave some space and let it breathe.

fromList :: [a] -> Set a
fromList []     = Empty
fromList (x:xs) = Set x (fromList xs)

fromList is a common name for converting lists to arbitrary datatypes. When it conflicts with other names from modules you have imported, you disambiguate with qualified imports, not a menagerie of globally unique names. (x:xs) is a common naming pattern for lists, that is, some variable x, y, e, or whatever, and then the plural form (xs, ys, es... it's a pun, get it?). Again, space out function application, tuples are a datatype in Haskell, not a method of passing arguments.

member :: (Eq a) => a -> Set a -> Bool
member _ Empty                  = False
member a (Set x xs) | a == x    = True
                    | otherwise = member a xs

A common function name for testing set membership is member. When you don't use an argument name in the body of a function, replace it with _. If you compile with -Wall (as you should), GHC will warn you about unused bindings. That is, names that you defined in a function body but didn't use. Often this can help you to notice errors before you ever get to running your code! Use guards (e.g., | a == x) instead of if statements where you can. Guards are like a multiway if, when you have multiple cases it becomes much clearer than chaining ifs, get into the habit now, there's no reason not to.

null :: Set a -> Bool
null Empty = True
null _     = False

Use pattern matching where you can, it's more explicit than equality testing, often faster, and helps you avoid unnecessary constraints. Notice how my version lacks the (Eq a) constraint?

-- Mourn headSet and tailSet here

These functions are meaningless on Sets. Being unordered collections, Sets do not have meaningful heads or tails, so you should not leak implementation details by exposing them.

insert :: (Eq a) => a -> Set a -> Set a
filter :: (a -> Bool) -> Set a -> Set a
intersection :: (Eq a) => Set a -> Set a -> Set a
union :: (Eq a) => Set a -> Set a -> Set a
isSubset :: (Eq a) => Set a -> Set a -> Bool

Around now you're starting to feel the pain of your choice of Set representation. Implementations are slow and unwieldy. For instance, your version of intersection is an \$O(n^2)\$ operation. You can improve running times by utilizing any of a number of standard algorithms, try using balanced binary trees to represent your sets instead of linked lists.

instance (Eq a) => Eq (Set a) where

Instead of making up another name, write your own instances for standard functions like equality. If the derived instance doesn't do what you want, don't use it, don't keep it around (because you'll be unable to keep it from being exported to users of your library), and don't let it clutter up good namespace.


Naming

According to the Swift API Design Guidelines,

  Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase

therefore it should be func oneDeletion, oldPerms, newPerms etc.

Some variable names such as A, L are non-descriptive.

I would use a different name for the array inside struct Permutation,
for example

struct Permutation: Hashable {
    let sigma: [Int]
    // ...
}

so that perm can be used for a Permutation variable without
causing confusion. (This is of course opinion-based.)

Hashing

You don't need to implement

static func == (lhs: Permutation, rhs: Permutation) -> Bool

because that is automatically synthesized in Swift 4.1. A future version
of Swift will also synthesize the hashValue automatically, this
is currently discussed at

Let Optional, Dictionary and Array conditionally conform to Hashable in the Swift forum.

and implemented in https://github.com/apple/swift/pull/15382.

Until that is implemented, you have to provide a hashValue method.
I would probably not choose the description method because that
requires a conversion to strings. A good choice would be the
_combineHashValues function in Hashing.swift from the above pull
request, this is also what hash.hpp from the Boost library uses:

// From https://github.com/lorentey/swift/blob/e03cb1340ad89013bbaef1c4f802a72de06e9e1a/stdlib/public/core/Hashing.swift
func combineHashValues(_ firstValue: Int, _ secondValue: Int) -> Int {
    let magic = 0x9e3779b9 as UInt
    var x = UInt(bitPattern: firstValue)
    x ^= UInt(bitPattern: secondValue) &+ magic &+ (x &<< 6) &+ (x &>> 2)
    return Int(bitPattern: x)
}

struct Permutation: Hashable {
    let sigma: [Int]

    var hashValue: Int {
        return sigma.reduce(0, combineHashValues)
    }

    // ...
}

Use functional methods

The loop

var A = [Int]() // Empty array of integers
for val in sigma.perm {
    if val < i {
        A.append(val)
    } else if val > i {
        A.append(val-1)
    }
}

in func one_deletion can be simplified using compactMap:

let a = sigma.perm.compactMap { val in
    val < i ? val : val > i ? val - 1 : nil
}

and in func downset the inner loop

        for val in sigma.perm {
            new_perms.insert(one_deletion(sigma:sigma, i:val))
        }

can be simplified using map:

        new_perms.formUnion(sigma.perm.map { one_deletion(sigma: sigma, i: $0) } )

Define instance methods

Both func one_deletion and func downset operate on an instance of
struct Permutation, therefore I would replace the free functions by
instance methods:

struct Permutation: Hashable {
    // ...

    func deleting(i: Int) -> Permutation { /* ... */ }
    func downset() -> [Set<Permutation>] { /* ... */ }
}

which would then be used as

let reduced = perm.deleting(val: i)

or

let ds = perm.downset()

Further remarks

Array<Int> and [Int] are equivalent notations for an array of integers, but I would
suggest to use only one of them consistently.

The comment in

var A = [Int]() // Empty array of integers

is useless, and here

let B = Permutation(perm:A)
return B

the intermediate variable is not needed.

Instead of re-initializing the set with an empty set

    new_perms = []

it might be more efficient to call

    new_perms.removeAll(keepingCapacity: true)

to avoid subsequence reallocations of the element storage.

Putting it all together

// From https://github.com/lorentey/swift/blob/e03cb1340ad89013bbaef1c4f802a72de06e9e1a/stdlib/public/core/Hashing.swift
func combineHashValues(_ firstValue: Int, _ secondValue: Int) -> Int {
    let magic = 0x9e3779b9 as UInt
    var x = UInt(bitPattern: firstValue)
    x ^= UInt(bitPattern: secondValue) &+ magic &+ (x &<< 6) &+ (x &>> 2)
    return Int(bitPattern: x)
}

struct Permutation: Hashable {
    let sigma: [Int]

    var hashValue: Int {
        return sigma.reduce(0, combineHashValues)
    }

    func deleting(val: Int) -> Permutation {
        let newSigma = sigma.compactMap { j in
            j < val ? j : j > val ? j - 1 : nil
        }
        return Permutation(sigma: newSigma)
    }

    func downset() -> [Set<Permutation>] {
        var newPerms = Set([self])
        var result = [newPerms]

        for _ in 0..<sigma.count {
            let oldPerms = newPerms
            newPerms.removeAll(keepingCapacity: true)
            for perm in oldPerms {
                newPerms.formUnion(perm.sigma.map { perm.deleting(val: $0)} )
            }
            result.append(newPerms)
        }

        return result
    }
}

let u3 = Permutation(sigma: [2,5,3,1,4])
let ds = u3.downset()


List contents of a folder using a shell script and mail the folder

As @Juaniyyoo already mentioned, ls is the usual way to list all the files in a directory. I'm not sure if you really want to send a separate email for each file. If you do, you can iterate over each file with a while loop.

ls | while read file; do mail ... <<< "$file"; done

If what you really intended was to send the whole list in one go, this is even simpler.

ls | mail ...

ls has a lot of options for controlling the output format. With no options, it will just write the name of each file.  ls -l lists permissions, number of links, owner user, owner group, size, modification date and name. The date modified might be interesting, i.e. when it was received, but the other one are probably not.

ls -l | sed -E 's/([^ ]+ +){5}//' | mail ...

Use this command to filter out the first 5 columns, and thus only get the date and filename columns. You might also want to sort the output - for this use the option --sort=time.

The first output line from ls -l is a header saying something like total 8440. You can skip this first line with tail -n+2.

ls -l | tail -n+2 | sed -E 's/([^ ]+ +){5}//' | mail ...

If you want the date and time in another format, use the --time-style option for ls.

Using ls instead of your rolling with your own loop provides a lot of utility, and prevents you from "reinventing the wheel".


Yes, the running time is \$O(n^2)\$.

When writing ruby, it's best to take advantage of ruby's built in methods, rather than writing procedural code the same way you would in C or Java.

Also, this problem expresses itself more naturally with recursion.

Notes on the solution below:

nums, in this recursion, are "the remaining numbers to be processed".  We start with smallest (first number on sorted list), pop off the head on each iteration.
ret is a hash of the results for all smaller numbers -- the same is max_result in the OP.

Here's a possible rewrite:

def largest_divisible_subset(nums, ret={})
  return ret.values.max_by(&:size) || [] if nums.empty?
  nums = nums.sort if ret.empty?
  head, *tail = nums
  max_set = ret.select {|n| head % n == 0}.values.max_by(&:size) || []
  ret[head] = max_set.dup.push(head)
  largest_divisible_subset(tail, ret)
end


Improve Trie manipulation in Haskell code

Can you add minimal imports so your code compiles? I had to guess:

import Data.ListTrie.Map as M hiding (null)
import qualified Data.Map as Map
import Data.Maybe
import Data.List

data Event = Event deriving (Show, Eq, Ord)
data Result = Result deriving (Show, Eq)

constructTrie can be easily improved by inlining comp:

constructTrie list = M.fromListWith (++) list

Or even to constructTrie = M.fromListWith (++) but that requires turning off monomorphism restriction or adding an explicit signature for constructTrie, so it's up to your taste.

Also you can deduplicate showTrie calls and long trie signatures:

mshow list = M.showTrie list ""

type ResultTrie = M.TrieMap Map.Map Event [Result]

duplicates :: ResultTrie -> String
duplicates m = mshow list
  where
    list = M.filter (\v -> length v /= 1) m

prefixOverlap :: ResultTrie -> String
prefixOverlap m = mshow list
  where
    list = M.filterWithKey (\k v -> not $ null $ catMaybes [M.lookup x m | x <- reverse (inits (init k))]) m

Now it's beneficial to inline list variables in both functions:

duplicates :: ResultTrie -> String
duplicates m = mshow $ M.filter (\v -> length v /= 1) m

prefixOverlap :: ResultTrie -> String
prefixOverlap m = mshow $ M.filterWithKey (\k v -> not $ null $ catMaybes [M.lookup x m | x <- reverse (inits (init k))]) m

Now you can get rid of m in duplicates:

duplicates :: ResultTrie -> String
duplicates = mshow . M.filter (\v -> length v /= 1)

In prefixOverlap the line is too long, I can split it. I chose to extract the (\ -> ) construct. Note that m is in more that 1 place so we cannot use ..

prefixOverlap :: ResultTrie -> String
prefixOverlap m = mshow $ M.filterWithKey f m where
    f k _ = not $ null $ catMaybes [M.lookup x m | x <- reverse (inits (init k))]

Now remove extra parentheses in the comprehension:

prefixOverlap :: ResultTrie -> String
prefixOverlap m = mshow $ M.filterWithKey f m where
    f k _ = not $ null $ catMaybes [M.lookup x m | x <- reverse $ inits $ init k]

From here I'll only work on f.

Now a trickier part. Long chains of $ are equivalent to . following one $ in the end:

    f k _ = (not . null . catMaybes) [M.lookup x m | x <- reverse $ inits $ init k]

not . null . catMaybes is a function of [Maybe a] -> Bool that returns True only if there is any Just in the list. I can literally translate this sentence into Haskell: it's just any isJust:

    f k _ = any isJust [M.lookup x m | x <- reverse $ inits $ init k]

Now even trickier: your comprehension is just a map:

    f k _ = any isJust $ map (\x -> M.lookup x m) $ reverse $ inits $ init k

Congratulations, we can again turn a chain of $ into a chain of .:

    f k _ = any isJust . map (\x -> M.lookup x m) . reverse . inits . init $ k

Now remember that . is associative so you can put parentheses in the middle of the chain wherever you want:

any isJust . (map (\x -> M.lookup x m) . reverse) . inits . init

Now we have map something . reverse. And it doesn't matter when you reverse - before or after map:

map something f . reverse = reverse . map something

That is, map and reverse commute and we can swap them and remove parens:

any isJust . reverse . map (\x -> M.lookup x m) . inits . init

Now we can put around any and reverse. It's clear that any works the same way for straight and reversed lists, that is, any something . reverse = any something, so we can throw reverse away:

any isJust . map (\x -> M.lookup x m) . inits . init

And put back into prefixOverlap:

prefixOverlap :: ResultTrie -> String
prefixOverlap m = mshow $ M.filterWithKey f m where
    f k _ = any isJust . map (\x -> M.lookup x m) . inits . init $ k

Here is the full version of the code:

import Data.ListTrie.Map as M hiding (null, map)
import qualified Data.Map as Map
import Data.Maybe
import Data.List

type Event = Char
type Result = ()
type ResultTrie = M.TrieMap Map.Map Event [Result]

data XComposeString = XComposeString { keyEvents :: [Event], s :: Result }
  deriving (Eq, Show)

data XComposeFile = XComposeFile { strings :: [XComposeString] }
  deriving (Eq, Show)

constructTrie list = M.fromListWith (++) list

mshow :: ResultTrie -> String
mshow list = M.showTrie list ""

duplicates :: ResultTrie -> String
duplicates = mshow . M.filter (\v -> length v /= 1)

prefixOverlap :: ResultTrie -> String
prefixOverlap m = mshow $ M.filterWithKey f m where
    f k _ = any isJust . map (\x -> M.lookup x m) . inits . init $ k

Note that I used fake Event and Result types. I also checked that old and new prefixOverlap are the same using QuickCheck and smallcheck libraries:

prefixOverlapOld :: ResultTrie -> String
prefixOverlapOld m = M.showTrie list ""
  where
    list = M.filterWithKey (\k v -> not $ null $ catMaybes [M.lookup x m | x <- reverse (inits (init k))]) m

prop_foo x = prefixOverlap m == prefixOverlapOld m where
    m = M.fromList $ map (first (++ "X")) x

first is from Control.Arrow.

The prefixOverlap probably can still be improved with using lookupPrefix and/or children functions from Data.ListTrie.Map.

Here is my take:

prefixOverlapNew :: ResultTrie -> String
prefixOverlapNew = mshow . M.unions . map (\(p,m) -> M.addPrefix [p] m) . Prelude.filter (\(p, m) -> M.size m /= 1 || (null $ fst $ head $ M.toList m)) . Map.toList . M.children1

Note that it differs from both original prefixOverlapOld and refactored prefixOverlap:

QuickCheck found that they differ on a map with 2 keys "fo" and "f". The prefixOverlapNew  version correctly shows both "fo" and "f" as they overlap. The original version(s) show only value on "fo" key which is dubuios.

Here is an improved version using list comprehension to combine filter and map:

prefixOverlapNew :: ResultTrie -> String
prefixOvelapNew mm = mshow $
    M.unions [M.addPrefix [p] m | (p, m) <- Map.toList $ M.children1 mm,  M.size m /= 1 || null (fst $ head $ M.toList m)]

Moved f out:

prefixOverlapNew mm = mshow $ M.unions [M.addPrefix [p] m | (p, m) <- Map.toList $ M.children1 mm, f m] where
        f m =  M.size m /= 1 || null (fst $ head $ M.toList m)

Finally, a version in list monad, just for fun:

prefixOverlapNew :: ResultTrie -> String
prefixOverlapNew mm = mshow $ M.unions $ do
        (p, m) <- Map.toList $ M.children1 mm
        guard $ M.size m /= 1 || null (fst $ head $ M.toList m)
        return $ M.addPrefix [p] m

guard is from Control.Monad.


Agree 100% with Corbin. GET isn't something that is inherently secure, and trying to make it so is nigh impossible. That's what POST is for. Only use GET for non-sensitive information. That being said, there are some generally concerning bits to your code that could cause some people to downvote it.

Your line length is rather long and convoluted, which causes major issues with legibility. I would suggest breaking up that single line into multiple lines to more easily maintain and read. Adding whitespace couldn't hurt either. Additionally, using single letter variables is not very descriptive and also leads to issues with legibility. Its a bit longer, but much easier to read.

$translation = strtr( $stringArray, '-_,', '+/=' );

$key     = md5( $key );
$data    = base64_decode( $translation );
$iv      = md5( $key );
$decrypt = mcrypt_decrypt(
    MCRYPT_RIJNDAEL_256,
    $key,
    $data,
    MCRYPT_MODE_CBC,
    $iv
);

$trimmed = rtrim( $decrypt, "\0" );

return unserialize( $trimmed );

A couple more potential issues with the above code are the methods you are implementing. I am by no means a security guru and have not put a lot of research into the matter, but I seem to remember from somewhere that mcrypt is frowned upon and that hashing a string with md5() twice is actually less secure than doing it just once. I don't know if this is true or not, but that could be a potential issue.

Your code is also slightly repetitive, violating the "Don't Repeat Yourself" (DRY) Principle. As the name implies, your code should not repeat. Your encrypt and decrypt functions seem to share some common elements, using some shared helper functions to provide that similar data might be beneficial, even though you might just end up creating wrapper functions. I don't really see anyone downvoting you for this alone, this is rather minor in this instance and is rather hard to spot due to the above reasons.

Another potential issue I see is with your braceless syntax. Braceless {} syntax can be somewhat confusing to those who have never seen it before, and therefore could cause issues with maintainability. This is entirely a point of preference, but one I would argue most vehemently against. It is especially bad to offer in the form of an answer when it is unknown how the questioner will use it. It is quite possible they attempted to modify the code and could not get it to work.

The last issue I see is the way you are accessing array elements with magic numbers. This is rather sloppy and could cause issues with legibility, though I don't think you would get downvoted for it. There are a number of different ways this could be solved. The first is by using the PHP construct list(), which is probably preferable in this instance. The second is by using array functions to slice off the required portions of the array. This is more beneficial when you need the first and last elements of an array of undetermined length. Finally, there is also the possibility of using extract(), but that requires an associative array and is sometimes frowned upon. I won't show that last method because it doesn't apply here, but here are the other two:

//using list
list( $baseurl, $params ) = $url;

//using array functions
$baseurl = array_shift( $url );
$params  = array_shift( $url );//could potentially use array_pop()

return $baseurl . '?params=' . encryptStringArray( $params, $key );

Hope this helps!


Questions

self is the instance of whatever class the method is defined on.
In your example the method is generate_new_salt which is defined on the Hashing class.

When you use my_hashing = Hashing() you're creating an instance and binding it to the variable my_hashing. When you then call the method, via something like my_hashing.generate_new_salt(...) then self is the same as my_hashing. They both point to the same instance of Hashing.

>>> class Foo:
        def comp(self):
            return my_foo == self

>>> my_foo = Foo()
>>> my_foo.comp()
True

This means that self.foo = ... binds ... to the instance. This allows you to then use self.foo to get the value, ..., back at a later date. Without having to pass it as an argument. If you have no reason to use self.foo rather than just foo, then using self.foo is not a good idea.
This comes from two different but linked things.

You're trying to be too helpful. A lot of your code is not doing much, and is just calling other functions.

This is a common problem when programming, and so I would recommend you follow the KISS principle. If you don't need the helper now, then you don't need it at all.
You're not really using objects to their potential. If you wrap all of your methods in staticmethod decorators then nothing will change. This highlights that you're not really following OOP. And it highlights you're barely using the features class provides.

Given the above points, it would be best to start over.

Review

It's normally recommended to not use print. There are exceptions, but in most cases you're better served either by just not having print or using logging.

There is one exception, which is to interact with the user via the CLI. And in this case Hashing does not need to do that. Where you're testing needs it and so you should only have them below that comment "code below is just for testing".
Inheriting from object, Hashing(object), is redundant in Python 3.
Rather than using an if to compare something and then return True and False. You can just return the comparison.

return re_hash.decode() == old_hash.decode()

It would be best if the code below the comment "code below is just for testing" were in a function. This would mean that the global namespace isn't polluted with things that don't need to be there.
It's best to use an if __name__ == '__main__': guard. Since you only run the main function if you're testing, this will allow you to import the code without the testing code running.

From the ground up

Merging both the hash and the salt into the encoding, "base64(hash + salt)", is a smart way to keep the hash and the salt together. However it would be clearer if you create a class that stores the hash and the salt independently.

class PasswordHash:
    def __init__(self, hash, salt):
        self.hash = hash
        self.salt = salt

ph = PasswordHash(b'hash', b'salt')
print(ph.hash)  # b'hash'
print(ph.salt)  # b'salt'

From here you should be able to see two things:

The method get_old_salt is now obsolete.
You no longer need to care about the salt length.

When you first define a class, after writing the __init__, you should ask yourself if the class will ever be printed. If it could be printed, then you should make at least one of these dunder methods, double underscore method.

__repr__ - Instructions on how to rebuild the method.
__str__ - A human friendly interpretation of the class.

In this case __repr__ could make sense, but __str__ doesn't.

def __repr__(self):
    return f'PasswordHash({self.hash}, {self.salt})'

You should be able to see, __repr__ outputs the exact text we used to make the instance.

>>> print(PasswordHash(b'hash', b'salt'))
PasswordHash(b'hash', b'salt')

From here we need to think about how we should hash the password, since we don't want to store the password in plaintext. And so we can add compute_hash to PasswordHash, with 2 modifications.

I prefer the name hash_password, as it explains what it does, and what it does it on.
Secondly I would make it a staticmethod. This comes with a couple of reasons why:

It allows us to create PasswordHash from a password easier.
It allows for subclasses of PasswordHash to change the way the class hashes things.

@staticmethod
def hash_password(password, salt):
    hash = hashlib.sha256(password.encode() + salt)
    return base64.b64encode(hash.digest())

Currently making a PasswordHash from a password is pretty ugly.

ph = PasswordHash(PasswordHash.hash_password(password, salt), salt)

Since the current interface for making a PasswordHash from a password is not the nicest. And is the standard way to use the class, we can make a class method to make it pretty.

The reason this is a classmethod and not a standard method is because we need it to run before __init__. It is also a classmethod and not a staticmethod as we'll be using the first argument, cls, to instantiate the class.

@classmethod
def from_password(cls, password, salt):
    return cls(cls.hash_password(password, salt), salt)

Now making the PasswordHash from a password is really clean.

ph = PasswordHash.from_password('pass', salt)

We're almost at the end. The last thing to do is to add the spiritual child of compare_hashes to the class. Which is really simple since we have self.salt and PasswordHash.hash_password.

def compare(self, password):
    return self.hash == self.hash_password(password, self.salt)

Tying this all together you can get:

import base64
import hashlib
import os

def new_salt(length=16):
    return os.urandom(length)

class PasswordHash:
    def __init__(self, hash, salt):
        self.hash = hash
        self.salt = salt

    @classmethod
    def from_password(cls, password, salt):
        return cls(cls.hash_password(password, salt), salt)

    def __repr__(self):
        return f'PasswordHash({self.hash}, {self.salt})'

    @staticmethod
    def hash_password(password, salt):
        hash = hashlib.sha256(password.encode() + salt)
        return base64.b64encode(hash.digest())

    def compare(self, password):
        return self.hash == self.hash_password(password, self.salt)

def main():
    salt = new_salt()
    print('salt:', salt)
    hash = PasswordHash.from_password('pass', salt)
    print('PasswordHash:', hash)
    print('hash:', hash.hash)
    print('salt:', hash.salt)
    print('compare pass:', hash.compare('pass'))
    print('compare bar :', hash.compare('bar'))

if __name__ == '__main__':
    main()

To make the comparison to be more OOP you could rename compare to the dunder method __eq__. And then you could use it via the == operator.

print('compare pass:', hash == 'pass')
print('compare bar :', hash == 'bar')


function markTodoItemComplete(id) {
    const todoListClone = todoList.slice();
    todoListClone[id - 1].complete = true;
    setTodoList(todoListClone);
  }

This seems me not good practice, what you could have done is just getting id(key) of array and just set it to true.
like

 function markTodoItemComplete(id) {
    todoListClone[id].complete = true;
  }


Find associated object if exists, otherwise generate it

You can use find_or_initialize_by dynamic finder, see a guide here

This would be equivalent to your code:

def pick_for_game(game)
  game_id = game.instance_of?(Game) ? game.id : game
  picks.find_or_initialize_by_game_id(game_id)
end

Hope it helps you!.


Looking for matching names among two text files

The first thing that really jumped out at me is your loadFile method is using synchronous http requests (looks accidental as you're using a callback anyway, see msdn for why this should be avoided etc).

Instead of client.open('GET', filename); you probably want client.open('GET', filename, true);

Making async requests will allow the first notable improvement I would make is to make init loading async. I'm going to use the native promises -- feel free to adapt

// setup
function init() {
  var base = "data/sample2/",
    namesFile = base + "names.txt",
    dataFile = base + "data.txt";

  Promise.all([loadFile(namesFile), loadFile(dataFile)])
  .then(function(values) {
    var names = values[0];
    processData(values[1]);
  });
}

// ajax loading
function loadFile(filename) {
  return new Promise(function(resolve, error) {
    var client = new XMLHttpRequest();
    client.open('GET', filename, true);
    client.onreadystatechange = function() {
      if (client.readyState == 4 && client.status == 200) {
        var result = client.responseText.split("\n");
        // custom handling for the data set..
        if (result[0].search(',') !== -1) {
          result = arrCSVtoObj(result);
        }
        resolve(result);
      }
    };
    client.send();
  });
}


It's great that you've put the questions and answers in arrays. You can take further advantage of that in your for loop. Notice how you're always looking at the place in the array that's indexed on less than num? You can use num - 1 as an array index. That eliminates all the duplication in your loop body.

for num in question:
    user_answer = input(questions[num - 1])
    if user_answer.lower() == answers[num - 1]:
        print("Correct\n")
        score += 1
    else:
        print("Incorrect\n")

As mentioned in the comments by Sisoma Munden, score = score + 1 can be turned into score += 1. This works for other arithmetic operators too (someVar *= 3 multiplies someVar by three).

You've also hardcoded the number of questions (in the random.sample line). You can get the length/count of a Python array by passing it to len. For instance, len(questions) is the number of items in the questions array. Therefore, you can replace the random.sample line with this:

question = random.sample(range(1, len(questions) + 1), len(questions))

Then your score-displaying line becomes this (I fixed the display as well, + concatenates strings together, the str function gets the text representation of a number):

print("Your final score is" + str(score) + " out of " + str(len(questions)) + "\n")

Come to think of it, I used len(questions) a lot there. You might consider declaring a variable for that after your arrays:

questionCount = len(questions)

You can then use that in place of len(questions).


With the given feedback I was able to remove the deepclone and to remove recursivity, which resulted in speed gains and simplicity gains.

The final version of the algorithm is now in the question ( I updated it ) and I will now mark this thread as solved.


As a rule of thumb in programming, "there are only four numbers": zero, one, two, and "many".  You have seven photo fields, which means that you should just treat that as "many".  Not only is that an unfortunate artificial limitation (someday there will be a listing with eight photos, and you won't be able to accommodate it easily), it's also a pain to write code that uses your schema (you either have to copy-and-paste code six times, or use variably-named identifiers).

What you want is a separate table for photos, to support a one-to-many relationship.


Creating a list out of a string
wordList = []
for i in "UDDDUdddDDUDDddDdDddDDUDDdUUDd":
   wordList.append(i)

can be shortened to:
wordList = list("UDDDUdddDDUDDddDdDddDDUDDdUUDd")

Algorithm
The first idea is to check the sequence letter by letter. This is more efficient than generating the sequence for a number x and then see if it matches the target sequence.
To find the number that matches Dd starting from 3, it would be:

x = 3
3 % 3 == 0, so it matches D
x = 3 / 3 = 1
1 doesn't match d, so try next number
x = 3 + 1 = 4
4 doesn't match D
x = 4 + 1 = 5
5 doesn't match D
x = 5 + 1 = 6
6 matches D
x = 6 / 3 = 2
2 matches d
Solution is 6

Second idea is to filter out numbers that cannot be part of the solution.
In the previous example, numbers 4 and 5 can be filtered out. Similarly to your n += 3. Let's see some examples:
Numbers that match the prefix D:
3,6,9,12,15,18,21...

Numbers that match the prefix DD:
9,18,27,36...

Numbers that match the prefix DDD:
27,54,81,...

Each sequence is a subset of the previous.
Numbers in the sequence differ by \$3^i\$, with i starting from 1.

Numbers that match the prefix U:
4,7,10,13,16,19,21,...

Numbers that match the prefix UU:
7,16,25,34,...

Numbers that match the prefix UUU:
25,52,79,...

Each sequence is a subset of the previous.
Numbers in the sequence differ by \$3^i\$, with i starting from 1.

Same for sequences that match d. Let's see a mixed prefix.
Numbers that match the prefix D:
3,6,9,12,15,18,21...

Numbers that match the prefix DU:
12,21,30,...

Each sequence is a subset of the previous.
Numbers in the sequence differ by \$3^i\$, with i starting from 1.


How can I better my URL checker program?

You forgot using using in your StreamReader

    using(StreamReader file = new StreamReader(inputFile)){
    string outputFile = @"D:\tmp\out.txt";

    ClearOutputFile(outputFile);

    while(!string.IsNullOrEmpty(line = file.ReadLine()))
    {
        string currentUrlAndStatus = CheckURL(line);
        if(!string.IsNullOrEmpty(currentUrlAndStatus))
        {
            WriteToFile(currentUrlStatus, outputFile);
        }
    }
  }

Use the var keyword for local variables, let the compiler figure out the type for you. Type inference helps in refactoring.

 var line = string.Empty;
 var inputFile = @"D:\tmp\links.txt";
 using(var file = new StreamReader(inputFile)){
 //...
 }
 var outputFile = @"D:\tmp\out.txt";
 // etc..


I'm not quite certain about the use of node and escaping, and I'm going to assume that it does exactly what you need, focusing on the code and style of your script only.

First, I notice that you use an if statement to check whether $1 is -n, then another where you check whether it is not -n.  You could, of course, use an if/then/else construction for that.

Secondly, instead of looping backwards through the command line arguments with ${BASH_ARGV[*]}, concatenating them with +es, could have unexpected side effects if you use quoted spaces, as in:

for i in ${BASH_ARGV[*]}; do
    search="$i+$search"
done
echo "$search"

Will do something like (I'm going to call the script google.sh here):

-> % ./google.sh -n this and that "thing at once"
-n+this+and+that+once+at+thing+

Instead, you could use the bash built-in replacement function and the all-parameters variable like this:

args="$*"
search=${args// /+}
echo "$search"

Which would produce:

-> % ./google.sh -n this and that "thing at once"
-n+this+and+that+thing+at+once

Thirdly, I do like "one line ifs", and would change the two checks for missing arguments to -n like follows:

[[ $# -lt 2 ]] && echo "Usage: google [-n] term [, term [, term...]]" && exit 1

But that is a matter of taste.  It does save three lines, though, and makes clear that it is some kind of precondition check (the lines end in exit).

Lastly, I would always start a script with a shebang, making it executable from the command line directly, but this also depends on how it is going to be used.

Applying these points, the code would look like:

#!/usr/bin/env bash

if [[ $1 == "-n" ]]
then
    [[ $# -lt 2 ]] && echo "Usage: google [-n] term [, term [, term...]]" && exit 1
else
    [[ $# -lt 1 ]] && echo "Usage: google [-n] term [, term [, term...]]" && exit 2

    if [[ $(node -v) != *"v"* ]]; then
        echo "This tool uses node.js to escape url entities"
        echo "To use this tool without escapes include -n as the first agument"
        echo "(THIS IS NOT RECOMMENDED!)"
        exit 3
    fi
fi

args="$*"
search=${args// /+}

escapedSearch=`node -e "a = escape(\"$search\"); console.log(a)"`

open "http://www.google.com/search?q=$escapedSearch"

You would probably do something with the -n flag between the then and else, like setting a variable, and deciding whether to call node or not, before calling open.


It's unclear what CreateRandomCardList is intended for during gameplay. I know, technically, it's generating random cards but then why just 11 (loop < 12), why not 13?

Nevertheless, I strongly feel, the Action class is clearly misleading. I would instead prefer to have a Deck which knows what cards it holds. Also, Card type should be as simple as possible, perhaps knowing only Suit and Value. RandomCardGenerator does not belong there.

// Deck is general term. You can more appropriately
// name it as DeckOfCards, CardDeck, or anything you deem fit.
public class Deck {
    private Card[] cards;

    // Setup() is purposely part of Deck creation because without cards deck is useless.
    public Deck() {
        // fill up 13 cards
        Setup();
    }

    private Cards[] Setup() {} // CreateFullSetCard()
    private Cards[] Shuffle() {}

    //.. so on
}

The Deck should not be static because

It is going to have it's own state.
If there are > 1 players, each will have their own Deck of cards. Even if it's single player, it should not be static for #1 reason.


Spliting PDF and get thumbnail while adding it to a ListView

This code leaves a bunch of open questions, minor ones:
- SplitPDF2(string input) what has been/happened to SplitPDF() or SplitPDF1()?
- what is lista2?

Non-minor:

Document/comment your source code. In the code.
Preparing thumbnails and splitting a PDF into separate-file-per-page do neither sound nor look related:
Do not put/implement both in a single procedure
I can't seem to see a purpose in saving each thumbnail rendered into a MemoryStream ms that doesn't get used otherwise.
You instantiate one and only one iTextSharp.text.pdf.PdfReader(input) for each input:
Do the same for PdfiumViewer.PdfDocument
it will add the thumbnail I don't see that.

Overall, I'm left mistrusting writing file-per-page PDF to be a useful step in accomplishing the larger task at hand.
wish someone could say where [to improve the] code so it doesn't take that long my crystal ball is dull, but profiling/timeit() might help.


Make binary search tree from sorted array

Simplify

The special handling for nums.length == 1 is unnecessary. This works just as well:

public TreeNode sortedArrayToBST(int[] nums) {
    if (nums == null || nums.length == 0) {
        return null;
    }
    int length = nums.length;
    TreeNode root = new TreeNode(nums[length / 2]);
    int[] numsLeft = Arrays.copyOfRange(nums, 0, nums.length / 2);
    int[] numsRight = Arrays.copyOfRange(nums, (nums.length / 2) + 1, nums.length);
    root.left = sortedArrayToBST(numsLeft);
    root.right = sortedArrayToBST(numsRight);
    return root;
}

Improve

While your solution works, some aspects can be improved:

Array copy is not cheap, it would be better to avoid
The null check is only necessary on the first call, in recursive calls it will always be false

The way to solve both of these issues is to introduce a helper method taking the start and end points of a range in the source array. Something like this, the most juicy part omitted to avoid spoiling your exercise:

public TreeNode sortedArrayToBST(int[] nums) {
    if (nums == null) {
        return null;
    }

    return sortedArrayToBST(nums, 0, nums.length);
}

private TreeNode sortedArrayToBST(int[] nums, int start, int end) {
    if (start == end) {
        return null;
    }

    // ...
}

Note that there is no more check on nums.length == 0, the start == end in the helper takes care of that. The function can be completed by adding a few lines with recursive calls, with adjusted range parameters.


You should check if ReadProcessMemory fails (returns 0)
parse sys.argv only once
read bigger chunks of memory in a row into an efficient array
best use numpy for search  (or at least array.array)

Key lines using numpy:

import numpy as np

match_val = int(sys.argv[1])
a = np.zeros(4096, 'l')     # chunk size; should be even bigger ..
r = ReadProcessMemory(ph, chunk_start_adr, a.ctypes.data,
                      a.itemsize * a.size, c.byref(bytesRead))
if r:
    indices, = np.where(a == match_val)   # fast bulk search
    log.write(''.join('%x\r\n' % i for i in indices))

It will be lightning fast.


#includes should not end with a semicolon:

#include "gameOfLife.h";

The reason this is incorrect is because this is a preprocessor directive, which do not follow the same syntax as compiled lines.
Instead of using a typedef:

typedef std::vector< std::vector<int>> gridVector;

you can now use C++11's type alias:

using std::vector<std::vector<int>> = gridVector;

If you don't need the default constructor, you can either leave it out or make it explicitly defaulted:

gameOfLife() = default;

There's really no need for multiple public and private sections.  If you prefer to organize or separate the members in some way, you can just add line breaks.
I'm not sure why you have a *gridCopy member.  Not only would it be more natural to use a copy constructor in such cases, but having a raw pointer as a member would "force" you to have an overloaded copy constructor.  This is because the default copy constructor performs shallow copies, which will copy the pointer instead of the value at that pointer.

After removing this member, you should also remove copyGrid().
I'm not too familiar with GoL, but I don't think that while loop in run() is supposed to run infinitely.  This type of while loop will not stop unless a break or return is encountered.  You may need to modify it in such a way that it can end.


To the readers: I had to use ::tolower because the std:: version was causing compiler errors. I'm investigating this right now. The issue stems from std::tolower being overloaded. What is funny is that it is in header <locale>, which means that the standard library implementation includes it in some way. Rakete1111 proposed lambda version, which works great.

Yes.

Use more standard library:

The std::string provides reverse iterators, so there is no need to do any copy at all. In fact, it is possible to it with indices, but it won't look that pretty:

    return std::equal(str.cbegin(), str.cbegin() + str.size() / 2, str.crbegin(),
                      [](unsigned char lhs, unsigned char rhs) {
                          return std::tolower(lhs) == std::tolower(rhs);
                      });

The actual version was different, thanks to Rakete1111 for a new version. There is a note in the comments from Loki and Jerry: it seems like using functions in <cctype> are dangerous and will result in undefined behavior unless the input is cast into unsigned char first.

It is also possible to refactor the ugly + str.size() / 2 into reusable function:

#include <iterator>

//some namespace
template <typename Container>
constexpr auto mid(const Container& container)
{
    auto half_distance = std::distance(std::begin(container),
                                       std::end(container)) / 2;
    return std::next(container.begin(), half_distance);
}

Then it transforms into:

bool is_palindrome(const std::string& str) {
    return std::equal(str.cbegin(), mid(str), str.crbegin(),
                      [](unsigned char lhs, unsigned char rhs) {
                          return std::tolower(lhs) == std::tolower(rhs);
                      });
}

Other things that could be done better:

Avoid std::endl. It can cause big performance issues.
There is a typo in the word palindrome.
std::boolalpha could be used to provide more user friendly output.
more unit tests.
It seems like the code is missing <cctype> header as well.
putting everything into a namespace. Absence of it will force users to do unqualified call, which is prone to ADL, which is sometimes very evil.

Put together:

#include <iomanip>
#include <iostream>
#include <algorithm>
#include <string>
#include <cctype>
#include <iterator>

//some namespace
template <typename Container>
constexpr auto mid(const Container& container)
{
    auto half_distance = std::distance(std::begin(container),
                                       std::end(container)) / 2;
    return std::next(container.begin(), half_distance);
}

bool is_palindrome(const std::string& str) {
    return std::equal(str.cbegin(), mid(str), str.crbegin(),
                      [](unsigned char lhs, unsigned char rhs) {
                          return std::tolower(lhs) == std::tolower(rhs);
                      });
}

int main()
{
    std::string str{ "KArak" };
    std::cout << std::boolalpha;
    std::cout << "is \"KArak\" palindrome? " << is_palindrome(str) << '\n';
    std::cout << "is \"fuf\" palindrome? " << is_palindrome("fuf") << '\n';
    std::cout << "is empty string palindrome? " << is_palindrome("") << '\n';
    return 0;
}

Live demo.