Single consumer and single producer lock-free circular buffer

A few notes, mostly unrelated to the actual lock-free nature of the code:

Some of your names are a lot less meaningful than I'd like. A prime example is your template parameter S in: template<typename T, int S=5>. This should probably be renamed to something like Size instead. Although not quite as problematic, I'd say your dis and gen have pretty much the same problem as well. (Note that although T as the type parameter is just as short, it's so common I'd accept it, much like I'd accept i as the index for a loop).
Although some people avoid them, I'd at least consider using something like size_t for the types of CircularBuffer::begin and CircularBuffer::end. It appears that neither should ever be negative.
You might want to consider using std::atomic_int (or std::atomic_uint) instead of std::atomic<int>. It's unlikely to make much difference, but does give the library design a little extra chance for optimization (i.e., atomic_int might just be a typedef for atomic<int>, but could be a separate type instead, if the library designer sees an advantage in doing so).
It may just be a side-effect of some strange tab expansion (or something similar) but at least as posted, your indentation is pretty strange in a few places. For one obvious example:

  if(start_idx==buffer.size())
start.store(0);
  else
start.store(start_idx);

I'd have to do some looking to be absolutely certain, but I believe your use of a global for the random number generator causes a data race that leads to undefined behavior. Specifically, a pseudo-random number generator has an internal state that's modified when you obtain a random number from it. Doing that modification simultaneously from two or more threads gives undefined behavior.
This sequence:

  start_idx++;
  if(start_idx==buffer.size())
start.store(0);
  else
start.store(start_idx);

Looks to me like it's subject to race conditions. For example, let's assume start_idx starts out equal to buffer_size-1, then we execute the code above from two threads:

thread A: start_idx++;
thread B: start_idx++;

thread A: if (start_idx == buffer.size())
thread B: if (start_idx == buffer.size())

Both if statements return false--start_idx is now one greater than buffer.size(). We then store start_idx into start.

The next time the function is called, it attempts to use:

auto ret_obj=std::move(buffer[start_idx]);

...and start_idx indexes past the end of buffer, giving undefined behavior.

Limiting to single-producer, single-consumer may be enough to prevent this problem from manifesting, but 1) I find that an essentially useless model, and 2) I'm not at all sure it's sufficient even then.

Although it may sound defeatist, let me give one little bit of advice: when you first do multithreaded programming, you're a lot better off sticking to using locks, mutexes, and so on. Getting just that much right will keep you busy for quite a while.

(Only) once you've gotten to the point that it's easy to handle that, then start to move on to working at lock-free programming (but be aware that it's an area where even the very best, brightest and most experienced still get things wrong quite frequently.


Designing a listener method and making it Testable

I think it's possible to test this method with another threads and some helper code which passes fix requests to your server and checks the server's answer. It definitely requires some work and I'm not sure how should we call this test: unit test, module test or integration test? Anyway, make sure that the checks happens on the the test method's thread, otherwise JUnit won't detect the uncatched exceptions.

To make it more testable I'd separate the ClientManager creation to an IncomingConnectionHandler interface and implementation and pass an instance of this object to the class of the listen method.

public interface IncomingConnectionHandler {
    void handle(Socket socket);
}

public final class IncomingConnectionHandlerImpl {

    public IncomingConnectionHandlerImpl {
    }

    public void handle(final Socket socket) {
            final ClientManager client = new ClientManager(clientSocket);
            client.start();
    }
}

public class MySocketListener {

    private final IncomingConnectionHandler incomingConnectionHandler;

    public MySocketListener(final IncomingConnectionHandler incomingConnectionHandler) {
        this.incomingConnectionHandler = checkNotNull(incomingConnectionHandler,
            "incomingConnectionHandler cannot be null");
    }

    public void listen() {
        try {
            serverSocket = new ServerSocket(portNo);
            while (true) {
                final Socket clientSocket = serverSocket.accept();
                incomingConnectionHandler.handle(clientSocket);
            }
        } catch (Exception e) {
            //handle any exceptions
        } finally {
            close(); //close any open sockets
        }
    }

After this in the unit test you could do the following:

create a MySocketListener instance with a mocked IncomingConnectionHandler,
start an new thread which connects to the port of MySocketListener,
check that the handle method of the mocked IncomingConnectionHandler was called with a live/proper Socket instance,
shutdown the helper thread and the MySocketListener.

Consider not using using abbreviation like Mgr. It would make the code readable.


Object assign via ... operator
There is a sorter way to do the property order if you use the spread operator to assign properties.
function propOrderFirst(key,objects){
     for(var i = 0; i < objects.length; i++){
          objects[i] = {[key] : null, ...objects[i]};
     }
     return objects;
}

The problem is
const objs = [{name: 'name1', phone: 'phone1', email: 'email1'},
        {name: 'name1', phone: 'phone1', email: 'email2'},
        {name: 'name1', phone: 'phone1', email: 'email3'}];

const obj1 = obj[0];

objs = propOrderFirst("email",objs);

if(obj1 !== objs[0]) { // true as you have created a new instance

Reorder in place
But you do lose the object reference that may not be the best option. You can reorder the object properties and still keep the object reference by using delete to remove properties.
A little more complex as you need to delete all the properties you want to move the new property position in-front of
function propOrderFirst(key, objects){
    const keys = Object.keys(objects[0]);  // assuming all objects have same properties
                                           // If not move this inside loop
    for (const object of objects) {
        const temp = {...object};     // get a copy of object
        for (const k of keys) { delete object[k] };  // remove all properties
        object[key] = temp[key];      // add the key you want first
        Object.assign(object, temp);  // assign the objects properties back
    }
    return objects;
 }

So now
const objs = [{name: 'name1', phone: 'phone1', email: 'email1'},
        {name: 'name1', phone: 'phone1', email: 'email2'},
        {name: 'name1', phone: 'phone1', email: 'email3'}];

const obj1 = obj[0];

objs = propOrderFirst("email",objs);

if(obj1 === objs[0]) { // true as you have reordered in place }


I think this will work fine and it's very close to how I would write it myself.

A few small things come to mind:

There's no documentation of any kind that explains what the semantics are, and they're not explicit either (the return None if the lock isn't acquired is entirely implicit). I would put the short explanation you put in this question into a docstring, and/or add an explicit else: return None to the if statement.
is there any reason why the lock object is exposed to the outside world by making it a property of the function (fn.lock) ? I would simply make it a local variable, so that it's hidden. But I'm not sure.


Some comments:

Rspec expects the concatenation of feature and `scenario to form a human readable text.
AFAIK, the orthodoox structure for specs is to perform the actions in the before block and only assertions in it blocks.
Use before blocks to keep your code DRY.
Personal opinion: in a feature spec, the less app internals you use, the better. So I'd write "/" instead of root_path.
The user/password info a in the factory, I'd prefer explicit attributes on the creation.

That's how I'd write the Login feature, the same ideas apply for Signup:

feature 'Login' do
  before do
    FactoryGirl.create(:user, :email => "test@example.com", :password => "password")
    visit root_path
    click_link 'Login'
  end

  scenario "with valid user/password", js: true do
    before do
      fill_in 'email', :with => 'test@example.com'
      fill_in 'password', :with => 'password'
      click_button 'Login'
    end

    it "shows the logged in message" do
      expect(page).to have_content('Logged in successfully')
    end
  end

  scenario "with wrong user/password", js: true do
    before do
      fill_in 'email', :with => 'failed@login.com'
      fill_in 'password', :with => 'something failed'
      click_button 'Login'
    end

    it "shows an error message" do
      expect(page).to have_content('Invalid login/password combination')
    end
  end
end


Extension methods to make ConcurrentDictionary GetOrAdd and AddOrUpdate thread safe when using valueFactory delegates

Allowing the caller to provide the type argument U implies that they are allowed to use a subclass of Lazy<V>, but this will not work as your implementations always creates a new List<V> and cast it to U. Since this means U must always be a Lazy<V> then why not do away with the extra type argument.

public static V GetOrAdd<T, V>(this ConcurrentDictionary<T, Lazy<V>> dictionary, T key, Func<T, V> valueFactory)

The name of the new extension methods conflict with the names of the existing methods. For the consumer to use yours instead of the existing methods, they would need to either access via your static class or use explicit type arguments. This could lead to subtle bugs when consumers try to use it as a extension method with type inference.

ExtensionHost.GetOrAdd(safeStore, 7, (i) => i.ToString());             // uses yours
safeStore.GetOrAdd<int, Lazy<string>, string>(6, (i) => i.ToString()); // uses yours
safeStore.GetOrAdd(5, (i) => i.ToString());                            // uses existing


Starting with summation,

let summation func low high =
    let function_result_set: int list = [for x in low..high do yield x |> func]
    let result = function_result_set |> List.sum
    result

First of all, we can remove result

let summation func low high =
    let function_result_set: int list = [for x in low..high do yield x |> func]
    function_result_set |> List.sum

Next, we don't need to construct a list containing func(low) .. func(high); we can instead operate over a sequence, meaning we don't have to have all those values in memory at once.

let summation func low high =
    let function_result_set = Seq.map func { low .. high }
    function_result_set |> Seq.sum

Now we can make it a bit more succinct

let summation func low high =
    Seq.map func { low .. high } |> Seq.sum

Finally, we can make it more generic by using statically resolved type parameters. At the moment, if we have a call to summation like this:

printfn "%d" <| summation id 1 10

then summation will be constrained to be of type (int -> int) -> int -> int -> int. We can fix this by making the function inline:

let inline summation func low high =
    Seq.map func { low .. high } |> Seq.sum

Now  summation has type ('a -> 'b) -> 'a -> 'a -> 'b and the following code will compile:

printfn "%d" <| summation id 1 10
printfn "%f" <| summation id 1.0 10.0

Similar comments hold for product, but with two additional things:

To make it generic we need to get the One property of the type ^a, and
I've used the checked version of * to check for overflow

let inline product func low high : ^a =
    Seq.map func { low .. high } |> Seq.fold Checked.(*) LanguagePrimitives.GenericOne< ^a >


Python's str has justifying functions. The relevant one here would be rjust(). So we could just use that directly:

def hash_print(number):
    for i in range(number):
        hashes = '#' * (i+1)
        print hashes.rjust(number)

This is also \$O(n^2)\$ to build up hashes over time, so on the off chance that performance becomes a consideration, we could build it up as we go:

def hash_print(number):
    hashes = [' '] * number
    for i in range(number):
        hashes[number - i - 1] = '#'
        print ''.join(hashes)


Employee name auto-complete on card scan

positionInitCaseNom1enY and positionCaseNomEnX should be declared as Const or in an Enum because they are default values that never change.
Const positionInitCaseNom1enY As Long = 5
Const positionCaseNomEnX As Long = 3

Do to implicit conversion no does not need to be cast to a String.  The compiler automatically does it for you.
Dim nos As String
nos = CStr(no)     ' no to string (now nos)

Use dynamic ranges whenever possible.
Set valeurnorm = Sheets("Liste Employé").Range("A2:A200").Find(nos)

Assuming the name list is the only thing in column A, you should dynamically size you range to fit the data like this:

With Sheets("Liste Employé")
    Set valeurnorm = .Range("A2", .Cells(.Rows.Count, "A").End(xlUp)).Find(nos)
End With

Using Dynamic Named Ranges helps to give your code identity.  And that is what we want to do as developers.  If you have to comeback a year from now, you may not know what StandarValues represent but you will immediately understand what EmployeeNames are.

Set employeeNames= Sheets("Liste Employé").Range("EmployeeNames").Find(nos)

Alerts are necessary but having to click a MsgBox() can get irritating.  I would prefer that:

If .Find("Another Solution") is Not Nothing Then Call
Use(.Find("Another Solution"))

Solution 1: Use Conditional Formatting
How To Highlight Cells If Not In Another Column In Excel?
Solution 2: Use an ActiveX Combobox
Setup
• Insert a hidden ComboBox on each Worksheet that needs the name validation
• Give it a meaning full name
• Set it's ListFillRange a Dynamic Named Range of employee names

When a cell in the validation range is selected use the Workbook_SheetSelectionChange()
• Move the ComboBox over the Activecell
• REsize the ComboBox to fit the ActiveCell
• Set the ComboBox.LinkedCell = ActiveCell
• Set focus to the ComboBox
When the user selects a cell in the
• Hide the ComboBox
• Set the ComboBox.LinkedCell = Nothing

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    AdjustEmployeeNameComboBox Sh, Target
End Sub

Private Sub AdjustEmployeeNameComboBox(ByVal Sh As Object, ByVal Target As Range)
    Dim hasEmployeeRange As Boolean
    On Error Resume Next

    Dim EmployeeNameComboBox As OLEObject
    Set EmployeeNameComboBox = Sh.OLEObjects("EmployeeNameComboBox")
    hasEmployeeRange = Err.Number = 0
    On Error GoTo 0

    If Not hasEmployeeRange Then Exit Sub

    Dim isEmployeeRangeSelected As Boolean
    isEmployeeRangeSelected = Not Intersect(Target, Sh.Range("C5:C8")) Is Nothing

    With EmployeeNameComboBox
        .LinkedCell = ""
        .Visible = isEmployeeRangeSelected
    End With

    If Target.Cells.Count > 1 Then Exit Sub

    If isEmployeeRangeSelected Then
        With EmployeeNameComboBox
            .LinkedCell = Target.Address
            .Top = Target.Top
            .Left = Target.Left
            .Height = Target.Height
            .Width = Target.Width
            .Activate
        End With
    End If
End Sub

Ugh..kinda nasty but it works.
Solution 3: Almost the Same as 2
Use the same setup as Solution2 but use a Cell Style to indicate that it is an Employee Name Validation Range.  The advantage of this is that you could have the validation anywhere on the Worksheet without having to update your code.
For this solution you will need to change

isEmployeeRangeSelected = Not Intersect(Target, Sh.Range("C5:C8")) Is Nothing

to this

isEmployeeRangeSelected = Target.Style = "Cell Style Name goes Here"


The first thing I notice is the somewhat misleading method name IsPrime. I would call it IsFactor, because it only checks if i is a factor of number - not if it is a prime factor.

Secondly I think it is a problem that PrimeFactorsMock.IsPrime has its own implementation of number % i = 0L because you then don't evaluate the base class implementation which could be invalid.

A solution to that problem could be as shown below. Be aware that I have dropped the IPrimeChecker, because it is unnecessary.

module PrimeFactors =

    type PrimeFactors() =

        // I've renamed IsPrime to IsFactor because it is only checking if i is a factor of number not if it is a prime factor
        // You have to tuple the arguments to make it possible to be called from a derived class by base.IsFactor
        abstract member IsFactor: uint64 * uint64 -> bool
        default this.IsFactor (number, i) = number % i = 0UL

        member this.CheckPrimes number i acc =
            match i with
                | _ when i > (number |> float |> sqrt |> uint64)   -> number::acc
                | _ when this.IsFactor (number, i) -> this.CheckPrimes (number / i) i (i::acc)
                | _  -> this.CheckPrimes number (i + 1UL) acc

        member this.Of number =
            if number = 1UL then
                [||]
            else
                this.CheckPrimes number 2UL [] |> List.toArray

module PrimeFactorsMock =
    open PrimeFactors

    type PrimeFactorsMock() =
        inherit PrimeFactors()

        let mutable stepCount = 0L

        override this.IsFactor (number, i) =
            stepCount <- stepCount + 1L
            base.IsFactor (number, i) // Her the base class implementation is called

        member this.StepCount number =
            stepCount <- 0L
            this.Of number |> ignore
            stepCount

When it comes to Object Expressions as a mock for testing, I haven't found a valid approach in this case, because you can't extend an OE beyond the type you "derive" from. For instance the below straight forward solution is not an option:

let mock = {
    new PrimeFactors.PrimeFactors()
    with
        member this.IsFactor (number, i) =
            stepCount <- stepCount + 1L
            base.IsFactor (number, i)

    // This is not allowed
    let mutable stepCount = 0L
    member this.StepCount number =
        stepCount <- 0L
        this.Of number |> ignore
        stepCount

}

According to Active Patterns for Prime|NoPrime (or is it Factor?) I would use a union type instead defined as follows:

type FactorType =
    | Factors of uint64 * uint64
    | NonFactor

- used in a way like this:

let getFactorType a b =
            match a % b with
            | r when r = 0UL -> Factors(b, a / b)
            | _ -> NonFactor

- and matched like this:

match getFactorType num i with
| Factors(a, b) -> getPrimes b a (a::acc)
| NonFactor -> getPrimes num (i + 1UL) acc

An entire solution that uses a discriminated union type for factor/nonfactor and minimize the Mock derive could be as follows - not claiming it to be best practice or anything like that.

module PF =

    // Instead of an active pattern, I use this discriminated union type
    type FactorType =
        | Factors of uint64 * uint64
        | NonFactor

    // Function prototype for functions testing if a number is a factor of another
    // I've changed the domain type from int64 to uint64
    type FactorChecker = uint64 * uint64 -> FactorType

    type PrimeFactors() =

        // This function is made static because it has nothing to do with the class itself
        // and because I want to reuse it in the derived Mock class (se below)
        // I renamed it to getFactorType from IsPrime,
        // because IsPrime is somewhat misleading
        // as it only checks if b is a factor of a not if it is a prime factor.
        static member getFactorType (a, b) =
            match a % b with
            | r when r = 0UL -> Factors(b, a / b)
            | _ -> NonFactor

        // This could be static as well but here I made it a member.
        // It would be nice to declare it protected, but that's not an option in F#
        // In order to let the client provide the function to check for factors, the last argument is a function of type FactorChecker
        member this.getFactors number (factorChecker: FactorChecker) =
            if number < 2UL then
                []
            else
                // The stop condition is the (uint64 sqrt) of n
                let max n = n |> float |> sqrt |> uint64

                let rec getPrimes num i acc =
                    match i with
                    | _ when i > max num -> num::acc
                    | _ ->
                        match factorChecker (num, i) with
                        | Factors(a, b) -> getPrimes b a (a::acc)
                        | NonFactor -> getPrimes num (i + 1UL) acc

                getPrimes number 2UL []

        member this.Of (number: uint64) : uint64 list = this.getFactors number PrimeFactors.getFactorType

module PFMocks =
    open PF

    // This is a simplified version of PrimeFactorsMock without the IsPrime override
    type PrimeFactorsMock() =
        inherit PrimeFactors()

        member this.StepCount number =
            let mutable stepCount = 0L
            let facChecker (a, b) =
                stepCount <- stepCount + 1L
                PrimeFactors.getFactorType (a, b)
            this.getFactors number facChecker |> ignore
            stepCount


The repeated n == 0 conditions are not pretty. It would be better to turn that part into a nested condition to avoid the duplication. It will also help simplifying the two conditions on sum.

In addition, there is one more comparison with 0 of n: in the loop condition. That's unnecessary, because n will never become 0. Only if the input is 0, but then the current implementation will return true, which is wrong, since 0 is not a happy number. As such, the loop can be while (true) infinite loop, and your could replace the last return statement with throw new IllegalStateException("whaaaat? How did you get here? ") or similar.

The overall logic would be easier to follow if you separate the summing of the digits from the method exit control. You could add a helper function that returns the sum of the squares of digits. Based on that result you could decide to return a value or continue for another round.

You can replace n=n/10 with n /= 10.

The formatting is messy too. Try the auto reformat feature of your favorite IDE.


You should never run a query in a loop, especially a loop where the number of queries issued scales with the size of the data.  There is almost always a way to formulate the SQL such that you get the results you want with a small, fixed number of queries.

In your case, you want two queries: one to find rows that are unique (ignoring the indx column), and another to find the rows that appear more than once (ignoring the indx column).  You could formulate those queries as:

SELECT data_lname, data_fname, data_mname, data_dob, data_mobile
    FROM tbl_data
    GROUP BY data_lname, data_fname, data_mname, data_dob, data_mobile
    HAVING COUNT(indx) = 1
    ORDER BY indx;

SELECT data_lname, data_fname, data_mname, data_dob, data_mobile
    FROM tbl_data
    GROUP BY data_lname, data_fname, data_mname, data_dob, data_mobile
    HAVING COUNT(indx) > 1
    ORDER BY indx;

Use those queries to populate lstUnique and lstDup, respectively.

Edit: I read the code carelessly, and misinterpreted the criteria for considering two records to be "duplicates".  I would reformulate the query close to the way your VB code worked.

To find the unique records:

SELECT *
    FROM tbl_data AS a
    WHERE NOT EXISTS (
        SELECT indx
            FROM tbl_data AS b
            WHERE
               a.indx <> b.indx
               AND a.data_lname = b.data_lname
               AND a.data_fname = b.data_fname
               AND a.data_mname = b.data_mname
               AND (a.data_dob = b.data_dob OR a.data_mobile = b.data_mobile)
    );

To find the records with duplicates, change WHERE NOT EXISTS to WHERE EXISTS.

This assumes that none of the fields can have a NULL value.

For performance, be sure that indexes exist on the table.  I assume that indx, being the primary key, already has a UNIQUE INDEX.  In addition, there should be an index on (data_lname, data_fname, data_mname).


Hard coding your data can be lengthy and it can restrict flexibility when carrying out further analysis. You can shorten your code with list comprehension.

import random

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

def main(val):
  ls = [i for i in random.choices(n, k=val)]
  ns = sum(ls)/len(ls)
  print('Length of Data : {}\nSum of Data    : {}\nAverage of Data: {}\nRandom Gen Data: {}'.format(len(ls), sum(ls), ns, ls))

main(100) #Enter amount of data you want to pass through the function

This returns:

Length of Data : 100
Sum of Data    : 399
Average of Data: 3.99
Random Gen Data: [7, 4, 0, 8, 8, 0, 6, 7, 6, 4, 7, 0, 0, 0, 9, 4, 3, 0, 0, 7, 0, 4, 6, 5, 3, 0, 6, 0, 7, 0, 0, 4, 3, 7, 7, 9, 5, 3, 5, 2, 0, 4, 1, 1, 5, 8, 9, 0, 3, 2, 7, 5, 3, 3, 3, 3, 7, 5, 7, 5, 7, 1, 6, 2, 7, 7, 5, 1,6, 6, 4, 7, 8, 2, 0, 1, 5, 3, 5, 4, 9, 7, 7, 2, 0, 3, 4, 6, 3, 4, 3, 5, 6, 3, 0, 1, 3, 8, 0, 1]

It isn't necessary to use a while loop in this instance because you will still need to break your loop which is the same as giving a start and end value to a random range reference.


Simulating the martingale betting system with roulette

Is it more natural for functions that compute random variable x to require StdGens as an argument, or for them to create StdGens and perhaps return IO x?

I think in most cases you're going to be better off passing around a pure source of randomness or a seed value so that you can guarantee deterministic output if need be by using the same seed in multiple runs. That is, you made the right choice.

  Also, is my source code posted below reasonable and could it be improved or made more natural?

I don't think there's anything wrong per se, but it's very narrowly focused without much opportunity for reusability. You'll not often go wrong if you attempt to mirror the reality of what you're modeling in your functions and type signatures. For instance, consider that a roulette wheel is an unlimited source of randomly chosen values. One way to express this in your Haskell program would be...

wheel :: StdGen -> [Int]
wheel = randomRs (0, 37)

It's useful to encapsulate this because there's nothing about martingale betting systems that involves a random element, the system itself is entirely deterministic.

martingale :: Int        -- ^ Current bet
           -> Bool       -- ^ Result of current spin
           -> (Int, Int) -- ^ (Next bet, winnings/losings)
martingale bet True  = (1      ,        bet)
martingale bet False = (bet * 2, negate bet)

Here I've separated out just the betting system aspect of your program, because tracking winnings or choosing ranges are separate functions from determining bets. This way also you can substitute different betting strategies fairly easy as long as it has the same type signature.

You'd tie this all together with a simulation function something like this.

simulate :: (Int -> Bool)               -- ^ A picking function
         -> (Int -> Bool -> (Int, Int)) -- ^ A betting function
         -> Int                         -- ^ An initial bet
         -> (Int -> Maybe Bool)         -- ^ Decides when to leave the table
         -> [Int]                       -- ^ A wheel
         -> Bool                        -- ^ Took winnings or unacceptable loss?

This is probably way overkill to start with, but with it you could test biased wheels, or different levels of acceptable losses, or different strategies against particular wheels. At this point also you'd want to start using type aliases, newtypes, or your own data types to disambiguate what's going on. E.g., you'd end up with...

simulate :: (Slot -> Bool)
         -> (Stake -> Bool -> (Stake, Winnings))
         -> Stake
         -> (Winnings -> PlayState)
         -> [Slot]
         -> PlayState

And used like,

simulate betOnRed martingale 1 quitWhileAhead unbiasedWheel
simulate betOnLow antimartingale 50 bailBelowFifty houseBiasedWheel


The functionality you are looking for is found in RequireJS and follows a spec called Asynchronous Module Definition (AMD). It is a mechanism that allows dependency management in JS, most notably in browsers.

As to why you think your own code is better, think again:

  it provides better latency on 3G network

It's because you think the modules are deployed "as is", as file-per-module basis. You are thinking of the "additional HTTP request per module" am I right?

Sure, they work when broken down into modules. But you don't actually deploy them that way. You use the optimier which minifies your modules, and combines related modules into a file. This results in:

Smaller files due to minification
Lesser files due to dependency combination
Lesser files to download since your dependencies are grouped into related modules.

Also, the modules are cached once loaded. Once another modules requires a module that is already loaded by another module earlier in the execution of your code, it uses the cached one rather than requesting it again.

  I don't like unnecessary function wrappers... for every module, every require call.

A require/define call is designed to:

define the dependencies
define the module
the filename is the module name

It isn't that hard to code:

//MyModule.js
define([
  'what',
  'you',
  'need'
],function(what,you,need){

  //what you do

  return whatYouWantExposedFromThisModule;

});

  I am now able to use my script like php's include.

Handling the modules

include is like appending one file to the other, which is synonymous to concatenating files. In JS, we don't want globals. What if one module of yours had a bam variable, but has bam in another and you required the two. How would you handle that?  Also, JS execution does not halt. How would you expect to do a require in your implementation? Synchronous XHR? preloading? That takes time! You'd be halting the execution for each require call of your implementation just to load a script.

<script>

  require('alert');
  //halt here to load alert?
  //you'd block the UI, freeze the browser, lose the user
  bam(); // 9

</script>

In the module definition in require, the code of the module lives in it's own scope. Nothing is spilled to the global scope. What is exposed by the module is only exposed to the function that requires it, which is also a closed scope. Also, modules are cached. Once a module is already loaded, future requires to that module are taken from the cache, not from the network. They are asynchronous, and does not block the UI thread and the requiring code only executes when the dependencies are loaded - nothing is halted while we wait for the dependencies to load.

Loading the modules

Suppose you will do AJAX with your eval approach - it's not cross-domain friendly, and cross-browser friendly (IE).

The concept of loading a module is based on script-loaders which can do cross-domain. It's similar to how JSONP works, but instead of an arbitrary callback, they are fed through define.

I suggest you read more about how script loaders and dependency loaders work. This is a broad topic and has it's own spec.


Image hosting site image downloader using requests and BeautifulSoup

According to PEP8 standard library import should be first.

Function find_link(element):

The docstring of the function find_link should probably say something about the argument type.
Why is the argument element (and not element_attributes) when it looks like all you use is element.attrs?
The list comprehension could be written as: attr_list = list(element_attr_dict.values())
But, you don't need it at all. You can simply write for element in attr_dict.values().

To summarize, you can delete most lines in the beginning. Instead start with

def find_link(element_attributes):
    link_regex = re.compile(r"//c\d+.staticflickr.com/\d+/\d+/\w+\.jpg")
    attr_string = ""
    for element in element_attributes.values():
        ...

As for the main function:

Investigate argparse.
Use logging instead of print.
Split the main function to sub-functions. At least saving an image from a link should probably be one.
The for loop where you append a link to a list can be expressed as a list comprehension.

I hope that helps!


Oracle PL/SQL decryption function breaking index?

I've found that the reason that decryption xor sorting is fast, but decryption and sorting is slow:

Decryption will only grab the first 100 or so records, decrypt them, and display them.  Fast.
Sorting will grab the first 100 or so records (utilizing the pk index) and display them.  Fast.
Decryption and sorting will force a table scan, resulting in decrypting several thousand records, and then sorting them all.

In other words, the "fast" queries are only fast because they're doing very little work.


Stack sizing

The 3 stacks have different size limits:

The 1st stack can have maximum size / 2 elements
The 2nd and 3rd stacks share their storage, they can have size / 2 elements

When there is a peculiar limitation like this, it's good to document it, and hopefully with an explanation of the reasoning.

An alternative approach could have been giving each stack size / 3 space.

Another alternative would be using an array of StackNode objects, where StackNode would store the payload, and a link to the StackNode above it. This way all stacks would have dynamic size, until their total use reaches the capacity of the StackNode array. However, in addition to the extra storage needed (for the links), the logic would be also more complicated to account for the freed spots in the array.

Make final what you can

This field can be final:

private int[] stack;

One statement per line

It's best when you can read code from top to bottom.
When there are multiple statements per line,
it's easy to overlook the right end.
So instead of putting multiple assignments on the same line like this:

first = -1; last = size; mid = (first + last) >> 1;

It would be better to break it up, to have one statement per line.

Clever code

This code is a bit clever:

mid = (first + last) >> 1;

It's best to keep things simple and natural:

mid = (first + last) / 2;

Sure, bit shifting is faster than division.
But it's reasonable to expect the compiler to automatically convert / 2 to use bit shifting instead of division, so that you can write simple, natural, unsurprising code. (I don't know if the compiler actually does that, but in any case, such micro-optimization is likely to be pointless pedantry anyway.)


Towards better design, functionality and performance

Start with good names: that means following Python naming conventions and give a meaningful names to your identifiers/functions/classes:

rangeSelector ---> ping_network_range
createThread ---> start_threads
pingBox ---> check_host

As @Peilonrayz already mentioned range(256) is the valid range for your case.

The former createThread function tried to create a single thread with start ing and join ing it at one step. But that undermines the benefit of using threading for parallelizing computations. The crucial mechanics is that all treads are initiated/started at once, then, we join them (awaiting for their finishing) at next separate phase.
On constructing a threading.Thread no need to pass custom thread name through kwargs={"threadName": ...} - the Thread constructor already accepts name argument for the thread name which is then accessed within target function via threading.current_thread().name.

The former pingBox function used os.system function (executes the command (a string) in a subshell) which is definitely not a good choice.
The more robust, powerful and flexible choice is subprocess module:

  The subprocess module allows you to spawn new processes, connect to
  their input/output/error pipes, and obtain their return codes. This
  module intends to replace several older modules and functions:
  os.system, os.spawn*
  ...
  The recommended approach to invoking
  subprocesses is to use the run() function for all use cases it can
  handle. For more advanced use cases, the underlying Popen interface
  can be used directly.

Some good, user-friendly description - on this SO link.

Furthermore, the ping command (OS network tool) can be speed up itself through adjusting specific options. The most significant ones in such context are:

-n (No attempt will be made to lookup symbolic names for host addresses. Allows to disable DNS lookup to speed up queries)
-W <number> (Time to wait for a response, in seconds. The option affects only timeout in absence of any responses, otherwise ping waits for two RTTs)
-i interval (Wait interval seconds between sending each packet. The default is to wait for one second between each packet normally, or not to wait in flood mode. Only super-user may set interval to values less than 0.2 seconds)

The difference would be more noticeable on sending more than one packet (-c option).In your case I'd apply -n and -q options. With -q option allows to quite the output since we'll get the returned code which itself indicates whether a particular host is reachable across an IP network. subprocess.run allows to access the returncode explicitly.

The 2 nested for loops within the former rangeSelector function is flexibly replaced with itertools.product routine to compose an efficient generator expression yielding formatted IP addresses:

from itertools import product
...
start_threads(f'127.0.{i}.{j}' for i, j in product(range(256), range(256)))

Designing command-line interface

As your program is planned to be used as part of pipeline, instead of hanging on interactive, blocking call of input('Choose range A|B :') - the more flexible and powerful way is using argparse module that allows building an extended and flexible command-line interfaces with variety of options of different types and actions.
For ex. the allowed network classes names can be supplied through choices:

...
parser = ArgumentParser(description='Ping network addresses by network class')
parser.add_argument('-c', '--nclass', choices=('A', 'B'), required=True, help='Choose class A or B')

The final optimized implementation:

import threading
from argparse import ArgumentParser
from itertools import product
import subprocess

def check_host(host: str):
    return_code = subprocess.run(["ping", "-c", "1", "-n", "-q", host],
                                 stdout=subprocess.DEVNULL,
                                 stderr=subprocess.DEVNULL).returncode
    print(f'response for pinging {threading.current_thread().name} is {return_code}')

    status = 'up' if return_code == 0 else 'down'
    print(f'{host} : is {status}')

def start_threads(addr_range):
    for addr in addr_range:
        t = threading.Thread(target=check_host, args=(addr,),
                             name=f'Thread:{addr}')
        t.start()
        yield t

def ping_network_range(net_class: str):
    net_class = net_class.upper()
    if net_class == 'A':
        threads = list(start_threads(f'127.0.0.{i}' for i in range(256)))
    elif net_class == 'B':
        threads = list(start_threads(f'127.0.{i}.{j}'
                                     for i, j in product(range(256), range(256))))
    else:
        raise ValueError(f'Wrong network class name {net_class}')

    for t in threads:
        t.join()

if __name__ == "__main__":
    parser = ArgumentParser(description='Ping network addresses by network class')
    parser.add_argument('-c', '--nclass', choices=('A', 'B'),
                        required=True, help='Choose class A or B')
    args = parser.parse_args()
    ping_network_range(args.nclass)

Sample usage (with timing, under Unix time command):

time python3 ping_network_range.py -c B > test.txt

real    2m4,165s
user    2m17,660s
sys     4m35,790s

Sample tail contents of resulting test.txt file:

$ tail test.txt
response for pinging Thread:127.0.255.250 is 0
127.0.255.250 : is up
response for pinging Thread:127.0.255.252 is 0
127.0.255.252 : is up
response for pinging Thread:127.0.255.253 is 0
127.0.255.253 : is up
response for pinging Thread:127.0.255.255 is 0
127.0.255.255 : is up
response for pinging Thread:127.0.255.254 is 0
127.0.255.254 : is up


Construct a tree given pre and inorder or post and inorder

The algorithm looks good to me. Regarding the code, here are a few points:

You don't need to overload the function. Semantically it's a tree builder, and probably the private function can be termed as buildTree.
The following condition should throw the IllegalStateException instead of IllegalArgumentException:

if (parentPosInorder > hb) {
    throw new IllegalArgumentException("Your tree is not accurate");
}

You can make the code generic by using a generic data type for the node value.  Accordingly, the API will be extensible enough.


Yes/no confirmation buttons on a slide-out panel

I would add a couple of named functions:

var hideConfirmationMessage,
    showConfirmationMessage;

hideConfirmationMessage = function () {
    $('.js-confirmation').stop(true).animate({ left : '-100%' }, 500);
};

showConfirmationMessage = function() {
   $('.js-confirmation').show().stop(true).animate({ left : '0' }, 500);
};

Then your event handler attachment becomes much simpler:

$('.js-confirmation-yes').click(function() {
    hideConfirmationMessage();
    $('.container').delay(500).fadeOut(200).hide(200);
});

$('.js-confirmation-no').click(hideConfirmationMessage);
$('.js-decline-button').click(showConfirmationMessage);

I'm not sure if that's "cleaner" to you but I think it's easier to read and doesn't repeat itself.


Simple HTTP server that performs a regex test

The call to regexp.MatchString is the only really expensive part of your code. Do you need full regexp support? If you just want to find substrings, you should use strings.Contains instead of the regexp package. Otherwise, there's no way around it. It might be worth looking at what each request looks like: you could call strings.Contains for the simple ones (that don't use any regexp features) and only use regexp.MatchString when needed.

Some comments on style:

Your NewMessageController method is useless. Just have your callers use new(controllers.MessageController).
Use t.Fatalf instead of log.Fatalf in your tests.
Build strings in a consistent manner:

var (
    longString = "your long string"
    subString = "home"
    host = "http://localhost:8080"
)
func TestPostMessage(t *testing.T) {
    url := fmt.Sprintf("%s/messages?body=%s&pattern=%s", host, longString, subString)
    …
}


JavaScript function for logging the members of an object (with horizontal alignment)

Simplification with for/in loops

Your loop through Object.keys() in the function you have for the max variable is reinventing JavaScript's for/in loop which loops over and objects keys. Here's how you could simplifying that code:

for(var key in obj) {
    if(!obj.hasOwnProperty(key)) {
        continue;
    }

    if(key.length > ret) {
        ret = key.length;
    }
}

Unnecessary recursion

Your getSpacer function is using recursion when it really does not need to be; the function would be a lot simpler and a lot faster if you used a neat JavaScript trick for repeating characters:

function getSpacer(len) {
    return Array(len + 1).join(" ");
}

Now, there's no need for recursion - that means there is less interaction with the stack - and, rather than switching to a loop, this nice solution can be used.


Check if the given string has duplicates

Documentation mismatch

The documentation and the functionality do not fit. Your function is supposed to "check if [a string] has duplicates". From the documentation, I expect a function hasDuplicates that returns true if I have duplicate characters and false otherwise.

However, you provide isUnique, which does the opposite: return true if there are no duplicates and false if there are duplicates. The internal documentation fits, but I would say "checks whether it contains no duplicate characters" or "contains unique characters only".

Possible bugs

You checked your string only on alphabetic strings. What happens on "12345678"? You will index -48 due to '1' - 'a'. That's a bug waiting to happen. Also, what happens if your string contains a 'z'? What happens if str is null? Maybe str shouldn't be null, but that should get mentioned in the documentation (see above).

Also, you should mention that your function is case-insensitive. But why does "Aa" count as a duplicate to begin with?

Both cases (non-alpha character and same letters in different cases) should get added to your tests.

Algorithm

Your seen algorithm is fine if you know exactly how many buckets you need. But you often don't know that. A Map<char,bool> can happen here. If you use a TreeMap you end up with the mentioned \$\mathcal O(n \log n)\$, but if you use a HashMap the asymptotic complexity is \$\mathcal O(n)\$ again. Alternatively, use a set.

But that's asymptotic complexity. If you don't consider any non-alpha strings (see section above), then you can immediately return false if the string is longer than 26 characters due to the pigeon hole principle.


Loading and comparing files containing 3D data

For inequality, it is sufficient to have one difference. If one difference is found, it's unnecessary to compare more data. There's no point in counting equal data entries and compare that number to the total number of entries, because a single inequality will reduce that number making it impossible to be the same as the total number of entries.

if(data_train[i] == data_test[i])
            count++;

Should be

if(data_train[i] != data_test[i])
            return 0;


If I were to use "find by" PageFactory-like notation in Python, I would go with the one proposed here - similar to your versions, but more concise and supports more features:

from pageobject_support import callable_find_by as find_by

class GoogleSearchPage(object):
    search_input = find_by(how=By.NAME, using='q')

Old Answer (in case there is anything useful there)

I would go further and follow the Page Object pattern, creating abstractions for the pages and elements you are working with, as demonstrated in the selenium documentation. This way you are isolating your locators from the logic of the test providing an "API" to work with a particular page.

Here is one way to do it - pay attention to how simple and concise the actual test has become:

import unittest

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

class MainPageLocators(object):
    """A class for main page locators. All main page locators should come here"""
    SEARCH_INPUT = (By.NAME, 'q')

class BasePage(object):
    """Base class to initialize the base page that will be called from all pages"""

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

class MainPage(BasePage):
    """Home page action methods come here."""

    def search(self, search_query):
        """Triggers the search"""
        search_input = self.driver.find_element(*MainPageLocators.SEARCH_INPUT)
        search_input.send_keys(search_query)
        search_input.send_keys(Keys.ENTER)

class TestGoogle(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.get("https://google.com")

    def tearDown(self):
        self.driver.close()

    def test_search(self):
        main_page = MainPage(self.driver)
        main_page.search("selenium python")

Note that you may also want a separate class for an element, but this should be good enough to get you started.

Also note that I'm using a unittest.TestCase as a base class for your test which, aside from bringing other benefits, allows to nicely start and close a browser via setUp and tearDown.


Missing header: #include <cstddef> is required for std::size_t (other headers also provide it).
There's no need for src_ to cast away the constness of *src:
char *dest_ = static_cast<char*>(dest);
char const *src_ = static_cast<char const*>(src);

Personally, I'd just go for d and s rather than the ugly trailing underscores, but that's very much a matter of taste.
Arithmetic and comparison between pointers to different objects is unspecified behaviour, and I don't see a way to avoid it in the test.  Thankfully, in the case where src and dest are in different objects, it doesn't matter which branch you take
There's no need to test for src + count > dest as well as src < dest; we can quite happily use the "reverse" copy for any lower-to-higher copy, as long as we don't subtract from count==0 in that branch.
In the "reverse" branch, it's disingenuous to hide the assignment to src_ inside the assignment to dest_.  Much clearer to write as:
    src_ += count - 1;
    dest_ += count - 1;

We can avoid that -1 if we pre-decrement rather than post-decrement (it's safe to point to one past the end).
Style: Use braces on both sides of else, or neither; avoid if () {} else ;.

My version
#include <cstddef>

void *memmove(void *dest, const void *src, std::size_t count)
{
    auto d = static_cast<char*>(dest);
    auto s = static_cast<char const*>(src);

    // If s and d are in distinct objects, the comparison is
    // unspecified behaviour, but either branch will work.
    if (s < d) {
        s += count;
        d += count;
        while (count--)
            *--d = *--s;
    } else {
        while (count--)
            *d++ = *s++;
    }

    return dest;
}

Performance
Copying a single char at a time is going to be sloowww.  Real implementations take advantage of processors' native transfer size, DMA hardware, and specialized instructions where available.  That's why it's a standard library function rather than user-supplied.


Generate a set of random values based on seed

unif.seed_value is very un-Pythonic. Instead use a class.
Rather than using getattr(unif, "seed_value",0), you can make self.seed_value at object instantiation, and use that as the default, unless it's falsy, where it'd instead use seed.
math.floor is mostly the same as int. If you're using this on division, you can change it to floor divisions using //.
numpy.int32 is odd, it adds a dependency to numpy that shouldn't be needed. Instead you can use & or %, this also means that it doesn't throw an error if the number is greater than (1 << 31) - 1.
unif.seed_value/float(m) is the same as unif.seed_value/m in Python 3. In Python 2 it'd do floor division, unless one number is a float.
generate_flow_shop shouldn't need to take output, that should be implemented in main.
generate_flow_shop should take a single problem rather than the list of problems.
You can use tuple unpacking to give all values in the problem a name.
I heavily recommend str.format over the old % formatting operator. It has less bugs, and is enhanced in 3.6 with f-strings.
You can use _ as a 'throw away variable' in Python, it's somewhat a standard and lets developers ignore that variable, greatly increasing readability.

unif uses some fairly odd math, and so I decided to go for a more succinct approach.
And so I'd change your code to: (note, it's untested)

class Random:
    def __init__(self):
        self.seed_value = None

    def unif(self, seed, low, high):
        seed_value = self.seed_value or seed

        a = 16807
        b = 127773
        c = 2836
        m = (1 << 31) - 1

        seed_value = (a * (seed_value % b) - (seed_value // b) * c)

        self.seed_value = (seed_value + (seed_value < 0)) & m
        return int(low + self.seed_value / m * (high - low + 1))

    def generate_flow_shop(self, problem):
        """Generates a flow shop problem set for a set in problem tuple and\
                writes to file in output"""

        time_seed, num_jobs, num_mach = problem
        r = [
            [
                self.unif(time_seed, 1, 99)
                for _ in range(num_jobs)
            ]
            for _ in range(num_mach)
        ]
        self.seed_value = None
        return r

def main():
    name = input("Enter filename to write the generated values:\n> ")
    seedfile = input("Enter filename of the seed values:\n> ")
    r = Random()

    with open(seedfile) as in_file:
        problems = [
            tuple(map(int, line.strip().split()))
            for line in in_file
            if line[0] != "#"
        ]

    with open(name, "w") as out_file:
        for i, problem in enumerate(problems):
            out_file.write("p {0:04} {1[1]} {1[2]}\n".format(i, problem)))
            data = r.generate_flow_shop(problem)
            out_file.write(''.join(' '.join(line) + '\n' for line in data))

if __name__ == '__main__':
    main()


Project Euler 14: Longest Collatz Sequence

An obvious improvement is to check n for being already solved on each iteration of for n loop. As coded, you still go all the way to 1, which might be quite long. Something along the lines of

for ( a = 2; a < maxnum; ++a) {
    std::vector<unsigned long long>cache;
    for (n = a; n != 1 && !cz[n].solved; ) {
        cache.push_back(n);
        n = (n%2 == 0)? n/2: 3*n+1;
    }
    // make cached data solved
    ...
}

If cz[1].solved is preset to true, the loop condition can be simplified to

for (n = a; !cz[n].solved; )


Rotate an image (2D array) by 90 degrees recursively with low memory usage

First of all, I don't see why do_rotateImageInplace shall be recursive. And indeed, it is a tail recursive, and as such is trivially converted into a loop.

Second, the comments are seriously misleading. This is what they say:

//backup row
//copy row into col
    (hmm... now `col` is permanently destroyed)
//swap tmp with end row
    (hmm... the comment above says that tmp istelf is a row. Why would I want to swap rows?)

etc.

The only useful comment is about peeling the onion. And a good comment really wants to be a function name. So

for (int layer = 0; layer < N/2; layer++)
    rotate_layer_inplace(img, N, layer);

seems like what you are trying to do.


Most of my comments are unrelated to security.  A few down at the bottom.

$myemail = "YOUR EMAIL ADDRESS";

Elsewhere you use snake_case names.  If you did that here, you'd have $my_email.  I'm assuming that you removed the read email address for privacy reasons.

if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}

The indenting here is not standard.  Usually it would have been written

if ( ! preg_match('{([\w\-]+\@[\w\-]+\.[\w\-]+)}', $email) )
{
    show_error("E-mail address not valid");
}

I also added some whitespace in the if because I find it easier to read.

I changed to a single quoted string and used a different regular expression delimiting pair.

Another problem is that this will match some invalid emails.  For example, -@-.- is valid in this pattern.  So if those five characters appear in the field, it will be recognized as valid.  Note that you don't restrict characters that appear before and after that sequence.

if (!preg_match("/5/", $captcha))

This would match 15, 51, etc. as well as 5.  You don't need to use preg_match here.  You can just say something like

if ( '5' != $captcha )

or

if ( 5 != (int)$captcha )

Note that if you want the exact original functionality (match any string that contains the number 5), you could say

if ( false === strpos($captcha, '5') )

That would be much faster than the regular expression version.

$message = "

Name: $name
E-mail: $email

Message:
$message

";

This would more commonly be written with a heredoc rather than a multiline double quoted string.

$message = <<<EOM

Name: $name
E-mail: $email

Message:
$message

EOM;

You don't need a final

?>

The usual convention is to leave it off if your script is not supposed to produce output.  Technically speaking show_error does produce output, but it's not supposed to be called by the script.  I'd leave off the final ?>.

Security

You don't show how the $subject is set, so it's unclear if it's safe or not.  If this is the whole script, it will send with a blank subject.

Note that trim and stripslashes do not add security.  They help fix the input to make it display properly.  The normal use of stripslashes is to undo a PHP security protection that didn't quite work right.  The htmlspecialchars is the security function.  I'm not sure that email is vulnerable to HTML characters.  Perhaps your email client is though.


The easiest way to do this is to note that each value that is generated will be a permutation of the values 0 - 9. This will generate 10! = 3628800 possibilities. There are a number of algorithms to generate permutations, the easiest in this case would simply be to generate them in lexicographic order.

Wiki has a rundown of some algorithms you can use to generate permutations.


Vectorized type conversion for autocorrelation

If this code goes into production then the asserts for the success of calloc() will be optimized out of the code if the code is optimized. Prefer if statements with calls to fprintf(stderr,.
The parameter rate is never used, this can lead to maintenance errors in the future.
For maintenance reasons the ability of someone else to understand the code I would suggest using &input[i] rather than input+ in the function call.


You are clearly violating the Single Responsibility Principle (SRP) because the method is doing two things. You should use two methods where each validates one type only.

You will see also that for this task you gain the advantage that the methods will be smaller and easier to read and understand.

A small side note: In .NET methods are named using PascalCase,  so isValid should be IsValid.

Don't omit braces {} although they might be optional. By always using them your code will become less error prone.

Another quick remark about the method in question. You have defined optional parameters min = 0 and max = 0. I would expect if parameters are optional, that they could return true for a bool method. Using this method without specifying min and max will result in false which is unexpected.

Integrating the said points into extension methods would look like so

public static bool IsInRange(this int value, int min, int max)
{
    return min <= value && value <= max;
}

public static bool HasValidLength(this string value, int maximumLength)
{
    if (value == null) { throw new ArgumentNullException("value"); }

    return value.Length < maximumLength;
}

which could then be called through this methods

public static bool IsValidInteger(this string value, int min = int.MinValue, int max = int.MaxValue)
{
   int v = 0;
   return int.TryParse(value, out v) && v.IsInRange(min, max);
}

public static bool IsValidString(this string value, int maximumLength = 30)
{
    return value != null && value.HasValidLength(maximumLength);
}

like e.g

if(userInput.IsValidInteger(0, 5))
{
   // do something awesome
}


Does this nodeunit test conform to best practices?

You could use sinon.js to have the power of spies, stubs and mocks. http://sinonjs.org/

That way you could create a stub of httpRequest.

Look for stub.yield([arg1, arg2, ...]).

Edit I added a code example. I did not fully tested the code, but it's how it would look like.

var sinon = require('sinon');
require('../server/extensions');
var FmsRescuers = require('../server/fms_rescuers');
var Rescuer = require('./stubs/helper').Rescuer;

var mockedHttpRequest;
var rescuers;
var rescuer;

exports.testCheckIn = {
    setUp: function(done) {
        var httpRequest { post: function () {} };
        mockedHttpRequest = sinon.mock(httpRequest);
        rescuers = new FmsRescuers(mockedHttpRequest);
        rescuer = new Rescuer(42, 'Name', new Date().addHours(-2).toTimeZonedString(), new Date().addHours(-1).toTimeZonedString());

    },

    'check in requests correct path' : function(test) {
        var expectedPath = '/attendance/checkin'
        mockedHttpRequest
                .expects('post')
                .once()
                .withArgs(expectedPath)
                .yields('', 200);

        rescuers.checkIn(rescuer, 123, 3, function(result, status) {
            mockedHttpRequest.verify();
            test.equal(result, '');
            test.equal(status, 200);
            test.done();
        });
    },
};


You definitely incorporated the response to your previous questions, such as:

Extract code into functions.
Always indent with 4 spaces.
Process input immediately instead of storing all input data and results in lists.

There is still too little (horizontal) whitespace, I suggest to check
your code against the PEP8 coding style,
for example at PEP8 online.

Also function and variable names should be snake_case according to PEP8.

More suggestions:

Variable names: T is too short and non-descriptive, num_tests
would be better. pair is better named pairs.
There is no need to pre-assign pair=[].
The value of the iterator variable i in the main loop is not needed,
a common convention is use _ instead:

for _ in range(T):

Negation as in -1*l[i] can be simplified to -l[i]
When printing the result list

print(" ".join(str(x) for x in pair))

you can use map instead, as you already do when reading the input:

print(" ".join(map(str, pair)))

Improving the performance:

Your algorithm has two nested loops traversing through the list, i.e. the
time complexity is \$ O(n^2) \$ as a function of the list length.

This can be improved by sorting the list first. One option would be to sort
the numbers in increasing order, e.g.

-3 -1 1 2 3 6

for the first test case, and then traverse the list from both ends to find
pairs. The time complexity is \$ O(n \log n) \$ for the sorting, and
 \$ O(n) \$ for the traversal, so this would be faster for large input.

Another option is to sort the number in increasing absolute value, e.g.

 -3 3 -1 1 2 6

Again a linear sweep of the sorted list is now sufficient to find matching pairs,
which are now consecutive entries.

Here is a possible implementation of the second approach:

def find_pairs(numbers):
    numbers.sort(key=lambda x: x + 0.5 if x >= 0 else -x)
    pairs = []
    for pair in [(x, y) for x, y in zip(numbers, numbers[1:]) if x == -y]:
        pairs.extend(pair)
    return pairs

using

sort() with a custom key. This relies on the given fact that the numbers are
distinct integers.
zip and list comprehension to enumerate pairs of consecutive list entries.


Overall, this looks very reasonable! There are some small style nits like spaces inside of struct declarations. A few bigger points:

The Rust community loves crates and reusing existing work. In this case, you should use byteorder instead of bit-banging yourself. Beyond being less code, a nice bonus is that the fact that you use little-endian is now written in words in the code!
If you weren't doing this project for fun or learning, I'd recommend using one of the existing CRC crates to completely avoid reinventing the wheel!
Consider making the lookup table into a lazy_static global. This would allow it to only be initialized once.
Even better, consider hardcoding the lookup table. This would allow you to avoid any creation overhead. There are two paths:

You could copy-paste it in. Probably fine as the CRC table is unlikely to change often.
Create a build script that generates it at compile time and then include the result. This has a little bit of overhead at build time, but captures the process used to generate the table.

There's a few extra places that have type specifications when they aren't needed, such as when building the table. It's better to allow inference to apply when you can. Because you switch back and forth between usize and u32, there will still be some places it's needed.
You could extract a function for the repeated bit shuffling and/or use a loop. You may wish to profile if you are concerned about performance, as sometimes a manual loop unrolling is still required.
Use expect instead of unwrap, to help you and your users understand failures.
Add some buffering to your file reading to prevent inefficient amounts of system calls.
Try to name your generic types so that the name hints at the type. T is great when the type can be basically anything, but in this case I'd recommend R to reflect the Read bound.
Expand on your variable names a bit. rd has a larger scope as it's shared among multiple locations and should have an easier name.
I prefer to use the where clause to specify trait bounds. I find it easier to read.
I only add trait bounds where the function implementation requires it.

extern crate byteorder;

use byteorder::{LittleEndian, ReadBytesExt};

use std::fs::File;
use std::io::{Read, BufReader};

struct WordIterator<R> {
    inner: R,
}

impl<R> WordIterator<R> {
    fn new(r: R) -> WordIterator<R> {
        WordIterator { inner: r }
    }
}

impl<R> Iterator for WordIterator<R>
    where R: Read,
{
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        self.inner.read_u32::<LittleEndian>().ok()
    }
}

struct CrcCalculator {
    lookup_table: [u32; 256],
}

impl CrcCalculator {
    fn new() -> CrcCalculator {
        let mut calc = CrcCalculator { lookup_table: [0; 256] };

        // Calculate the table:
        for v in 0..256 {
            let mut v2 = v << 24;
            for _ in 0..8 {
                if 0 != v2 & 0x80000000 {
                    v2 = (v2 << 1) ^ 0x04C11DB7;
                } else {
                    v2 = v2 << 1;
                }
            }

            calc.lookup_table[v as usize] = v2;
        }

        calc
    }

    fn calculate<R>(&self, r: R) -> (u32, u32)
        where R: Read,
    {
        let mut crc = 0xFFFFFFFF;
        let mut count = 0;

        for word in WordIterator::new(r) {
            crc = crc ^ word;

            for _ in 0..4 {
                crc = (crc << 8) ^ self.next_component(crc);
            }

            count += 1;
        }

        (count, crc)
    }

    fn next_component(&self, crc: u32) -> u32 {
        self.lookup_table[((crc >> 24) & 0xFF) as usize]
    }
}

fn main() {
    let calculator = CrcCalculator::new();

    let f = BufReader::new(File::open("Image.bin").expect("Couldn't open input file"));
    let (count, crc) = calculator.calculate(f);

    println!("count=0x{:X} crc=0x{:08X}", count, crc);
}

For fun, I wanted to see what the compile-time build solution would look like.

build.rs

use std::env;
use std::io::{self, Write, BufWriter};
use std::fs::File;
use std::path::Path;

fn write_table<W>(mut w: W) -> io::Result<()>
    where W: Write,
{
    try!(writeln!(w, "static CRC_LOOKUP_TABLE: [u32; 256] = ["));

    for v in 0..256u32 {
        let mut v2 = v << 24;
        for _ in 0..8 {
            if 0 != v2 & 0x80000000 {
                v2 = (v2 << 1) ^ 0x04C11DB7;
            } else {
                v2 = v2 << 1;
            }
        }

        if v % 8 == 0 { try!(write!(w, "    ")) }
        try!(write!(w, "0x{:08X}, ", v2));
        if (v + 1) % 8 == 0 { try!(writeln!(w, "")) }
    }

    writeln!(w, "];")
}

fn main() {
    let out_dir = env::var("OUT_DIR").expect("Could not determine where to place output");
    let dest_path = Path::new(&out_dir).join("lookup_table.rs");
    let f = File::create(&dest_path).expect("Could not create lookup table file");
    let f = BufWriter::new(f);
    write_table(f).expect("Could not write lookup table")
}

And this means that the CRC functions don't need to be instance methods anymore, and can just be free functions:

include!(concat!(env!("OUT_DIR"), "/lookup_table.rs"));

fn crc_next_component(crc: u32) -> u32 {
    CRC_LOOKUP_TABLE[((crc >> 24) & 0xFF) as usize]
}

fn crc<R>(r: R) -> (u32, u32)
    where R: Read,
{
    let mut crc = 0xFFFFFFFF;
    let mut count = 0;

    for word in WordIterator::new(r) {
        crc = crc ^ word;

        for _ in 0..4 {
            crc = (crc << 8) ^ crc_next_component(crc);
        }

        count += 1;
    }

    (count, crc)
}


Find all multiples of a number in given range in reverse order

Multiplication is not a very cheap operation.
Subtraction is much cheaper.
It will be a better and cleaner algorithm to start from the highest multiple,
and then keep subtracting until reaching 0:

int truncatedCount = limit / divisor;
int highestMultiple = truncatedCount * divisor;

for (int multiple = highestMultiple; multiple > 0; multiple -= divisor) {
    printf("%d ", multiple);
}

The improvements:

multiplication replaced by subtractions
more meaningful variable names (instead of i, for example)
more conventional spacing (around operators and around (...) and { ... }


Advent of Code 2017 Day 5 (part 1) in Functional Programming (FP)

Simple and pure

Regarding the comments the following is an example of a simple JS solution to the problem. Turns out that it is also a pure function.

// list is a copy of input, thus passing strings is inherently pure
function traverseJumpList(list) {
    list = list.split("\n");  // no need to parse the numbers as
                              // the ++ operator will coerce a string to
                              // a number for you..
    var jumps = 0, index = 0;
    // Assuming that an exit jump is also jumping to negative index
    while (index >= 0 && index < list.length) {
        jumps += 1;
        index += list[index]++;
    }
    return jumps;
}
const solution = traverseJumpList(INPUT);

Recursion

This particular problem can not be solved via recursion without proper tail calls  because you can not know the max steps in advance.

Memory

Even with tail calls on you are still fighting JS because you are not being memory aware. In the function jumper you create a new copy of the maze and then make the next jump via recursion.

This means for each jump you create a complete copy of the maze and hold it in memory until the end. So if you have a maze with 1024 items and it takes 2048 jumps to complete you will have 2097152 unique items. This is very wasteful by any standard.

You should release the previous maze before you make the next jump

  const jumper = input => {
    var currentMaze = input.maze;
    const currentPosition = input.position;
    const currentStepNumber = input.stepNumber;
    if (currentPosition >= input.maze.length) {
       return currentStepNumber;
    }
    const newOffset = input.maze[currentPosition] + 1;
    const maze = input.maze
     .slice(0, currentPosition)
     .concat(newOffset)
     .concat(input.maze.slice(currentPosition + 1));
    const position = currentPosition + input.maze[currentPosition];
    const stepNumber = currentStepNumber + 1;

    // clean up memory
    input = undefined;

    return jumper({maze, position, stepNumber});

  };

Indirect recursion.

An alternative to direct recursion is indirect recursion. This is done by calling the recuse function using a time event. The code is similar but you will need to provide the result as a function call.

This method gives unlimited recursion and frees up all incidental memory by releasing each recursive call's context from the heap before doing the next iteration. Also exiting to context idle makes GC more efficient.

Using your jumper function as an example.

  const jumper = input => {
    const currentMaze = input.maze;
    const currentPosition = input.position;
    const currentStepNumber = input.stepNumber;
    if (currentPosition >= currentMaze.length) {
      // return currentStepNumber;
      showAnswer(currentStepNumber);   // The result must be called in
      return;
    }
    const newOffset = currentMaze[currentPosition] + 1;
    const maze = currentMaze
     .slice(0, currentPosition)
     .concat(newOffset)
     .concat(currentMaze.slice(currentPosition + 1));
    const position = currentPosition + currentMaze[currentPosition];
    const stepNumber = currentStepNumber + 1;
    // call next step via timeout. This will not execute until after
    // this function has exited.
    setTimeout(() => jumper({maze, position, stepNumber}),0);

    // this function now exits before the next jump releasing the
    // original input object
  };

And the starting and answer functions

  jumper({maze: startMaze, position: 0, stepNumber: 0});
  const showAnswer = (result) => console.log(result);

Or you could have jumper return a promise on the first pass which resolves with the answer. I am not too sure if this fits the FP paradigm.


Threadsafe oneshot-event which fires on subscription if the event was fired in the past

Thread safety

Both Subscribe and GetEventHandle use lock and and+remove on field event are thread-safe too. You can even remove the volatile from m_invoked because you only ever access it under the lock from those two methods.

API and naming

Event and Invoke are pretty obvious, especially with the description. I would only change the signature of Invoke to return bool (true = invoked, false = not invoked, already done before) to better reflect the fact, that it won't throw exception if you try to invoke it multiple times (could as well be named TryInvoke, maybe changing Invoke to throw exceptions if invoked multiple-times).

GetEventHandle does not sound as good name to me, because it does much more than just getting the handle, it stores sender+args, takes current handle and clears it. I would either use it (and Subscribe) directly where they are used (only one place for each), which also solves naming-problem, or make them local functions.

AutoInvokeEvent hmm, how about OneShotEvent? Although it automatically calls subscribed handlers even after the event was fired, this is more about how it does it under the hood, than what the API is about - it will execute the handler exactly once when it is fired or if it already was fired.

Optimization

I don't think any optimization is necessary. You would have to first specify (and or test/profile) how often is the event subscribed compared to invoking it, to even have some direction in which to optimise. I can see you have switched to using some read-write-lock in the implementation you currently have on GitHub, makes sense (concurrent subscriptions, if that is trully important to you). Could as well be implemented by double-checked-locking, thanks to the fact this is one-shot event, but I don't think it is worth it, too easy to make a mistake, very hard to make it right. (The idea is to have volatile object m_lock and make it null when you fire the event, instead of using that bool m_invoked.)


I'm a bear of very little brain, so I don't really understand what you are trying to achieve, or why you think polymorphism will help you achieve it.

But I did notice some problems with your code:

There's no documentation.
There are no test cases.
Python doesn't need semicolons at the end of lines.
You don't need a \ at the end of a line if the statement cannot end at that point because of an unclosed parenthesis.
There are no checks on the validity of entity and attribute names.
Values aren't escaped.
There's no check to stop the caller adding multiple attributes with the same name.
You shouldn't raise an exception class, you should raise an instance of that class (passing a suitable error message to the constructor).


This will add the use of LINQ to clean up the code the way you want:

private TreeNode GetNodeAddress(cls_Transactions trPassedInTransaction)
{
    //a predicate to pass to the FirstOrDefault method
    Func<cls_Transactions,Boolean> filter = null;
    switch (trPassedInTransaction.sMessageType)
    {

        case "Q":
        case "8b":
                 filter = x => trPassedInTransaction.sExecID == x.sExecID;
            break;
        case "3":
                 filter = x => trPassedInTransaction.iMsgSeqNum == x.iMsgSeqNum;
            break;
        default:
                 filter = x => trPassedInTransaction.sClOrderID == x.sClOrderID;
            break;
    }

    cls_Transactions result = cls_GlobalVariables.transList.FirstOrDefault(filter);
    return result != null ? result.tnAddress : null;
}

As an explanation, the switch statement has just been converted to use a predicate, which is a function type where it passes one parameter (in this case a cls_Transactions) and returns true/false.

The FirstOrDefault method is shorthand for the foreach loop and return, foreach-ing through the elements and using the predicate to determine if it meets the required condition, if none meet the required condition it will return a default value (in the case null).

You can use the First method also, which will throw an exception if nothing is found :)


Algorithm

You seem to essentially be doing linear regression with a least absolute deviations optimisation criterion. There are various standard approaches, although I'm not entirely sure about their applicability.

Problem: the task implemented by this code is not well specified. The precision variable serves to quantise the gradient and intercept of the line, but it's impossible to tell from the given specification and comments whether this quantisation is inherent to the problem domain or whether it's there to control the runtime of the search.

If the quantisation is inherent then some of the standard techniques will give starting points but you'll need to test the four nearest valid parameters (rounding each parameter up and down).

Given the size of your data, the approach which tries all lines through two points is probably going to be the most efficient, but again I'm not sure whether the real scenario has a larger dataset.

Code

start_time = datetime.now()
...
print("That run took:", datetime.now() - start_time)

I believe that timeit is the standard way of doing this in Python.

for adder in range(int(max_adder / precision)):
    for multiplier in range(int(max_multiplier / precision)):
        ...
                result[0] * (multiplier*precision) + (adder*precision) - result[1])

It took some thought to decipher the intent here, especially since precision's meaning is not documented. It would be clearer to use numpy.arange or to implement something similar.

print("adder: {:0.3f}".format(1 / (best_setting[1] * precision) if best_setting[1] else 0))
print("multipliertiply: {:0.3f}".format(1 / (best_setting[2] * precision) if best_setting[2] else 0))

Huh? Where did those reciprocals come from? Also, you seem to have started changing multiply to multiplier and got distracted part-way through.


Trapezoidal rule to approximate the integral of x^2

Avoid variable names that collide with built-in functions

sum is a built-in function.  Redefining it causes unconventional behavior:

>> sum([1 2 3])

ans =

     6

>> sum = 0.0

sum =

     0

>> sum([1 2 3])
Index exceeds matrix dimensions.

>> clear all
>> sum([1 2 3])

ans =

     6

Idiomatic MATLAB

The whole point of using MATLAB, rather than C, is that the language is designed to work on many values at once.  Therefore, you should avoid looping wherever possible, and let MATLAB do its job on vectors.

% Givens
n = 5                                  % number of subdivisions
a = 1.0                                % x coordinate left endpoint
b = 2.0                                % x coordinate right endpoint

x = linspace(a, b, n)                  % x coordinates of samples
y = x .^ 2                             % y coordinates of samples
sum_y = sum(y) - (y(1) + y(end)) ./ 2  % sum y coordinates, taking just half of endpoints
dx = (b - a) / (n - 1)                 % width of each trapezoid
area = sum_y * dx

Reinventing the wheel

For your information, MATLAB has built-in support for numerical integration:

>> integral(@(x) x .^ 2, 1, 2)

ans =

    2.3333


So essentially, you want to layout an array of items in a 2D grid. This problem can be solved by using division and remainder operations to calculate the coordinates.

x is the remainder of dividing the index by maxX
y is the remainder of dividing by maxY the result of dividing the index by maxX.
A new page made is when both x and y are 0

Here's a rough sketch of how it looks:

let i = item index
let maxX = 5
let maxY = 6
let x = i % maxX
let y = (i / maxX) % maxY
let p = !(i % (maxX * maxY))

i: 0 1 2 3 4 5 6 7 8 9 ... 29 30 31 32 33 34 35
x: 0 1 2 3 4 0 1 2 3 4 ... 4  0  1  2  3  4  0
y: 0 0 0 0 0 1 1 1 1 1 ... 5  0  0  0  0  0  1
p: 1 0 0 0 0 0 0 0 0 0 ... 0  1  0  0  0  0  0

In code, this would be:

const griditems = []

const pageconstants = {
 grid:{
   x: 5, // 5 across
   y: 6, // 6 down
 }
}

const doc = new PDFDocument({
  layout : 'portrait',
  width: 612,
  height: 792,
  autoFirstPage: false
})

const getX = i => i % pageconstants.grid.x
const getY = i => Math.floor((i / pageconstants.grid.x) % pageconstants.grid.y)
const isNewPage = i => !(i % (pageconstants.grid.x * pageconstants.grid.y))

const positions = griditems.forEach((item, index) => {
  const x = 100 * getX(index)
  const y = 100 * getY(index)

  if (isNewPage(index)) createNewPage(doc)

  addGridItem(doc, { x, y }, item)
})


Averages and standard deviations for a Knn application

As others mentioned in comments, you should follow the .Net naming guidelines. It will make your code consistent with all other .Net code.
Try to avoid abbreviated names like KNN, because they can be confusing. And if that's supposed to mean k-nearest neighbors, then I don't see how does your class compute that.

This applies also to names like numK.
Computing some statistics on your data should be separate from parsing inputs. So the constructor of KNN should take directly numK and dataSet and it should be the job of its caller to parse the inputs.
If the common approach is to create a DataRow once and then never change it again, consider making it immutable: make the property setters private and create a constructor that can be used to set them.

You could also add a constructor from an array of doubles, as an counterpart of ToArray().
Both your GetAverage() and GetStdDev() follow the same pattern. I would try to abstract away this pattern into a separate method, to avoid repetition:

public static DataRow AggregateRows(
    this IList<DataRow> rows, Func<IEnumerable<double>, double> func)
{
    return new DataRow
    {
        Sun = func(rows.Select(row => row.Sun)),
        Temp = func(rows.Select(row => row.Temp)),
        Humidity = func(rows.Select(row => row.Humidity)),
        Wind = func(rows.Select(row => row.Wind))
    };
}

With this, both methods can be significantly simplified using the LINQ method Average():

public DataRow Average()
{
    return dataSet.AggregateRows(values => values.Average());
}

public DataRow StdDev()
{
    return dataSet.AggregateRows(
        values =>
        {
            var average = values.Average();
            var variance = values.Average(value => Math.Pow(value - average, 2));
            return Math.Sqrt(variance);
        });
}

Note that the structure of the expression for computing variance is very similar to the way it's normally written: E[(X - E[X])2].

Also, if you do it this way, you won't need the ToArray() method anymore.
If you have many types whose ToString() follows the same pattern, you could implement it just once using reflection and then use that implementation everywhere.


I'm going to go with no. There's at least two responsibilities in your description alone:

Determine accounts that are about to expire due to inactivity.

and

Notify users of a situation (in this case, the inactivity expiry).

And then in your code, you have a third:

Disable expired account.

I can potentially see the first and third items being in a class together. But user notifications lumped into this smells and likely should be separated.


The implied any aspect of the code posted is fair game for feedback and criticism justifies asking on CR even without an(y) explicit question. I'm taken against guessing what any piece of code is there for: Why another python quicksort? doesn't get answered in the code.
While the docstring looks charming, the parameter to quicksort() is over-specified: everything needed is "subscripting" to get&set items and comparable items. (Numeric items could be deemed handy for picking as a pivot the mean value of several.)
The code mentions neither iterative nor in-place:
quicksort() should be specified to return its (ordered) parameter.

clean, like beauty, lies in the eye of the beholder - to mine, both are close regarding code. I like python for its ability to express things with minimum ado.
(I don't quite like elem_idx&pivot_idx - sometimes use up&down.)

In demonstration code, it seems to have grown conventional to factor out partitioning the current sequence from quicksort().

True? The code doesn't use indexes_stack as a stack. As far as in-place means o(n) space (in addition to output is where input used to be), the implementation presented is not in-place.

More efficient? Sure -

Space: handle the smallest partition first (with impeding out-of-memory, this is a correctness issue)
Time:

choice of pivot is pivotal, using a value from either end of the partition disastrous for pre-ordered input.
Hoare partition scheme instead of Lomuto - three-way if lots of repeated values are to be expected
don't bother with less than two items, better yet:
use a different algorithm for small partitions
don't push the top-priority partition to immediately pop it

In stead of further ranting (keeping elem, elem_idx & pivot_idx for recognition value):

# non-recursive quicksort - re-inventing the wheel finger exercise

# docs.python.org tutorial:
# To add an item to the top of the stack, use append()
class stack(list):
    ''' push() to add an item to the top of the stack '''
    push = list.append

# non-recursive quicksort
def quicksort(items):
    """
    Sort a sequence using the quick-sort algorithm.

    :param items: the sequence to be sorted
    :return: items, sorted
    """
    nItems = len(items)
    if nItems < 2:
        return items
    todo = stack([(0, nItems - 1)])
    while todo:
        elem_idx, pivot_idx = low, high = todo.pop()
        elem = items[elem_idx]
        pivot = items[pivot_idx]
        while pivot_idx > elem_idx:
            if elem > pivot:
                items[pivot_idx] = elem
                pivot_idx -= 1
                items[elem_idx] = elem = items[pivot_idx]
            else:
                elem_idx += 1
                elem = items[elem_idx]
        items[pivot_idx] = pivot

        lsize = pivot_idx - low
        hsize = high - pivot_idx
        if lsize <= hsize:
            if 1 < lsize:
                todo.push((pivot_idx + 1, high))
                todo.push((low, pivot_idx - 1))
        else:
            todo.push((low, pivot_idx - 1))
        if 1 < hsize:
            todo.push((pivot_idx + 1, high))
    return items

if __name__ == '__main__':
# run the sorting function
    from random import randint
    for _ in range(99):
        test = [str(randint(0, 100)) for _ in range(randint(15, 99))]
        assert (quicksort(test[:]) == sorted(test)), test


Critique Request: Reversing a singly linked list

This could be done simpler and more efficiently. This only requires one iteration through the list:

public static LinkedList reverse(LinkedList Node) {
    LinkedList previous = null;
    while (Node != null) {
        LinkedList next = Node.next;
        Node.next = previous;
        previous = Node;
        Node = next;
    }
    return previous;
}

On another note, it is more common for package names to be all lowercase and for local variable and parameter names to be camel case. For example:

package linkedlists;

public static LinkedList reverse(LinkedList node) {

LinkedList headNode = new LinkedList(1);


My main tip is to use break and continue to control the flow of your while loops rather than having a bunch of extra bools in the loop condition.  For example, instead of:

  restart = True
  while (bank_balance >= 25 and restart == True):

    print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
    print (f"Betting $25")
    bank_balance-=25

    deal_hand = play_hand(player_name)

    play=input("Type 'y' to play again, or type any key to quit" + '\n')

    if (play == 'y'):
      restart=True
      print('\n')
    elif (play != 'y'):
      print('Thanks for playing ')
      restart=False

get rid of the restart flag and do:

  while bank_balance >= 25:

    print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
    print (f"Betting $25")
    bank_balance-=25

    deal_hand = play_hand(player_name)

    play=input("Type 'y' to play again, or type any key to quit" + '\n')

    if (play == 'y'):
      print('\n')
    elif (play != 'y'):
      print('Thanks for playing ')
      break

(Also, for a true/false value instead of saying flag == True or flag == False just say flag or not flag.)

You can apply this same principle to the loops in play_hand where you're checking several bools in each while loop:

  player_bust = False
  dealer_bust = False

  while True:
    hors= input(f"Type 'h' to hit and 's' to stay ")
    if (hors == 'h'):
      new_card= random.randint(1, 11)
      player.append(new_card)
      print(f'{name} pulled a {new_card}')
    elif (hors == 's'):
      print('stay')
      break
    print(f'Dealer total is {sum(dealer)}')
    print(f"{name}'s cards are", *player)
    print(f"{name}'s total is {sum(player)}", '\n')
    if sum(player) > 21:
      player_bust = True
      break

  if not player_bust:
    while sum(dealer) > 17:
      dealer.append(random.randint(1, 11))
      print('The dealers total is', sum(dealer), '\n')
  if sum(dealer) > 21:
    dealer_bust = True

  if player_bust:
    print("You busted!")
  elif dealer_bust:
    print("You win!  The dealer busted!"
  elif sum(dealer) > sum(player):
    print("The dealer wins!")
  elif sum(player) < sum(dealer):
    print("You win!")
  else:
    print('Its a Tie! ')

The idea is to minimize the number of conditions that each check depends on; it gives you less to keep track of as you read your code and try to figure out what it's going to do in any given situation.


Superscript all numeric characters after ^ in an excel cell

Formatting individual characters in a string is relatively slow.  My solution convert the exponents to superscript using Ascii and Unicode characters.  This allows me to work with the values in an array and then write it back over the original range.

Using characters code took 0.79 seconds to process 10,000 cells compared to 42.05 using formatting individual characters.  The file size increased by 14KB using the character codes and 50KB using character formatting.

Before                                                          After

Code to Convert Exponents to SuperScript Characters

Function convertExponentsToSuperScript(Text As String, Optional ExponentChar As String = "^") As String
    If InStr(Text, ExponentChar) = 0 Then
        convertExponentsToSuperScript = Text
        Exit Function
    End If
    Dim newText() As String
    ReDim newText(Len(Text) - UBound(Split(Text, ExponentChar)))

    Dim exponentChars() As Variant
    exponentChars = Array(ChrW(&H2070), Chr(185), Chr(178), Chr(179), _
                          ChrW(&H2074), ChrW(&H2075), ChrW(&H2076), ChrW(&H2077), _
                          ChrW(&H2078), ChrW(&H2079))

    Dim textIndex As Long, newTextIndex As Long
    Dim ch As String
    Dim flag As Boolean

    For textIndex = 1 To Len(Text)
        ch = Mid(Text, textIndex, 1)
        If ch = ExponentChar Then
            flag = True
        Else
            newTextIndex = newTextIndex + 1
            If flag Then
                If IsNumeric(ch) Then
                    ch = exponentChars(ch)
                Else
                    flag = False
                End If
            End If

            newText(newTextIndex) = ch
        End If
    Next

    convertExponentsToSuperScript = Join(newText, "")
End Function

Test Code

Sub TestConvertExponentsToSuperScript()
    Dim target As Range
    Dim results As Variant
    Set target = Selection ' getTestRange(10000)
    results = target.value

    Dim t As Double: t = Timer

    Dim r As Long
    For r = 1 To UBound(results)
        results(r, 1) = convertExponentsToSuperScript(CStr(results(r, 1)))
    Next

    target.value = results

    Debug.Print Round(Timer - t, 2)
End Sub

Function getTestRange(TestRows As Long) As Range
    Dim results() As String
    ReDim results(1 To TestRows, 1 To 1)
    Dim r As Long
    For r = 1 To UBound(results)
        results(r, 1) = "O2 Permeability [cm^" & WorksheetFunction.RandBetween(0, 1000) & "/m^" & WorksheetFunction.RandBetween(0, 1000) & "]"
    Next
    Application.ScreenUpdating = False

    With Worksheets.Add
        .Range("A1") = "Test Data"
        With .Range("A2").Resize(UBound(results))
            .value = results
            Set getTestRange = .Cells
        End With
    End With
End Function


I would do six changes:

Better variable names, especially for the arguments
Remove unnecessary temporary array
Handle negative numbers
Initialize temporary array with memset instead of a loop.
Comments with pre and post conditions
Dynamically allocate the temporary array to avoid problems with the stack for large arrays.

The code looks like this:

/* Preconditions:
   array is a pointer to the array that should be sorted
   length is the number of elements in the array

   Postconditions:
   array is sorted
*/
void sort(int *array, size_t length) {
    if(!array || length<1) return;

    int max = array[0];
    int min = max;

    for (int i = 0; i < length; i++) {
        if(max < array[i]) max = array[i];
        if(min > array[i]) min = array[i];
    }

    const size_t range = max - min + 1;
    const size_t size = range * sizeof *array;
    int *tmp = malloc(size);
    if(!tmp) { /* Handle allocation error */ }
    memset(tmp, 0, size);

    for (int i = 0; i < length; i++) tmp[array[i] - min]++;

    int index = 0;
    for (int i = 0; i < range; i++) {
        for (int j = 0; j < tmp[i]; j++) {
                array[index] = i + min;
                index++;
        }
    }
    free(tmp);
}


Check if list contains a pair which adds up to a given sum

If you're worried about efficiency you could copy the Array into a Vector or use an index instead of paring down the input.


Choosing between 2 Fibonacci alternatives

You can compute fibonacci numbers with both time and space complexity O(1).

(n) => ((Math.Pow(phi,n) - Math.Pow(1-phi, n)) / Math.Sqrt(5);

where phi is the golden ratio:

(1 + Math.Sqrt(5)) / 2

But if you needed to iterate fibonacci numbers one after the other, I would use an "iterator", then every other number would also be generated in O(1) and it would be better then the double formula.


Limit fgets input to up to a certain number of characters

This would obviously be better as a function, so we can call with different parameters.
Instead of repeating the constant 12 in the fgets() call, we could simply use sizeof v.  Then it remains consistent if we change v.
Instead of strcspn() with only one character, I'd prefer strchr().  Conveniently, that returns a null pointer if not found, so we don't need to calculate the length to search.  And we shouldn't repeat the search to replace the newline with null character.
Error messages should go to stderr, not stdout.
We can skip the rest of line with a simple scanf("%*[^\n]") (note the * to suppress assignment).  That would replace the ch loop.


Baby-sitting bash script using DVD drive

These days a -T (toggle) argument exists. That allows us to make this a lot neater:

watch -n0 eject -T

You can alter the delay between rocks by changing the -n0 argument.

  watch is used to run any designated command at regular intervals.

http://www.linfo.org/watch.html