Things I would fix:

All of your condition test statements do exactly the same thing.

else if (item == 1)
{
    if (paid >= item1)
    {
        System.out.println("Thank you for buying item " + item + ", your change is $" + (paid-item1) + ". Please come again!");
    }
    if (paid < item1)
    {
        System.out.println("Please insert another " + "$" + (item1-paid));
    }
}
else if (item == 3)
{
    if (paid >= item3)
    {
        System.out.println("Thank you for buying item " + item + ", your change is $" + (paid-item3) + ". Please come again!");
    }
    if (paid < item3)
    {
        System.out.println("Please insert another " + "$" + (item3-paid));
    }
}
...

You can use arrays to help solve this issue.

double[] prices = new double[] { 1.25, 0.75, 0.9, 0.75, 1.5, 0.75 };

Then you can access those specific values with prices[item - 1].  Remember that arrays start with the index 0, so without subtracting 1 you will end up with an off-by-one error.  The comparison is now simplified.

if (paid >= (prices[item - 1]))
{
    System.out.println("Thank you for buying item " + item + ", your change is " + (paid - prices[item - 1]) + ". Please come again!");
}

You ask the user to insert more money, but never actually allow him to.

if (paid < item2)
{
    System.out.println("Please insert another " + "$" + (item2-paid));
}

This can easily be solved with a while loop and another pair of input request statements.

You never close your Scanner when you are finished with it (a memory issue).

keyboard.close();

You never check if the item you buy is actually within the bounds of the array length.

if (!(item <= prices.length))
{
    System.out.println("Sorry, we don't have that item in stock.");
    keyboard.close();
    return;
}

When working with money, it is hard to work with doubles, they are too imprecise.  An example of this is that 0.42 - .21 is likely something like 0.209999999999999997 rather than 0.21 exactly.

We are going to use the NumberFormat class to make sure that the our double values will stay accurate.

NumberFormat.getCurrencyInstance().format(number)

Recommendations that are optional:

Don't do this:

import java.util.*;

It could be problematic for the compiler to import a bunch of packages at once. If two packages provide the same type, both are imported, and the type is used in the class, a compile-time error occurs. This is described in JLS 6.5.5.1:

  Otherwise, if a type of that name is declared by more than one type-import-on-demand declaration of the compilation unit, then the name is ambiguous as a type name; a compile-time error occurs.

In addition, it also saves a bit of memory.  And your IDE (if you use one), should have the ability to do this automatically.

You might note that this:

public static void main(String... args)

Is a bit different than your usual:

public static void main(String[] args)

They both do the same thing, but one uses variable arity parameters.

The Scanner.nextInt() method does not read the last newline character of your input, and thus a newline could be consumed if you call Scanner.nextLine.  I prefer to use Scanner.nextLine since you can input any valid String, and then just parse it into the type you need (as long as it's a valid type to parse it to).

Final code:

import java.text.NumberFormat;
import java.util.Scanner;

public class Test
{
    public static void main(String... args)
    {
        Scanner keyboard = new Scanner(System.in);
        double[] prices = new double[] { 1.25, 0.75, 0.9, 0.75, 1.5, 0.75 };
        int item = 0;

        System.out.print("Enter an item number: ");
        item = Integer.parseInt(keyboard.nextLine());
        if (!(item <= prices.length))
        {
            System.out.println("Sorry, we don't have that item in stock.");
            keyboard.close();
            return;
        }

        System.out.print("Enter the amount paid: ");
        double paid = Double.parseDouble(keyboard.nextLine());

        while (paid < (prices[item - 1]))
        {
            System.out.print("You need " + NumberFormat.getCurrencyInstance().format(Math.abs((paid - prices[item - 1]))) + " more for item " + item);
            paid += Double.parseDouble(keyboard.nextLine());
        }
        System.out.println("Thank you for buying item " + item + ", your change is " + NumberFormat.getCurrencyInstance().format((paid - prices[item - 1])) + ". Please come again!");

        keyboard.close();
    }
}


LeetCode: Trie Tree implementation, Search, Insert, startWith C#

In terms of data structures and algorithms this all looks pretty straightforward - not much to say about that.

Performance

Edges.ContainsKey and Edges[...] each perform a lookup. Edges.TryGetValue lets you achieve the same with just a single lookup.

Design

I see no reason why Trie.Head should be public, and certainly not why it should have a public setter. That's poor encapsulation. Likewise, TrieNode.Edges should be get-only: you don't want outside code to be able to do Edges = null;.
Search and StartsWith do exactly the same thing, except for the final check. I'd move the duplicate code to a TrieNode FindNode(string prefix) helper method.
TrieNode is only used internally within Trie, so it makes sense to make it a private inner class.

Other notes

You can remove Trie's constructor if you initialize Head directly: TrieNode Head { get; } = new TrieNode();. The same goes for TrieNode and Edges.
I'd replace those for loops with foreach loops, for clarity's sake.
Comparing a boolean against true is unnecessary. Just do return current.IsTerminal;
I'd replace those default LeetCode comments with C#-specific xml comments.


Welcome to Code Review!

isLeaf compares the Size of children, a solution that is better readable is to use isEmpty() instead of compare the size of children.
The tree avoid a serialization that others may support, add the serializable-interface to keep serialization support.
edgeVal and data have no setter and to add final would help to avoid sideeffects whenever the code changes.
To have a ArrayList as a list of children has the problem that

The ArrayList can contain null
The ArrayList can contain one element twice (i do not think its a case you like to have)

You better use some kind of set, a LinkedHashSet in example.
You can use getChildren() to have read-write-access to the children, if you do oscar.getChildren().add(oscar); your loop is perfect but not a Tree. Use the unmodifyable-functions of the class Collections to return a readonly-collection.
The class is named Tree that can contains a list of Tree. Even if a Tree can be a parasite to other Trees i propose to name the Class TreeNode.
toString should describe the node, not the data inside.
Am i the only one who write javadoc?


You could unpack them twice into (overlapping) unsigned shorts of 16bit and shift/mask them accordingly.

upper12 = struct.unpack(">H", msg[1:-1])[0] >> 4
lower12 = struct.unpack(">H", msg[2:])[0] & 0xFFF

Telling Python to interpret them as short integers helps you to get rid of int.from_bytes.


Implementation of a templated Singly linked list class in c++

Advice 1

You can move the definition of node into the declaration body of one_way_linked_list. This allows "inheritting" the type parameter t, and, thus, omitting it altogether in the node.

Advice 2

node(t d)
{
    data=d;
    next=NULL;
}

The more C++ way would be:

node(t d) : data{d}, next{nullptr} {}

Advice 3

Most C++ programmers write the type parameters starting from an uppercase letter. In your case, I suggest you rename t to T in the template declaration.

Advice 4

public:
    node<t> *head=NULL;
    node<t> *prev=NULL;

Here, you expose the implementation details. Move the two under a private:. Also, write nullptr instead of NULL.

Advice 5

prev: a better name is tail.

Advice 6

list_create: a better name is add or append.

Advice 7

template<typename t>
void one_way_linked_list<t>::list_delete()
{
    node<t> *ptr=new node<t>();
    ptr->data=this->head->data;
    while(ptr!=NULL)
    {
        ptr=ptr->next;
        delete ptr;
    }
    delete this->head;
    head=NULL;
    cout<<"Deleted"<<endl;
}

rewrite as:

node<t>* next;
node<t>* current = head;

while (current) {
    next = current->next;
    delete current;
    current = next;
}


Monitor asynchronous tasks, tracking their running times

Ugly typedef

I'm not a big fan of this:

typedef std::future<int> FutureResultInt;

It's not significantly shorter or easier to read, it doesn't isolate the user from an underlying type, and it only serves to slow down my reading every time I hit it.  That's somewhat subjective, of course, but I don't believe it adds value.  I'd be happier with it if it told us what it's for, rather than merely what it is.  I'm thinking of something like:

using TimerTaskResult = std::future<int>;

Now the name conveys something that's not just duplicating the standard name.

Member initialization

My compiler warns me that the initializer list is in a misleading order:

203856.cpp:47:54: warning: ‘CFutureTest::m_start’ will be initialized after [-Wreorder]
203856.cpp:46:19: warning:   ‘FutureResultInt CFutureTest::m_result’ [-Wreorder]
203856.cpp:33:3: warning:   when initialized here [-Wreorder]
   CFutureTest(FutureResultInt&& fr)
   ^~~~~~~~~~~

I'd also recommend value-initializing m_result rather than default-constructing followed by move-assigning:

  CFutureTest(FutureResultInt&& fr)
      : m_result{std::move(fr)}
      , m_start{std::chrono::system_clock::now()}
  {
  }

Missing case

203856.cpp: In function ‘int main()’:
203856.cpp:63:14: warning: enumeration value ‘ready’ not handled in switch [-Wswitch]
       switch (stat)
              ^

I like to have this warning enabled.  We could provide a minimal case std::future_status::ready: break;, or we could unify the control flow by changing the other branches from continue to break and inlining the following code into the ready case like this:

        switch (stat) {
        case std::future_status::timeout:
            if (future.GetAge() > 4000) {
                std::cout << "Thread has exceeded the time limit" << std::endl;
            }
            break;

        case std::future_status::deferred:
            std::cout << "std::future_status::deferred" << std::endl;
            break;

        case std::future_status::ready:
            {
                const int iResult = future.m_result.get();
                std::cout << "future returned [" << iResult << "] (removing!)" << std::endl;
                futures.erase(it);

                if (futures.empty()) {
                    return 0;
                } else {
                    it = futures.begin();
                }
            }
        }

Instead of returning to futures.begin() when we harvest a result, it's arguably better to keep going from the next element if there is one:

                it = futures.erase(it);
                if (it == futures.end()) {
                    if (futures.empty()) {
                        return 0;
                    } else {
                        it = futures.begin();
                    }
                }

Interleaved output

I know it's not part of your production code, but it's quite irritating to have the different threads' output interrupting each other mid-line.  We can provide a class to hold a lock while several items are written to a stream:

class LogStream
{
    static std::mutex mutex;

    std::lock_guard<std::mutex> guard{mutex};
    std::ostream& stream{std::clog};

public:
    LogStream() {}
    template<typename T>
    std::ostream& operator<<(T&& t) { return stream << std::forward<T>(t); }
};

std::mutex LogStream::mutex;

And use it like this:

LogStream() << "ThreadFunc waiting for [" << iRand << "] ms ... " << std::endl;

Be clear about units

I don't like this function name:

int GetAge() const

Perhaps change it to getAgeMillis(), or how about making it a template method? Like this:

template<typename TimeUnit = std::chrono::seconds>
int GetAge() const
{
    auto now = std::chrono::system_clock::now();
    return std::chrono::duration_cast<TimeUnit>(now - m_start).count();
}

That also helps us deal with the very long lines that are a perennial problem with duration_cast.

Avoid polling

This is the big one.  It's very power-inefficient to poll every 1ms to see whether you have any results; that's a bad thing on battery-powered systems, but it's just as important in a server farm.

What we need to do instead is have each finishing thread notify a condition variable.  When we're woken, we then examine all the futures, picking up any where is_ready().

Unfortunately, that means we can't use std::async(), as its future isn't made ready until the called function has returned.  We'll need to implement our own version that can accept a std::condition_variable& to be notified after it sets the future's value.

You might be able to pick up some advice from Stack Overflow - here's a couple of starting points that might have something relevant:

Signaling main thread when std::future is ready to be retrieved
How to implement std::when_any without polling?


Convert a string into an R vector expression

How I would do it:

import Data.List.Split
import Data.List
foo delim s = "c(\"" ++ intercalate "\",\"" (wordsBy (`elem` delim) s) ++ "\")"

reads yours

No brackets needed around unpack . strip . pack.

I would replace if toStrip then map stripString ws else ws with (if toStrip then map stripString else id) ws.

Some of your names are unneeded; I would inline ws, ws1 and ws2 into where they are used (once ws is only used once), perhaps even res.

Instead of foldl (++), use concat.


Run two computations in parallel, and return the results together

From my point of view the implementation is free of race condition because the parallel method does not access any shared variables. All its state is in its local variables so is not shared.

That is not true. The variable aResult is shared between the thread that called parallel and the thread t1. So there needs to be some synchronization between these two threads, otherwise you run into undefined behaviour.

This low-level JDK memory model gets tricky, so I would try to avoid it as far as possible, i.e. use higher-level abstractions and prefer immutable state.

I suppose the following (still rather low-level) tools (which would solve these issues) are not available for this exercise:

Scala Futures
Java Callables (which return a result instead of having to publish it somewhere)
java.util.concurrent.AtomicReference (which you can use as a thread-safe holder if you have to use Runnable instead of Callable)

As for the specific question: According to the Java Memory Model FAQ

  All actions in a thread happen before any other thread successfully returns from a join() on that thread.

Meaning that after your master thread has joined the first worker thread, it will read the updated value of aResult without that field needing to be volatile.

So your code looks correct to me.

But I had to look this up. Really try to avoid mutable state when multiple threads are concerned.


Improving performance of VBA batch scripts?

Rather than copying sheet by sheet - plus deleting three excess sheets one by one, either

Delete the sheets you don't need then use SaveAs on the reduced file.
Copy both sheets you need to a new file in a single hit.

(Also, don't Dim variables inside a loop)

(2) below

Sub Flujo()

Const FilePath = "A path..."
Const Destination = "Another path..."
Dim xlApp As New Excel.Application

With xlApp
    .Visible = False
    .ScreenUpdating = False
    .DisplayAlerts = False
End With

Dim strDir As String
Dim WrkBook As Workbook

strDir = Dir(FilePath & "\*.xlsx")

Do While Len(strDir) > 0
Set WrkBook = xlApp.Workbooks.Open(Filename:=FilePath & "\" & strDir, UpdateLinks:=0)
  WrkBook.Sheets(Array("SheetName", "AnotherSheetName")).Copy
  ActiveWorkbook.SaveAs Filename:=Destination & "flujo_" & WrkBook.Name
  ActiveWorkbook.Close False
  WrkBook.Close False
strDir = Dir
Loop

xlApp.DisplayAlerts = True

xlApp.Quit
Set xlApp = Nothing
End Sub


Sass code for displaying two simple search forms

Sass

If this is meant to be a reusable Sass library, you'll want to make use of default variables so that they're easier to override:

$container-width: 940px !default;
$search-container-padding: 54px !default;

You'll want to do something similar with your mixins so that the values can be changed for one-off instances:

@mixin input-width($width, $form-width: $default-form-width, $button-width: $default-button-width, $input-inset: $default-input-inset)
{
    .search-input
    {
        width:$width;
    }
    .search-placeholder
    {
        left:$form-width - $width - $button-width + $input-inset;
    }
}

You'll probably want to avoid generating styles by default, since the user might not want them.  It is a common request for people who use libraries like Bootstrap and Foundation:  how do I make it stop generating default styles?  Instead, you might want to consider having a separate file that can be imported that generates these styles.

The $input-br variable has an ambiguous name.  When I initially saw it in the source, I thought it was for the br element.  It wasn't until later I realized br was being used as an abbreviation for border-radius (none of your other variables are abbreviated).

Sass has a bit of a shortcut you can use for some properties:

border: {
  top: $input-border;
  bottom:$input-border;
  left:$input-border;
  radius: $input-br 0 0 $input-br;
}

CSS

If the background image for your button fails to load, the button is completely invisible because it is white text on a white background.

The use of px units here is sub-optimal.  When your containers contain text, you should be using a unit that's relative to the font-size, like em or ex, to specify its measurements.  If the user changes their browser's font settings in such a way that they want their font size to be 20px at the bare minimum, then your content is going to spill out of these containers.

Using archaic widths of yesteryear (900px~1024px) are very unfriendly towards mobile devices.  Set a max-width if you must, but avoid setting hard widths that are likely to cause horizontal scrolling.  Better yet, look into responsive design.

HTML

Placeholder text is not meant to be a replacement for labels, please don't treat it as such.  It should be thought of as example content only.

Labels must have a closing tag.  If they're not containing the input element that they're for, they need to have a for attribute and the associated input element needs to have an id with the matching value.

There's a new input type of search that I recommend using instead of text for your search input fields.  Browsers that don't support search will fallback and use text anyway.

Your 2nd submit button has a class of submit rather than a type.


I'm not sure this answer will be sufficient, but some quick things that jump out:

Keep your code organized:

Put imports at the top
Guard any serious code execution in a __name__ == '__main__' block (and usually use a main function as well)
Have blank space every few lines to visually separate logical groups of code
If the code doesn't document itself (and ideally, it should), add comments where necessary

Use consistent, conventionally Pythonic naming, such as using lower-case snake-case for variable names (e.g., return_code instead of rCod)
As a super minor detail, there are better ways to construct strings than adding them. A fairly modern, flexible way to do so is to use .format, or if you can be sure you're using Python 3.6+ then "f-strings" are wonderful)
It's really not clear why you sleep for a random amount of time at the end... If that's important, comment why so, otherwise probably don't do it. If there's something specific you're waiting on, figure out how to wait for it properly so you don't have a possible race condition.
I'm not super familiar with Windows commands and what /S /Q do to the rmdir command, but could you not just use os.rmdir(del_dir)?

Here's what your code might look like using the above suggestions:

import os
import subprocess
import winshell
from random import randint
from time import sleep

def main():
    file_size = os.path.getsize('C:\Windows\Temp')
    print("{} kb of data will be removed".format(file_size))
    del_dir = r'c:\windows\temp'

    # Could this just be os.rmdir(del_dir)???
    process = subprocess.Popen('rmdir /S /Q {}'.format(del_dir), shell=True,
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    _ = process.communicate()
    return_code = process.returncode
    if return_code == 0:
        print('Success: Cleaned Windows Temp Folder')
    else:
        print('Fail: Unable to Clean Windows Temp Folder')

    winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=False)

    # Is this important?
    # sleep(randint(4, 6))
    input("Press any key to continue")

if __name__ == '__main__':
    main()


Checking if a value is in the RGB range and then increment/decrement

Avoid repeating yourself
First, avoid having separate variables for r, g and b. It means you have to write all code three times. Just store the three components in a list, like so:
color = [0, 255, 0]

Then you can pass color to other functions, and have those functions iterate over the elements of the list.
Better way to create a triangle wave
What you are doing is basically creating a triangle wave shape for the intensity of each color component. Instead of keeping the current color value and a flag to store whether you are on the increasing slope or decreasing slope, just store a variable that holds the phase in a full cycle of the triangle wave.
In this case, I would store an integer between 0 and 511 for each color component. Initialize the phase like you did the color vector before:
phase = [0, 255, 0]

When updating the phase, do:
for i in range(3):
    phase[i] += colorVel
    phase[i] %= 512

Of course, this gives a sawtooth wave, and the values you get will be too high, but now you can map it onto a triangle wave with the correct amplitude:
color = list(map(lambda x: x if x < 256 else 511 - x, phase))

Create a class to store the state of the iridescence
Even better would be to have a class manage all the internal state of an iridescence color, and allow it to be called as a function that generates the next color:
class Iridecence:
    def __init__(self, r, g, b, colVel=10):
        self.phase = [r, g, b]
        self.colVel = colVel

    def __call__(self):
        for i in range(3):
            if self.phase[i] < self.colVel:
                self.phase[i] = random.randint(1, 100)
            self.phase[i] += self.colVel
            self.phase[i] %= 512;
        return list(map(lambda x: x if x < 256 else 511 - x, self.phase))

Now you can use this as follow in your code:
irid = Iridescence(0, 255, 0)
color = irid()

while running:
    ...
    if keys[pygame.K_LEFT]:
        x -= vel
        color = irid()
    ...
    pygame.draw.rect(win, color, (x, y, width, height) )
    pygame.display.update()


Return values from array A in the order they are in array B

Your solution looks good to me, I tried some alternatives but they end up being a little more verbose and not adding value that makes it worth.

Also, I don't think it is worth adding one more step to order it just to use select.

I would go with your first solution.


Problem with pop
Your pop() function could return false when there are still elements in the list.  The problem is with this check:

      if(!lcl_ptr.s.ptr || _head == _tail) {
          return false;
      }

Here, lcl_ptr.s.ptr could be NULL if some other thread just popped that element.  If that happens, you should just move on to the next element instead of returning false.  So for example:
      if (_head == _tail) {
          return false;
      }
      if (!lcl_ptr.s.ptr) {
          continue;
      }

This solution spins until the other thread finishes incrementing the head pointer.  There may be better ways of handling this case which involve searching forward for an element to pop.


Get rid of all those commas:

i18n.init
  detectLngQS: "lang"
  ,ns: { namespaces: ['ns.common', 'ns.layout'], defaultNs: 'ns.common'}
  ,resSetPath: "./locales/__lng__/new.__ns__.json"
  ,...

CoffeScript doesn't need them:

i18n.init
  detectLngQS: "lang"
  ns: { namespaces: ['ns.common', 'ns.layout'], defaultNs: 'ns.common'}
  resSetPath: "./locales/__lng__/new.__ns__.json"


A little Python roguelike with mostly using standard libraries

Your use of y_coord and range is suboptimal here. You're iterating over a range(3) and ignoring the produced number, while also using y_coord as an iteration variable.

Just iterate over the range of numbers that you want from the start:

def check_surroundings(self, y_coord, x_coord):
    enemies = []
    for cur_y in range(y_coord - 1, y_coord + 2):  # Exclusive end
        if self.engine.check_inbounds(cur_y, x_coord - 1) and self.engine.check_inbounds(cur_y, x_coord + 2):
            for entity in self.engine.techmap[cur_y][x_coord - 1:x_coord + 1]:
                if entity and entity.team != self.team:
                    enemies.append(entity)
    return enemies

The main benefit here is the boost to readability. Ideally, it should be easy to tell what a for loop is iterating for just by looking at it.

for entity in self.engine.techmap[cur_y][x_coord - 1:x_coord + 1]:

It's obvious that you're getting all the matching entities from techmap, then doing something with each.

for _ in range(3):

Here though, you're ignoring the iteration variable, so it isn't clear what is actually changing each iteration. Superficially, it looks like you're just repeating the same body three times, which is odd. It takes a second step of thinking to realize that you're using y_coord to iterate.

This is also arguably a good place to use a list comprehension (although 2D+ list-comprehensions usually tend a little on the ugly side). The point of your nested loops is to produce a filtered list from existing collections (the iterable returned by techmap, and range in this case). That is exactly the use-case for list comprehensions.

def check_surroundings(self, y_coord, x_coord):
    return [entity
            for cur_y in range(y_coord - 1, y_coord + 2)
            if self.engine.check_inbounds(y_coord, x_coord - 1) and self.engine.check_inbounds(y_coord, x_coord + 2)
            for entity in self.engine.techmap[cur_y][x_coord - 1:x_coord + 1]
            if entity and entity.team != self.team]

You may want to save that into a variable then return the variable. It depends on your style. I can't say that I necessarily recommend using the comprehension here, but I thought I'd show that such an option is available. I'll note too that I didn't test this; I eyeballed it. It looks like it should be equivalent though.


The code is nice, there are only some minor improvements here.

I love that you have written a docstring.
You do not need the # in the variable names. These names are used for generating symbols but you do not use this capability in the code.
You could make adjusted-make a symbol when defined in the let block. This way the constructed form would be simpler and more readable.
I prefer doing assert calls for error handling in macros. You could check that the first parameter is a symbol? and the second is a vector? of keys.
Instead of (into {} (map ...)) you can also use zipmap to construct the map.

The code can be rewritten as the following:

  (defmacro defmap
"Generates a defn that creates a function with the name (str \"->\" map-name) that
returns a map. The map will have keys of fields, with the values of the arguments passed to the function."
[map-name fields]
(assert (symbol? map-name))
(assert (vector? fields))
(let [adjusted-name (symbol (str "->" map-name))
      args          (mapv (comp symbol name) fields)
      body-map      (zipmap fields args)]
  `(defn ~adjusted-name ~args ~body-map)))


Anti-pattern or acceptable way of using Promises?

The Q.resolve() and the outer then(function() {...}) are not necessary. Your code will simplify to ...

var something = 'value';
var someResultPromise = callFunctionThatReturnsPromise(something).then(function (result) {
    return processing(result);
});

... and in general that is what we would write.

However sometimes it's advantageous to start a promise chain with a resolved promise, even if it's not strictly necessary.

For example, we might want a chain such as ...

var promise = doSomethingAsync()
    .then(doSomethingAsync)
    .then(doSomethingAsync)
    .then(doSomethingAsync);

... but we might choose to write ...

var promise = Q.resolve()
    .then(doSomethingAsync)
    .then(doSomethingAsync)
    .then(doSomethingAsync)
    .then(doSomethingAsync);

... which is functionally identical but easier on the eye because it allows the first doSomethingAsync to be coded the same as all the others; it does not appear to be a special case.


You have a lot of code duplication. As a first step, your code should be rewritten somehow like that:

if (_InitialDataGridPersonList != null)
{
    var personState = GetSelectedComboBoxPersonStateText();
    var personLanguage = GetSelectedComboBoxPersonLanguageText();

    var personStateSpecified = personState != "-";
    var personLanguageSpecified = personLanguage != "-";

    if (!personStateSpecified && personLanguageSpecified)
    {
        AddPersons(_InitialDataGridPersonList
                   .Where(w => w.Language.Equals(personLanguage)));
    }
    else if (personStateSpecified && !personLanguageSpecified)
    {
        AddPersons(_InitialDataGridPersonList
                   .Where(w => w.PersonState.Equals(personState)));
    }
    else if (!personStateSpecified && !personLanguageSpecified)
    {
        AddPersons(_InitialDataGridPersonList);
    }
    else if (personStateSpecified && personLanguageSpecified)
    {
        AddPersons(_InitialDataGridPersonList
                   .Where(w => w.PersonState.Equals(personState) &&
                               w.Language.Equals(personLanguage)));
    }
}

private void AddPersons(IEnumerable<Person> persons)
{
    foreach (var person in persons)
    {
        _DataGridPersonList.Add(person);
    }
}

As a second step, you can place all comboboxes in a map where you'll link each combobox with property selector:

public enum PropertyType
{
    State,
    Language
}

private static readonly Dictionary<PropertyType, Func<Person, object>> _propertySelectors =
    new Dictionary<PropertyType, Func<Person, object>>
    {
        [PropertyType.State] = p => p.PersonState,
        [PropertyType.Language] = p => p.Language
    }

private void PopulatePersons()
{
    if (_InitialDataGridPersonList != null)
    {
        var propertyValues = Enum.GetValues(typeof(PropertyType))
                                 .Cast<PropertyType>()
                                 .ToDictionary(t => t,
                                               t => GetComboBoxText(t));

        AddPersons(_InitialDataGridPersonList.Where(p =>
        {
            return propertyValues.All(v => v.Value == "-" ||
                                           _propertySelectors[v.Key](p).Equals(v.Value)));
        });
    }
}

private void AddPersons(IEnumerable<Person> persons)
{
    foreach (var person in persons)
    {
        _DataGridPersonList.Add(person);
    }
}

private string GetComboBoxText(PropertyType propertyType)
{
    switch (propertyType)
    {
        case PropertyType.State:
            return GetSelectedComboBoxPersonStateText();
        case PropertyType.Language:
            return GetSelectedComboBoxPersonLanguageText();
        ...
    }

    return "-";
}

This approach allows you to add another comboboxes without a pain.


Functionality to read large files (> 3 GB) in chunks

Here are a few comments on your function.

Firstly taking the prototype, why return an int8_t. A simple int is better
as uint8_t will probably be slower.  Also returning several types of error
is unusual in UNIX functions like this.  I'd expect errno to tell what
failed and suggest you return the number of bytes read, 0 on EOF and -1 on
error (like read(2)).

And again on the prototype, why are you passing a FILE instead of a
descriptor?  Passing a FILE and then messing around with the raw descriptor
makes me uneasy.

You allocate a strange structure in the function.  This is odd for a low level
utility.  It is unnecessary and arguably wrong, as it means the caller cannot
avoid an allocation even if the buffer from the last call can be reused or a
static buffer is available.  Just pass a buffer and its size (as a size_t)
into the call.

And it would be more normal to pass in the size to read (as a size_t)
instead of the number of pages. If you pass a buffer and its size as I
suggested above, you don't need an extra size to say how much to read.

You are mixing use of buffered fread (operating on a FILE) and lseek (on
an fd).  This is a bad idea as you are messing with something the FILE has
reason to call its own.  If you are going to seek, then use read to read the
data.

And in your use of fread, the call returns the number of items read (number
of bytes in this case) so assigning that to a variable called curr_pos is
not sensible. The name nread would make more sense.  And keeping that value
in the byte_array structure with a different, equally meaningless name,
curr_i, is unnecessary.

Also, reading up to end-of-file might return less than requested.  That is
not an error from the perspective of this function (it might be from an
application perspective if the file size is expected to be multiples of page
size, but the handling of such an error doesn't belong here).  So calling
feof and treating end-of-file as an error is wrong.  There is only a
possible error it nread != chunk_b.  But you should be using read(2)...

Some other points:

your goto statements are unnecessary.  Occasionally gotos are useful in
simplifying error recovery, but in this case they simplify nothing.
your end_pos is unnecessary.  The file descriptor knows its current
offset, which is available with fseek(fd, 0, SEEK_CUR)
chunk_b is a bad name for a size, don't you think?
test the return from lseek immediately. If you have a stderr, use perror
to print the reason for failure (perhaps best in the calling functions).
use of sizeof(uint8_t) is silly - just use 1

EDIT

FILEs and fopen, fwrite, fread, fprintf, fgets etc are provided by stdio for use as buffered IO in which the standard library maintains a buffer through which your requests are served.  When you use fread to read (say) 10 bytes, the library might read a whole page or disc sector or line of input from the terminal (on the assumption that you'll want the rest later) and give you just the amount you asked for, saving the rest in the buffer.  The "file descriptor" (fd), which is returned by fileno, is the lower level interface to the actual file returned by open (type man 2 open on UNIX/Linux/MacOS) - open is used by fopen to open the actual file/device.

If you are doing unbuffered or 'raw' IO, you can use open/write/read/lseek etc to save the overhead of the stdio and to give you more control. Since you are explicitly seeking to the location you want to read, you are certainly doing raw (unbuffered) IO and the lower-level interface makes more sense.

On the interaction between buffered and unbuffered IO on the same underlying file descriptor, I've never read anything that suggests this is forbidden.  But intuitively it seems that using buffered IO and then moving the file's position by seeking behind stdio's back is asking for trouble. Also, if you are on a 32-bit system, stdio probably does not support files bigger than 2GB (or perhaps 4).

I just would never mix calls to the FILE and the fd.  Hopefully someone else with deeper knowledge will shed some more light on this.


There are some issues with your code concerning the code design.

Why do you use a class for your BinaryCalculator? You don't have multiple instances of the class, you do not even give the class a meaningful constructor. This task should not be solved with OOP, but just with regular functions.

You can easily drop the class and define the two functions as top level functions, e.g:

def num_to_list(num):
    ..... your code goes here ...

def bit_adder(a, b):
    ..... your bit adder goes here ....

if __name__ == '__main__':
    res = bit_adder(111101, 1011)
    print(res)

Second, you can reduce your code significantly with some utility functions, e.g for your num_to_list function:

def num_to_list(x):
    return [int(n) for n in reversed(str(x))]

Third, for your bit_adder the function zip_longest from the package itertools comes in handy. This just zips two lists like a regular zip, but fills up the shorter list with default values.

That's why I reversed the bit order in the num_to_list function earlier.

With this function you can reduce your bit_adder to a more compact version:

# zip the two revered bit lists with a default fillvalue of 0
z = itertools.zip_longest(a, b, fillvalue=0)
# add each bit, this results of a list that could look like [1, 0, 2, 1]
added = [n + k for n, k in z]

# we still have to get rid of the two's, so we iterate through the list
# and take care of the overflows, similarly to your approach
carry = 0
for n, v in enumerate(added):
    if v != 2 and carry == 0:
        continue
    elif v == 0 and carry == 1:
        added[n] = v + carry
        carry = 0
    else:
        added[n] = 0
        carry = 1

if carry == 1:
    added.append(carry)

The main advantage of this version, is that you don't have to care about the
smaller or bigger number.


Rewriting nested for loops to give better formatted output

You should extract out at least two methods:

boolean isMatchingClients(final Client client, final Client otherClient) { ... }
int calculateCommonInterests(final String clientInterests,
    final String otherClientInterests) { ... }

It would improve readabilily a lot and make the code more flatten.

I usually prefer final variables. Making a variable final relieves the programmer of excess mental juggling - he/she doesn't have to scan through the code to see if the variable has changed. (From @nerdytenor's answers.)
Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used.

For example, the count variable could be right before the second for loop:

int count = 0;
for (int c = 0; c < numberOfClients; c++)

(Effective Java, Second Edition, Item 45: Minimize the scope of local variables)
If it's possible I'd consider storing the interest data in BitSets. Then it would be possible to and two of them and get the number of common bits with the cardinality method. Here is some test code:

@Test
public void testBitSet() {
    final BitSet interestBitSet = createBitSetFromString("11100111");
    final BitSet otherInterestBitSet = createBitSetFromString("11001001");

    final BitSet clone = (BitSet) interestBitSet.clone();
    clone.and(otherInterestBitSet);

    assertEquals(3, clone.cardinality());
}

private BitSet createBitSetFromString(final String input) {
    final BitSet result = new BitSet();

    final char[] inputArray = input.toCharArray();
    for (int index = 0; index < inputArray.length; index++) {
        if (inputArray[index] == '1') {
            result.set(index);
        }
    }
    return result;
}

The and method modifies the bitset which is a disadvantage here. Cloning helps, although it's not the most beautiful solution.
Instead of

System.out.println("");

you could use

System.out.println();

You could remove some duplication:

if (count == 0) {
    System.out.println(clientDetails[b].getClientName() + "is compatible with the following client(s)");
    System.out.println("\t" + clientDetails[c].getClientName());
} else {
    System.out.println("\t" + clientDetails[c].getClientName());
}

The following is the same:

if (count == 0) {
    System.out.println(clientDetails[b].getClientName() + "is compatible with the following client(s)");
}
System.out.println("\t" + clientDetails[c].getClientName());

I'd create local variables for clientDetails[b] and clientDetails[c]. They are used a lot.
About the output: if you want to show the number of compatible clients in the header you have to count them (and maybe store them in an ArrayList to avoid running the loop twice) before printing the header. If you are not allowed to use ArrayLists I don't think that it's worth it.
I don't know what's the type of the clientGender field. If it's String, you should not compare it with != or ==. See: Java String.equals versus ==
The anyMatch variable is duplicated, it could be eliminated. It only stores the state whether count == 0 or not.

final boolean anyMatch = (count > 0);
if (anyMatch) {
    ...
}

Some optimization ideas:

Use two arrays: one for males, one for females, so you don't have to compare clients with the same sex.
Order the arrays by age and skip the definitely non-matching clients. You could use binary search here.
Use a two-dimensional array with the first dimension as the age. The second dimension contains the clients with the corresponding age.
You could use one array which is sorted by gender then age. You could use Arrays.sort and a custom compareTo method in the Client class:

@Override
public int compareTo(final Client o) {
    final int nameResult = name.compareTo(o.name);
    if (nameResult != 0) {
        return nameResult;
    }
    return age - o.age;
}

Finally, here is my two methods after the refactorings mentioned above:

public static void matchClients(final Client[] allClients) {
    for (final Client client: allClients) {
        checkClient(client, allClients);
    }
}

private static void checkClient(final Client client, final Client[] allClients) {
    int matchCount = 0;
    for (final Client otherClient: allClients) {
        if (!isMatchingClients(client, otherClient)) {
            continue;
        }
        if (matchCount == 0) {
            System.out.println(client.getClientName() +
                "is compatible with the following client(s)");
        }
        System.out.println("\t" + otherClient.getClientName());
        matchCount++;
    }
    final boolean anyMatch = (matchCount > 0);
    if (!anyMatch) {
        System.out.println(client.getClientName() +
            "is not compatible with any client.");
    }
    System.out.println();
}


Build a combinatorial matrix from two vectors


Split excel file with multiple sheets, manipulate the data and create final out file

Found a better way to iterate over the rows (although I still feel like I'm repeating myself!):

for idx, row in enumerate(active_sheet.rows):
    for i in active_sheet.rows[idx]:
        values.append(i.value)

And instead of converting the tuple to a list:

rows = [list(t) for t in zip(*[iter(values)]*column_count)]


Simple Gradient Descent Algorithm In Haskell

one obvious change would be to add type signatures,
i additionally introduced some type synonyms to distinguish between all those Doubles. A bit explanation could be done towards the algorithm - I don't know what it actually want to achieve. I am no programmer so the non understanding comes quite often.

Next thing is it seems costFunc is never used - why is it there?

and I've replaced genericLength by length and converting the result - as the library says length is faster.

type TrainData = [(Double,Double)]
type LearnRate = Double
type DeltaPair = (Double,Double)

trainingSet ::  TrainData
trainingSet = [ (1.0,10.0),(2.0,20.0),(3.0,30.0),(4.0,40.0) ]

hypothesis :: DeltaPair -> Double -> Double
hypothesis (d1,d2) x = d1 + (d2 * x)

costFunc :: TrainData -> DeltaPair -> Double
costFunc ts d = scaleFactor * sum squares
    where scaleFactor = 1.0 / (2 * fromIntegral (length ts))
          squares = map (square . diff d) ts
          square x = x * x

diff :: DeltaPair -> (Double, Double) -> Double
diff d (x,y) = hypothesis d x - y

descendTheta :: ((Double, Double) -> Double) -> (DeltaPair -> Double) -> TrainData -> LearnRate -> DeltaPair -> Double
descendTheta thetaFunc deltaFunc ts lr deltas =
    deltaFunc deltas - (scaleFactor * sum scaledDiffs)
    where scaleFactor = lr / fromIntegral (length ts)
          diffs = map (diff deltas) ts
          scaledDiffs = map (\(x,y) -> x * thetaFunc y) $ zip diffs ts

descendThetaZero :: TrainData -> LearnRate -> (Double, Double) -> Double
descendThetaZero = descendTheta (const 1) fst

descendThetaOne :: TrainData -> LearnRate -> (Double, Double) -> Double
descendThetaOne = descendTheta fst snd

singleDescend :: TrainData -> LearnRate -> DeltaPair -> DeltaPair
singleDescend ts lr deltas = (thetaZero, thetaOne)
    where thetaZero = descendThetaZero ts lr deltas
          thetaOne = descendThetaOne ts lr deltas

descend :: (DeltaPair -> DeltaPair) -> DeltaPair -> Int -> DeltaPair
descend f deltas i
    | i < 0 = error "no negative numbers"
    | i == 0 = deltas
    | otherwise = descend f (f deltas) (i-1)

main :: IO ()
main = print (descend descendFunc (100, 1) 10000)
    where descendFunc = singleDescend trainingSet 0.1


Python List Continuation with multiple lambdas applied

The biggest problem with your code was the formatting issues (PEP8 violations), which you already fixed, with the exception of workingList which should be working_list.

Doc strings would be nice.

Instead of "uniquify", perhaps unique or even uniq sounds better.

In your first lambda you used word as the variable, in the second you used x. It would be more natural to unify.

This code doesn't make your ass look fat, I think.


I would simulate the enum using class constants.

class VoucherType {
  const INVOICE = 0;
  const CREDIT_NOTE = 1;
  const ADVANCE = 2;
}

$myType = VoucherType::INVOICE;

They are accesible from everywhere you can access the class, virtually everywhere if you use (and you should) an autoloader.

This is a readable and well-known pattern but there are more sophisticated options, starting with SplEnum and ending with php7-enum, but I like the simplicity of the constants.

Also I you are new to PHP I recommend you to read other's code to learn and get used to the language.


Top 2 most common elements inside array in Python

If you're okay with using the built-in collections module, I'd suggest the following. collections.Counter is ideally suited for this and will make the problem trivial.

from collections import Counter

def top_k(numbers, k=2):
    """The counter.most_common([k]) method works
    in the following way:
    >>> Counter('abracadabra').most_common(3)
    [('a', 5), ('r', 2), ('b', 2)]
    """

    c = Counter(numbers)
    most_common = [key for key, val in c.most_common(k)]

    return most_common

Without using the built-in collections module, the following will work:

def top_k_nobuiltin(numbers, k=2):
    # The first part is identical to your implementation and works just
    # fine
    counter = {}
    for number in numbers:
        if number in counter:
            counter[number] += 1
        else:
            counter[number] = 1

    # The line below creates an iterator that will generate the
    # sequence [(4, 3), (3, 2), (5, 1), (1, 1)], i.e.
    # count the occurrence for each value.
    # In particular, sorted() with key=lambda kv: kv[1] will turn
    # a dictionary into a list of tuples, sorted by the second item
    # of each tuple

    sorted_by_value = reversed(sorted(counter.items(), key=lambda kv: kv[1]))

    top_vals = [item[0] for item in sorted_by_value][:k]

    return top_vals

For both cases, you'll get the desired result:

def main():
    nums = [1, 4, 3, 4, 5, 3, 4]  # [4,3]

    print(top_k(nums))  # [4,3]
    print(top_k_nobuiltin(nums))  # [4,3]

if __name__ == '__main__':
    main()


My implementation of javascript class library

There is nothing fundamentally wrong about your class strategy, it is a matter of personal style really. The only suggestion I would have is to add Object.prototype.hasOwnProperty guards in the for-in loops, to avoid extending your classes with bogus properties if someone adds things to Object.prototype.

for (var i in obj) {
     if(Object.prototype.hasOwnProperty.call(obj, i)){
         // ...
     }
}

As for the name === '' thing, its just a coincidence since Javascript functions (and therefore your class) always have this property defined:

(function(){}).name     // ""
(function foo(){}).name // "foo"

Some other properties such as "prototype" or "length" should also always be defined and there is nothing you can do about them.


The console prints a list of items for the user to scroll through using the up and down arrow keys

get_input should be called handle_input. get_input suggests that it returns input values, whereas really, it's a "step" function used to handle what's going on at a slice in time.
Also in that function, self.selected += -1 is confusing. Why add a negative number instead of subtracting? I would change that and the other similar instances to self.selected -= 1. Personally, I'd also get rid of the prefix + in +1. I don't find it adds anything.

Sorry, I wrote another review before this and my brain's tired. Hopefully someone else can give better suggestions.


As long as you are 100% certain that all threads will use the same instance of MyModuleRefreshableConfig, this code should work. Just to be certain I would make the refreshConfigMutexstatic:

private static final AtomicBoolean refreshConfigMutex;

public MyModuleRefreshableConfig(IConfiguration configProvider, long refreshInterval) {
    synchronized {
         if (refreshConfigMutex == null) {
             refreshConfigMutex = new AtomicBoolean(false);
         }
    }
    ....
}


int.Parse will throw an exception if input isn't an integer. Consider using int.TryParse instead.

You should verify that the user doesn't enter a negative integer for the 2nd argument.

Your while loop should be a for loop.

A multiplication isn't much more expensive than an addition, especially compared with the performance cost of calling Console.WriteLine; so I'd use multiplication instead if that makes the code clearer:

for (int i = 1; i <= userValue_length ; ++i)
{
    Console.WriteLine("{0} x {1} = {2}", i, userValue_number, i * userValue_number);
}

userValue_number is a strange mix of camelCase and using_underscores. camelCase is more conventional in C#. I think I'd rename those to chosenNumber and chosenTimes or something like that.

The final Console.ReadLine(); is ugly and uncessary. You probably use it for debugging; instead (to inspect output from a debugger session before the console window auto-closes) put a debugger breakpoint on the final curly brace of main.

Your message E.g. 12, then {0} x 12 is ... doesn't match your output {0} x {1} = ...; instead i should be the 2nd (not 1st) number in your output.


Adding multiple rows in an HTML table using jQuery

I'd do it like this:

$('#add-row').click(function() {
  var $tbody, $row, additionalRows;
  var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);

  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('Please enter number of rows to insert');
  } else {

    $tbody = $('table tbody');
    $row = $tbody.find('tr:last');

    additionalRows = new Array(numNewRows + 1).join($row[0].outerHTML);

    $tbody.append(additionalRows);
  }
});

    Col1
    Col2

      1
      2

<input type="number" id="insert-rows-amnt" />
<button id="add-row" type="button">Add Rows</button>

Firstly, don't trust user input, verify you actually have a number, try to parse it and be explicit. Always use the radix, parseInt() can try to be too clever for its own good. The result could be NaN or a number, so check for these:

var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);

if (isNaN(numNewRows) || numNewRows <= 0) {

If you're using JQuery, cache found objects, finding them isn't free, a search is done every time you pass a string selector, so if you've already found it, use it. This ins't going to set the world on fire, but it's a good habit to get into.

Onto the meat of the method, there are two methods for inserting HTML quickly. HTML updates are like Excel Worksheet updates, no small amount of processing goes on when you change the dom. Most of the time this is negligible, but if you're inserting a huge amount of html it's something to be aware of.

You could create a document fragment and append nodes to it. This gives the benefit of working with objects rather than strings so is less error prone. The essence of it is you create the fragment in memory and insert it once.
You can create the html as a string and insert it, it's a single dom update, but more error prone as you're string building. This case is simple enough for it to be a good option though.

new Array(numNewRows + 1).join($row[0].outerHTML);

This replicates a string x number of times. It works by initialising an array of x dimensions and then joining it using a given string as the text between the elements.


Pagination implementation for a blog system

int num

What does num represent exactly? Number of pages? Number of posts per page? Current page number? Properly naming the variable would help a lot in clarity here.

var postsPerPage = 3;

Turn it into a parameter with default value 3. That way you can always decide later that the user can change this without much trouble.

Instead of using 0-based pages and then adding 1 to the presentation, I would consider using the reverse: 1-based pages and subtracting 1 when determining the pages to display. In essence this would turn your loop from i = 2, name becomes unnecessary and in your controller you use int skip = (num - 1) * postsPerPage instead.

using (UnitOfWork uwork = new UnitOfWork())
{
    IEnumerable<Post> posts = uwork.PostRepository.GetAll().ToList();

    int totalPosts = posts.Count();
    ViewBag.pages = totalPosts / postsPerPage;
    int skip = num * postsPerPage;

    return View(posts.Skip(skip).Take(postsPerPage));
}

ViewBag.pages (note the incorrect naming convention) indicates to me a collection of pages. In your case however, a more appropriate name would be AmountOfPages.

I feel like there's room for an optimization here: what if you have 100.000 pages? Or even just 100? You will load all your items each time someone visits the frontpage and you're only doing this to show the user how many pages of items there are. In fact you're not even doing that: you won't show them past 10 pages anyway!

I would argue that maybe you should just use two queries:

var totalPosts = uwork.PostRepository.GetAll().Count()

which will just perform a select count(*) from posts at the database side and another query that gives you your pages:

var pages = uwork.PostRepository.GetAll().Skip(skip).Take(postsPerPage)

Another way to keep performance in mind is to use

uwork.PostRepository.GetAll().Take(postsPerPage * 10).ToArray();

This will you give

The amount of posts (the exact amount being pages.Length)
The concrete posts (being pages.Skip(skip).Take(postsPerPage))

The benefit of this is that it will only call the database once (network latency is one of your demons) with the downside being that it retrieves more items than you're interested in.

Instead of looping to ViewBag.pages + 1 and possibly breaking out at i >= 10, I would just loop until Math.Min(ViewBag.Pages + 1, 10).


A security problem is ReleaseSession adds whatever T session passed to _available, whether it was issued by you or not.

You can change _inUse like so:

HashSet _inUse = new HashSet<T>(new ObjectReferenceEqualityComparer<T>())

where ObjectReferenceEqualityComparer is an EqualityComparer that uses Object.ReferenceEquals and check whether _inUse contains session before adding it to the _available to avoid that problem.

You may think because you intend, for now, to use this pool with class X, which you think, for now, this problem does not apply. It may turn out that this problem applies to X after all, or someone else, or even yourself, may use this pool for some other class Y.


Proxy test class approach to allow covering legacy code with unit tests

public class MyService
{
    public bool Execute()
    {
        return _newMethod() && _legacyMethod();
    }

    protected virtual bool _newMethod()
    {
        // some business logics

        return true;
    }

    protected virtual bool _legacyMethod()
    {
        // hundreds of lines of code

        return false;
    }
}

You abuse inheritance for testing purposes instead of splitting it up in two classes - one for each service. The current solution also violates the Open/Closed Principle. If you wanted to add another service or logic later you couldn't do it without modifying this god-service.

Virtual/abstract methods should have some purpose and be overriden in a concrete implementation and not used as workaround for testing.

You could improve it by either implementing the decorator pattern or using inheritance correctly. Here are two examples.

Decorator

I find the decorator pattern would be a better choice here. With a decorator you would define an interface like

interface IService
{
    bool Execute();
}

and implement it in two classes. One for the legacy service:

public class MyLegacyService : IService
{
    public bool Execute()
    {
        // hundreds of lines of code
    }
}

and one for the new service:

public class MyNewService : IService
{
    private readonly IService _service;
    public MyNewService(IService service)
    {
        _service = service;
    }

    public bool Execute()
    {
        return ExecuteInternal() && _service.Execute();
    }

    private bool ExecuteInternal()
    {
        ..
    }
}

This has the advantage that you can provide any IService to the decorator and test the new logic independently. You can easily create a test-service to fake the legacy one.

Inheritance

If you want to do it with inheritance then the new service should be derived from the legacy service that is derived from an abstract base service.

The overridable method should then be called ExecuteCore. The base service just calles the core method:

public abstract class MyService
{
    public bool Execute()
    {
        return ExecuteCore();
    }

    protected abstract bool ExecuteCore();
}

The legacy-service implements the core method:

public class MyLegacyService : MyService
{
    protected override bool ExecuteCore()
    {
        // hundreds of lines of code

        return false;
    }
}

and the new-service implements it in its own way and using its base class core method:

public class MyNewService : MyLegacyService
{
    protected override bool ExecuteCore()
    {
        // some new business logics

        return newResult && base.ExecuteCore();
    }
}

This will be a little bit harder to test as the new-service depends on the legacy one so you would need to stub it in tests. Nothing impossible but more work then with the decorator.


You could try making the questions/answers declarative and then the logic surrounding the questions/answers could then be factored out. An easy way would be to store the questions/answers in a list of tuples:

data = [("What is 5+5?", 10), ("What is 10+10?", 20) ...]


localStorage setExpire code to add time expires

I think this code could use a lot of polishing.

Getting the localStorage

 storage =localStorage.getItem('limitStorage');
 getItems = storage !== null && storage !== "[]" ? localStorage.getItem('limitStorage') : null;
 getItems = getItems !== null ? JSON.parse(getItems) : null;

can easily be replaced with:

items = JSON.parse( localStorage.getItem('limitStorage') || "[]" );

I renamed getItems to items ( getItems is a name better suited for a function ), the code also defaults items to an empty array if nothing was found.

Setting an expiry date

The easiest way to deal with that is to get now in milliseconds, add 1000 * 60 * 60 * 24 * days to it, and set that as the expiry date. Then you only have to compare (new Date()).getTime() with the expiry date.

So you have something like

var now = (new Date()).getTime();
var day = 1000 * 60 * 60 * 24;

for (var key in arrObj) {
  newItems.push( { value : key , expires : now + day * arrObj[key] } );

Now, we are facing 2 problems:

If you want to change the expiry date of an item, you cant..
Much worse, once you set some items to expire, you can never add extra items to expire since you will always fall into the else branch.

At this point, I think the whole code needs a re-write and re-think.


Range for can be used with iterators, including pointers, as follows

for (auto name: strMapListGlobal)
{
    #ifdef CHECK_STRING_3
    if (strMapEventOx == stringName)
    {
        if (0 <= rVictim.GetRace() && rVictim.GetRace() <= 7)
            return FALSE;
    }
    #endif

    if (name == stringName)
    {
        for (auto p: pListGlobal)
        {
            if (rVictim.GetRace() == p ||
                pListPet[0] <= rVictim.GetRace() &&
                rVictim.GetRace() <= pListPet[1])
                return FALSE;
        }
    }
}

Your program needs further refinement. Upon inspection, we see that the first conditional inside the loop body

if (strMapEventOx == stringName)
{
    if (0 <= rVictim.GetRace() && rVictim.GetRace() <= 7)
            return FALSE;
}

is invariant inside the loop and can be factored out.
That leaves us with the following

for (auto name: strMapListGlobal)
{
    if (name == stringName)
    {
        for (auto p: pListGlobal)
        {
            if (rVictim.GetRace() == p ||
                pListPet[0] <= rVictim.GetRace() &&
                rVictim.GetRace() <= pListPet[1])
                return FALSE;
        }
    }
}

To further refine your program, eliminate raw pointers. Not knowing what your macros do it is difficult to say but you might consider.

auto pets = std::vector<int> { 34001, 34051 };

auto globalPets = {
    9001, 9002, 9003, 9004,
    9005, 9006, 20011,
    20091, 20092, 20093,
    20094, 20095, 30000
};

auto globalEventNames = { "string1" , "string2" };

auto eventOx = "string3";

auto mapName = CPythonBackground::Instance().GetWarpMapName();

#ifdef CHECK_STRING_3
if (eventOx == mapName)
{
    if (0 <= rVictim.GetRace() && rVictim.GetRace() <= 7)
        return FALSE;
}
#endif

for (auto event: globalEventNames)
{
    if (event == mapName)
    {
        for (auto pet: globalPets)
        {
            if (rVictim.GetRace() == pet || pets[0] <= rVictim.GetRace() && rVictim.GetRace() <= pets[1])
                return FALSE;
        }
    }
}

as for strcmp

if (strcmp(strMapEventOx, stringName))

avoid it!

if (strMapEventOx == stringName)

is more readable, more idiomatic, and likely faster.


LINQ statements that aggregate sums from a List of objects

To combine the two queries into one, you can use select … into:

chartData.DataRows = (from h in hours
                      orderby h.Year, h.WeekOfYear, h.LocationName, h.ProgramName
                      group h by new { h.Year, h.WeekOfYear, h.LocationName, h.ProgramName }
                      into programLocationGroups
                      select new
                      {
                          Location = programLocationGroups.Key.LocationName,
                          Program = programLocationGroups.Key.ProgramName,
                          Hours = programLocationGroups.Sum(p => p.Hours)
                      }
                      into d
                      group d by new { d.Program, d.Location } into programLocationSums
                      select new FindAllAnalyticsResponse.DataRow
                      {
                          Location = programLocationSums.Key.Location,
                          Program = programLocationSums.Key.Program,
                          Data = programLocationSums.Select(p => p.Hours).ToList()
                      }).ToList();

Though I'm not sure this is actually an improvement.

I think an equivalent and simpler query would be to first group only by location and program and then by week in a nested query:

chartData.DataRows = (from h in hours
                      orderby h.LocationName, h.ProgramName
                      group h by new { h.LocationName, h.ProgramName } into programLocationGroup
                      select new FindAllAnalyticsResponse.DataRow
                      {
                          Location = programLocationGroup.Key.LocationName,
                          Program = programLocationGroup.Key.ProgramName,
                          Data = (from pl in programLocationGroup
                                  orderby pl.Year, pl.WeekOfYear
                                  group pl by new { pl.Year, pl.WeekOfYear } into weekGroup
                                  select weekGroup.Sum(w => w.Hours)).ToList()
                      }).ToList();

Note that the above code may need some better in the variables I introduced.


//Let's wrap this module in a closure so we can have a private scope for our
 //module. That way, we don't expose too many globals as well as place too
 //many things in our namespace
;
(function (exports) {

  //Let's pull out these guys since they are static, and we don't want them
  //get recreated everytime a parse is required.
  var urlRegex = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
  var hashTagRegex = /#([^ ]+)/gi;

  //I suggest you use a templating system. In this example, I am using
  //Mustache. As you can see, it's easily readable, where you have an
  //array of tweets, each printing the contained section.
  var feedTemplate = '
{{#tweets}}

{{user.name}}
{{parsedHTML}}{{/tweets}}
';

  //Now our parser doesn't need to be an object. It could only be a function
  //that returns parsed data. Also, unless parse is required to be public, it
  //should remain inside the scope that requires it. That way, we don't
  //expose too much to our namespace.

  function parse(html) {
    return html.replace(urlRegex, '$1')
               .replace(hashTagRegex,'#$1');
  }

  //We move out this function to separate it from the AJAX call. That way,
  //it's not jumbled up with the AJAX code.

  function format(data, config) {

    //We have an array of twets that we will use later with the templating.
    var tweets = [];

    $.each(data, function (i, tweet) {
      //Now, for each tweet retrieved, we parse the text, and reattach it to
      //the tweet object as parsedHTML, which will be used in the template.
      tweet.parsedHTML = parse(tweet.text);

      //We then collect the tweets into the array defined earlier.
      tweets.push(tweet);

      //We needed that array, so that we won't feed the original array into
      //the template. So here's the break when the limit is reached.
      if(i === config.limit) return false;
    });

    //Now, with the template, and our tweet array, we render. The return is
    //an HTML string, which we can then use jQuery to build the elements.
    var html = Mustache.render(feedTemplate, {
      tweets: tweets
    });

    $(data.id).html(html);
  }

  //We expose our twitterFeed function to our namespace
  exports.twitterFeed = function (config) {
    $.ajax({
      url: 'http://example.com/api/twitter/timeline/name/' + data.name,
      dataType: 'json',
      crossDomain: true,
      cache: false,
      success: function (data) {
        format(data, config);
      }
    });
  }

}(this.TwitterTimeline = this.TwitterTimeline || {}));

Minus the comments, this is how it looks:

;(function (exports) {
  var urlRegex = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
  var hashTagRegex = /#([^ ]+)/gi;
  var feedTemplate = '
{{#tweets}}

{{user.name}}
{{parsedHTML}}{{/tweets}}
';

  function parse(html) {
    return html.replace(urlRegex, '$1')
               .replace(hashTagRegex,'#$1')
  }

  function format(data, config) {
    var tweets = [];
    $.each(data, function (i, tweet) {
      tweet.parsedHTML = parse(tweet.text);
      tweets.push(tweet);
      if(i === config.limit) return false
    });
    var html = Mustache.render(feedTemplate, {
      tweets: tweets
    });
    $(data.id).html(html)
  }

  exports.twitterFeed = function (config) {
    $.ajax({
      url: 'http://example.com/api/twitter/timeline/name/' + data.name,
      dataType: 'json',
      crossDomain: true,
      cache: false,
      success: function (data) {
        format(data, config)
      }
    })
  }

}(this.TwitterTimeline = this.TwitterTimeline || {}));


Determine if simple arithmetic expression is valid

It is not always an easy task to solve this sort of problem. For data structures, we traditionally use a stack for open and close parenthesis but this is only needed if the type of parenthesis can differ and need nesting correctly. For only "(" and ")" I simmply use an int.

I re-wrote the isAnOperator to a switch statement - its personal choice that one.

I added a isANumber function to aid some checking.

I unit tested the function with 9 tests and worked till it past them all. (JUnitParams, read it as the string is the expression and the boolean is what I expect your function to return)

Your original code fails 3 of these tests - but it may because of not handling spaces in the expressions but you didn't provide any example data

To handle parenthesis I used a counter - but decrement it if I find a close. If I get into a negative number then something went wrong and if it isn't 0 at the end it was wrong. You can work out from the final value if there were too many close or opens. Simple boolean values keep track of wether the last character was an operation or a open parenthesis.

I welcome feedback on this answer - I'm trying to keep it as close to the original code as possible

$(
            $("()", true),
            $("3", true),
            $("3 + 2", true),
            $("(3 + (2))", true),
            $(")", false),
            $("+3", false),
            $("3+-2", false),
            $("(3 + (3 + 2)", false),
            $("(x + 3)", false)
    );

I've re-written the function to be cleaner with less variables:

public static boolean isAnOperator(char c) {
    switch (c) {
        case '*':
        case '/':
        case '+':
        case '-':
        case '%':
            return true;
        default:
            return false;
    }
}
public static boolean isANumber(char c){
    return ((int)c) >= 48 && ((int)c) <= 57;
}

public static boolean isValidExpression2(String expression) {
    // TEST 1
    if (isAnOperator(expression.charAt(0)) || isAnOperator(expression.charAt(expression.length() - 1))) {
        return false;
    }

    int openParenthCount = 0;
    boolean lastWasOp = false;
    boolean lastWasOpen = false;

    for (char c : expression.toCharArray()) {
        if(c == ' ') continue;
        if (c == '(') {
            openParenthCount++;
            lastWasOpen = true;
            continue;
        } else if (c == ')') {
            if (openParenthCount <= 0 || lastWasOp) {
                return false;
            }
            openParenthCount--;
        }else if (isAnOperator(c)){
            if (lastWasOp || lastWasOpen) return false;
            lastWasOp = true;
            continue;
        }else if(!isANumber(c)){
            return false;
        }
        lastWasOp = false;
        lastWasOpen = false;
    }
    if(openParenthCount != 0) return false;
    if(lastWasOp || lastWasOpen) return false;
    return true;
}


Option functional type implementation and scenarios

I'm not a fan of your usage example. The line .Place(null) looks really fishy to me. It looks like something, that should not happen in my imaginary web store, like some kind of error, which I probably want to catch and debug. However Optional<T> class hides this potentioal error completely and my application keeps working as if nothing has happened. Now, if null is for some reason a valid value, then I guess its fine.

Overall, Optinal<T> class looks OK to me, even though I am having troubles coming up with a sceanrio, where I would find it useful. You could probably group public methods together though, it makes class easier to read.

Also I think you are overusing => operator. To the point where method's body becomes really hard to read. => is fine when your function is a short one-liner (i.e. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();). But you should probably use braces, when it is not (i.e your Place method).


Checking if all the characters from an A-Z is present in the string

private static byte N;

We know that N<=100, but this is a very premature optimization. In theory, you're saving 3 bytes total. Actually, it'll get rounded up to a nearest multiple of 8 or whatever and you save nothing at all.
It's also no good idea top make everything static.
BufferedReader keyboard = new BufferedReader(new InputStreamReader(
            System.in));

But the input does not come from the keyboard. Or can you type 100 lines in two seconds? I'd call it in as I'm lazy, something like reader would be fine.
isCompleteString(testingString);

According to the name, isCompleteString returns boolean. And there should be a method doing just this. Coupling output with computation makes you method 100% non-reusable.
First version
    String resultString= "";

Switch on your warning to see unused variables.
    char[] toChar = testingString.toCharArray();
    int length = toChar.length;
    for (int i = 0; i < length; i++) {

This looks like a premature optimization. And toChar is a bad name as there's no char but char[]. The IDE proposes charArrays or chars, which is both better.
If you want to use a char[], then use simply
   for (char c : chars)

This is clearly non-optimal
        if(resultString.indexOf(toChar[i])==-1){
            resultString=resultString.concat(toChar[i]+"");
        }

for many reasons

indexOf - you're running through the string for each char
toChar[i]+"" creates a String from each char needlessly
resultString.concat(...) creates a new String every time

You could use a StringBuilder here.
But creating a String only to measure it's length is plain wrong. You could count the chars instead.
But counting the chars is plain wrong too. If you want to know if a beer crate is full, do you count the bottles? Or do you if there's a bottle missing?

    if(resultString.length()==26)System.out.println("YES");
    else System.out.println("NO");

This should be written as
   System.out.println(resultString.length()==26 ? "YES" : "NO");

apart from that 1. there should be no resultString, 2. there should be a method computing and a method printing.
Second version
    boolean[] findingAlphabet = new boolean[26];

No good name. What about foundChars or simply found?
        byte alphabets = (byte) toChar[i];

What byte? Never use a byte, unless either it's exactly what's needed or you have a big bunch of them.
        findingAlphabet[122-alphabets]=true;

Nice obfuscation. What about
       found[chars[i] - 'a'] = true;

? And bottle counting again
    int count=0;
    for(boolean b:findingAlphabet){
        if(b)
        count++;
    }

This should be
    for (boolean b : found) {
        if (!b) {
            return false;
        }
    }
    return true;

How can I optimaize these programs further (I have used BitSet)?

You haven't. But BitSet is slower than a boolean[] (except when memory locality comes in play).
It looks like most of the time gets spend on IO. Not surprising, even the first solution with doing 26 times indexOf on a 100 chars string is not computationally intensive.
It could be sped up by avoiding strings and working with the input bytes directly. But I'd concentrate on readability first, otherwise it'll become a huge mess.
You may want to specify input encoding as US-ASCII as it's sufficient and much faster than UTF-8 which may be your platform default.


Batch rename files with Mac Bash,while the dir index should be recorded

Limit globbing to directories only by appending a slash:  for dir in */

If you cd into subdirectories, you don't need to construct a new path for each file.  If you cd inside a subshell with ( cd … ), the original directory will be restored when subshell exits.  Make sure to increment n outside of the subshell, or the new value will be lost!

The IFS= is not needed; bash will split the filenames properly.  You just need to quote the variable when you refer to it.

n=0
for d in */ ; do
    ( cd "$d" && for f in * ; do mv  "$f" $n"_$f" ; done )
    (( n++ ))
done


About point (1)
If it's obviously copied from somewhere without changing anything then it's perfectly fine to not change anything to the code itself. Given that you also have the link to the (pseudo-)code. In this case I wouldn't even add comments other than: look at this page to know how it works.

If however you want to integrate it better into your own code to treat it like it's actually part of it then there's no reason to keep the code as close to the original as possible.
Instead you should refactor it until it fits the general java standards. Meaning making variables private, making constants final (static), following naming conventions (both for variables and methods), ...

question (2)
(see above if you want to stick to the structure from the source without changing anything. If you start refactoring following coding standards read on)

If like you say there are a number of variables and methods that are forming a coherent group then you should put them into their own class.

For your new class you'll have to find out what to put in the class and what methods to provide.

My first thought is something like this:

public class LissajousPointCalculator{
    private static final int HORIZONTAL_FACTOR = 300;
    private static final int VERTICAL_FACTOR = 300;
    private float xTimeScale;
    private float yTimeScale;
    private float xTimeOffset;

    public LissajousPointCalculator(float xTimeScale, yTimeScale, xTimeOffset){
        this.xTimeScale = xTimeScale;
        this.yTimeScale = yTimeScale;
        this.xTimeOffset = xTimeOffset;
    }

    public Point getPointAt(float time) {
        int x = (int) ( HORIZONTAL_FACTOR  * Math.sin(xTimeScale*time + xTimeOffset) );
        int y = (int) ( VERTICAL_FACTOR  * Math.sin(yTimeScale*time) );

        return new Point(x + HORIZONTAL_FACTOR , y + VERTICAL_FACTOR );
    }
}

Note that I did not include any timetracking inside this class. My reasoning is that the other class that uses this one is responsible for deciding which points to draw. So that class is responsible for staring over, deciding the step size, deciding how many points to add before drawing it on the screen etc...

I also made the horizontal and vertical scaling factors constant inside the class. This was just as an example. If you want to be able to change the size of the figure as well it's obvious that you want these as variables that you can pass through constructor or setters instead.


Overall, it looks pretty good. Here are some points to consider:

There is no need to explicitly return at the end of void methods, for example, at the end of displayAll().

Keep your variable declarations close to where they are used. For example, in insertNumber(), I would change this...

String stringName = "";
String stringNumber = "";
System.out.println("Enter name: ");
stringName = input.nextLine();
System.out.println("Enter number: ");
stringNumber = input.nextLine();

...to this...

System.out.println("Enter name: ");
String stringName = input.nextLine();
System.out.println("Enter number: ");
String stringNumber = input.nextLine();

Also, limit the scope of variables to the block where they are used. This follows from the point above. For example, in main(), stringCommand is declared near the top, but is only used inside the do/while block. I would remove the declaration above and change this line...

stringCommand = input.nextLine();

...to this...

String stringCommand = input.nextLine();

These will reduce the number of lines slightly, but will also make reading and debugging the code easier.

As a slighter bigger project, you could change the methods to be non-static, then create an instance of MongodbPhonebook in main() to interact with instead. It may also make sense to move some of the code from main() somewhere else. For example, you could make the mongo variables private members of MongodbPhonebook and initialize them in the constructor.

public class MongodbPhonebook {

    private MongoClient mongoClient;
    private DB db;
    private DBCollection coll;

    public MongodbPhonebook() {
        this.mongoClient = new MongoClient();
        this.db = mongoClient.getDB( "myphonelist" );
        this.coll = db.getCollection("myphonelist");
    }

    ...

}

If you did this, you would no longer need to pass the DBCollection around to the other functions.

Beyond that, consider separating the user interaction and database logic into separate functions. For example, split findNumber() into two functions: one to ask the user for input and display the results, the other to perform the search based on the supplied input. This would allow the database logic functions to be reused in different circumstances, for example, a web application.


An alternative approach is:

require (teamSizes.min == teamSizes.max)

but ỳour forall-solution expresses better the idea, that all members share the same size.

And without measuring it, or trying to investigate my assumption, I guess that my approach traverses the collection twice, which could be a drawback for bigger collections or if performed million of times. So less so in this example.

But maybe it is possible to model the constraint into your design, so that all teams get the right size from the beginning?


It is a good idea to use consistent styles throughout your code.  Right here, you use braces around a 1-line if/else block:

if (m_PropertyBag.ContainsKey(name)) { m_PropertyBag[name] = value; }
else { m_PropertyBag.Add(name, value); }

Right here, you do not:

if (GetType() != min.GetType() || GetType() != max.GetType())
        throw new InvalidOperationException("Not the same type.");

I recently switched to always using braces, but whatever you decide, be consistent.

I don't think you need all those assignments to result when you are just going to return if the value is false:

var result = true;
foreach (var property in m_PropertyBag)
{
    if (property.Value is IEnumerable)
    {
        var values = (IEnumerable)property.Value;
        var minValuesEnum = ((IEnumerable)min.m_PropertyBag[property.Key]).GetEnumerator();
        var maxValuesEnum = ((IEnumerable)max.m_PropertyBag[property.Key]).GetEnumerator();

        foreach (var value in values)
        {
            result &= minValuesEnum.MoveNext();
            result &= maxValuesEnum.MoveNext();
            if (!result) return false;

            result &= Compare(value, minValuesEnum.Current, maxValuesEnum.Current);
            if (!result) return false;
        }
    }
    else
    {
        result &= Compare(property.Value, min.m_PropertyBag[property.Key], max.m_PropertyBag[property.Key]);
        if (!result) return false;
    }
}
return result;

You can do this instead:

foreach (var property in m_PropertyBag)
{
    if (property.Value is IEnumerable)
    {
        var values = (IEnumerable)property.Value;
        var minValuesEnum = ((IEnumerable)min.m_PropertyBag[property.Key]).GetEnumerator();
        var maxValuesEnum = ((IEnumerable)max.m_PropertyBag[property.Key]).GetEnumerator();

        foreach (var value in values)
        {
            if (!minValuesEnum.MoveNext() ||
                !maxValuesEnum.MoveNext() ||
                !Compare(value, minValuesEnum.Current, maxValuesEnum.Current);
            {
                return false;
            }
        }
    }
    else if (!Compare(property.Value, min.m_PropertyBag[property.Key], max.m_PropertyBag[property.Key]))
    {
        return false;
    }
}
return true;

I'm not sure what is going to, or should, happen if neither the if nor the else if statements execute.  Should there be an else { return false; } statement in there?


Deserialize, Copy and Merge Orders from XML to C#

Naming
var orders = new List<XElement>();
var _orders = new List<Order>();

First, according to the C# naming convention, you should never have underscores in your variable names declared inside methods. Second, this is pretty confusing.
How about :
var xmlOrders = new List<XElement>();
var convertedOrders = new List<Order>();

It's a weird (and probably controversial) thing to say, but naming has to be one of the hardest thing to do when it comes to programming. You want your name to be so clear that anyone reading your code would be able to understand it quickly. So names need to be clear and exact.
For example : secondOrder isn't a second order, so it's confusing.
What is it, how should it be named? Well it seems like this order is an alreadyAddedOrder. You might want to find another name, but it should give the same "vibe".
C# things

You can use the object initializer :
var orderTemp = new Order();
orderTemp.OrderDate = Convert.ToInt32(order.Attribute("date").ToString());
orderTemp.Id = Convert.ToInt32(order.Attribute("id").ToString());
orderTemp.CategoryId = Convert.ToInt32(order.Attribute("categoryId").ToString());
orderTemp.ProductCount = Convert.ToInt32(order.Attribute("productCount").ToString());

becomes :
var orderTemp = new Order
{
    OrderDate = Convert.ToInt32(order.Attribute("date").ToString()),
    Convert.ToInt32(order.Attribute("id").ToString()),
    //etc..
};

It's simply shorter and clearer, but it is compiled the same way as your previous code.

Note : Order ID is not unique, date + id + category, is unique altogether

We've got a great case of override Equals.
As it is right now, the responsibility of deciding if two orders are equal is stored (as code) in your Load method. Is this fine? I don't think so!
An Order should be able to tell if it's equal to another Order`.
public class Order
{
    public int Id;
    public int CategoryId;
    public int OrderDate;
    public int ProductCount;

    public override Equals(object obj)
    {
       //etc.
    }
}

I recommend you read a little bit on how to correctly implement the Equals override as you'll also need to override the GetHashCode method.

Don't use Convert.ToInt32 when you have a string that should be an int. Use int.Parse. reference

Also, override ToString to replace orderTemp.OrderDate.ToString() + orderTemp.Id.ToString() + orderTemp.CategoryId.ToString().

Encapsulation
public class Order
{
    public int Id;
    public int CategoryId;
    public int OrderDate;
    public int ProductCount;
}

Now, you might not feel it's necessary to implement this as it's a pretty "defensive programming" thing, but I feel it's important to talk about it. If I look at this class from a business point of view, it means that if I pass an order, I should be able to modify the said order afterwards. But when an order is passed, should I be able to modify, say, the OrderDate? Not really. There's also an important point that once you override the GetHashCode method, you should consider making your object "read only", so that it doesn't mess with the hashes.
Order becomes :
public class Order
{
    public Order(int id, int categoryId, int orderDate, int productCount)
    {
        //etc.
    }

    public int Id { get; }
    public int CategoryId { get; }
    public int OrderDate { get; }
    public int ProductCount { get; }

    //Equals and GetHashCode override.
}

General points

Don't use _alreadyAddedOrders to keep string. You're looking for orders, this list should contain orders.

Why is OrderDate an int? If it's stored as milliseconds, it should be a long, otherwise I don't see how you can parse an int to a meaningful date.


public double Price { get; set; } clearly should be of type Decimal. That is what Decimal for.
private static List<CartItem> CartItems = null; can be safely refactored to Dictionary<int, CartItem> with ProductId used as keys. Then CheckItemExistThenAddToCart can be refactored using Dictionary.ContainsKey method, and GetCartItems can return dictionary itself, CartItems.Values or CartItems.Values.ToList(). I think the latter option is the best, since it will copy the collection, which will restrict access to CartItems property. As of now, someone might modify it in outer code, which will result it modifying ShoppingCart state. Returning a copy will prevent that.
return (CartItems as IEnumerable).GetEnumerator(); cast can be removed.
I'm not sure i like the idea of having two methods to add items to the cart, which have different logic. It's pretty error-prone. Is it really necessary? I think you should probably stick to one.
I think your shopping cart interface misses Remove method.

Your unit tests look fine to me (except you should move them to different file), tho i'm not too experienced with them.


If I take newHeaderHeight = HeaderViewHeightConstraint.Constant - offsetDifference and expand offsetDifference I get: newHeaderHeight = HeaderViewHeightConstraint.Constant - (offset - _previousOffset) which is newHeaderHeight = HeaderViewHeightConstraint.Constant - offset + _previousOffset

If I then go to the else statement and expand newHeaderHeight = (HeaderViewHeightConstraint.Constant + offsetDifference); I get newHeaderHeight = HeaderViewHeightConstraint.Constant + (_previousOffset - offset); which is newHeaderHeight = HeaderViewHeightConstraint.Constant + _previousOffset - offset;

They're the same thing. So you can basically remove them from the if/else statement and only write them once.

The second part is a bit more tricky to refactor because you compare it with min values in one condition and max values in the other. It would however still refactor each ternary operator statement with Math.Min() or Math.Max() (careful not to get them the other way round).


Some notes:

add definition of the undeclared variables BytetoWrite, OriginalByte and how they are used/initialized
format your code for better readability. Left indentation is not aligned. Too many void blank lines
using

resource := CreateResource;
try
    // do something
finally
    FreeAndNil(resource);
end

pattern is easy to follow and it prevents unintended memory leaks nicely
for byte-to-byte memory compare in CompareByteArrays better use built-in CompareMem function instead of custom array traversal. In an old language runtime source codes this function was implemented in optimized assembly language
using Integer for file-offset is not very future-friendly idea considering that it is normal (for average end-user) today to work with video files in 4K resolution where single file size can be >4GB
using Memory Mapped Files for read-only file access will give you simpler code (whole file is an in-memory array) and faster I/O operations (on-demand reading managed by OS kernel code). This method can give you significant boost if the original file is big and the searched-pattern is located near the beginning of the file
the loop should end at High(FileByteArray) - Length(OriginalByte) (+/-1) as beyond this boundary the pattern can not be found anyway
you can get some speed by comparing against the original byte array just offset by the i index. Creation of the intermediate ExtractedByteArray would not be necessary (throw away, safe some memory allocation and memory copy CPU-clocks). Like this:

if CompareByteArrays(ExtractedByteArray, OriginalByte) = True then

if CompareMem(@FileByteArray[i], @OriginalByte[0], Length(OriginalByte)) = True then

assuming the i...i + Length(OriginalByte) - 1 boundaries are withing the range Low(FileByteArray)...High(FileByteArray) as mentioned in (7)