Simple Rock, Paper, Scissors Python Game I tried to learn Python during the weekend and after getting some knowledge decided to make a small rock-paper-scissors game. I would be grateful for your input on how I could improve my code. All feedback is highly appreciated.

import random

def round_winner(choice):
    ai_chosen = str(random.randint(1, 3))
    print(f'AI chose {ai_chosen}')

    if choice == '1' and ai_chosen == '2':
        return 'ai'
    elif choice == '2' and ai_chosen == '3':
        return 'ai'
    elif choice == '3' and ai_chosen == '1':
        return 'ai'
    elif choice == ai_chosen:
        return 'tie'
    else:
        return 'player'

def display_round_winner(winner):
    if winner == 'tie':
        print('This round is tied!')
    else:
        print(f'The winner this round is the {winner.upper()}')

    print(f'''
    Current points as follows:
    Player: {counter['player']}
    AI: {counter['ai']}
    Rounds Tied: {counter['tie']}
    ''')

def score_checker():
    global game_ongoing
    for key, value in counter.items():
        if value == 2:
            print(f'{key.upper()} wins the game!')
            game_ongoing = False

def initializer():
    global counter
    message = '''
    Please choose one of the following:
    1: Rock
    2: Paper
    3: Scissors
    '''

    print(message)

    choice_of_obj = input('What will it be: ')
    if choice_of_obj in ['1', '2', '3']:
        winner = round_winner(choice_of_obj)
        counter[winner] += 1
        display_round_winner(winner)
        score_checker()
    else:
        print('Out of bounds')

counter = {
    'player': 0,
    'ai': 0,
    'tie': 0
}

game_ongoing = True

while game_ongoing:
    initializer()

You ask the player to enter 1, 2 or 3 for Rock, Paper or Scissors.  When you tell the player what the AI choose, you say it was a 1, 2 or a 3.  It would be friendlier if you said what they choose.  You could do this with a dictionary that translates the abbreviated choice into the actual item.

choices = { '1': 'Rock', '2': 'Paper', '3': 'Scissors' }

def round_winner(choice):
    ai_chosen = ...
    print(f'AI chose {choice[ai_chosen]}')
    ...

Also, you could use that dictionary to print out the menu for the player, instead of hard-coding it:

    print('Please choose one of the following:')
    for choice, item in choices:
        print(f'{choice}: {item}')

You are using “ai”, “player”, and “tie” as keys for your counter dictionary, and always printing out winner.upper() when you print out a winner.  You could just use “AI”, “PLAYER” and “TIE” as the dictionary keys, avoiding the need for the .upper() calls.

score_checker is an odd name.  Perhaps one of the hardest things about programming is coming up with good names.  check_for_game_winner might be better.

Using global is almost always bad.  You just need to pass a true/false value back to the caller to indicate if the game is over.   Use a return statement.  Ie, inside if value == 2:, add a return True statement.

initializer is another terrible name.  play_round would be better.

Checking for the overall winner inside play_round is confusing responsibilities.  The play_round function doesn’t know it is being called in a loop, if at all.  It should be removed from here.

global counter is again a bad idea.  You could simply pass the counter in as an argument.

Instead of having the game code run directly, you should add a play_games function, and move the counter initialization code and loop inside that.  With other changes, above, it might look like:

def play_games():
    counter = { 'PLAYER': 0, 'AI':0, 'TIE': 0}
    while True:
        play_round(counter)
        if check_for_game_winner(counter):
            break

The file should only execute code if the file is the main program.  If the file is imported into another file, you wouldn’t want the code to automatically run.  The following guard is usually used for this:

if __name__ == '__main__':
    play_game()

Your model of storing the player’s & AI’s moves as strings is perhaps not the best.  If you used integers, you could perform the rock beats scissors beats paper beats rock test with modulo arithmetic:

if ai_choice % 3  == (choice + 1) % 3:
    # the AI won


Create custom Queue class with O(1) Enqueue and O(1) Dequeue I am implementing a Queue class in C# using a Node/LinkedList class that I also implemented, and I wonder if there is a way to implement the enqueue and the dequeue methods, both in algorithmic efficiency of \$O(1)\$.

In the Queue class I have a field of the tail and the head, and I managed to implement the enqueue method in \$O(1)\$, but the dequeue is \$O(n)\$.

This is the code for the Node and the Queue classes:

public class Node<T>
{
    #region Fields

    private Node<T> next;
    private T data;

    #endregion Fields

    #region Constructors

    public Node(T data, Node<T> next)
    {
        this.data = data;
        this.next = next;
    }

    public Node(T data) : this(data, null)
    {

    }

    #endregion Constructors

    #region Properties

    public Node<T> Next
    {
        get { return next; }
        set { next = value; }
    }

    public T Data
    {
        get { return data; }
        set { data = value; }
    }

    #endregion Properties

    #region Methods

    public bool HasNext()
    {
        return next != null;
    }

    #endregion Methods
}

public class Queue<T>
{
    private Node<T> head;
    private Node<T> tail;

    public Queue()
    {
        head = null;
        tail = null;
    }

    public void Enqueue(T data)
    {
        if (IsEmpty())
            head = new Node<T>(data);
        else if (tail == null)  // There is only one element in the queue
            tail = new Node<T>(data, head);
        else
            tail = new Node<T>(data, tail);
    }

    public T Dequeue()
    {
        if (IsEmpty())
            throw new InvalidOperationException("The queue is empty");

        T data = head.Data;

        if (tail == null)  // There is only one element in the queue
        {
            head = null;
            return data;
        }

        Node<T> temp = tail;

        while (temp.Next != head)  // Get the previous Node of the head
            temp = temp.Next;

        temp.Next = null;
        head = temp;

        if (tail == head)
            tail = null;

        return data;
    }

    public T Head()
    {
        if (IsEmpty())
            throw new InvalidOperationException("The queue is empty");

        return head.Data;
    }

    public bool IsEmpty()
    {
        return head == null;
    }
}

This is your bottleneck in retrieving the new head at removal, which can not be avoided in a Singly-Linked structure, so it's \$O(n)\$.

while (temp.Next != head)  // Get the previous Node of the head
    temp = temp.Next;

Doubly-Linked

If you want fast removal \$O(1)\$, you can do so at the cost of slightly slower insertion. You'd need to augment the queue to a doubly linked queue:

var previous = head.Previous;
head.Previous = null;
head = previous;
head.Next = null;

Make sure at insertion, you'll set both Previous as Next references on the relevant nodes.

Circular Doubly-Linked

If you make the queue circular, you don't even need to store the tail, only the head. The tail would be head.Previous; In case of a single element, since it's circular, head.Previous would point to head. Make sure in iterators to terminate at head, instead of at null.


Improving CSV filtering with Python using regex Consider a .csv file that contains a set of video names like so:

"There are happy days","1204923"
"Beware of ignorance","589636"
"Bloody Halls MV","258933"
"Dream Theater - As I Am - Live in...","89526"

The intent of the code I built is to filter items in the csv depending on the list of excluded items. Therefore, if the name of the video contains a word in the list of excluded items, it'll be rejected for saving. The following is the code:

exclude_list = ["mv","live","cover","remix","bootleg"]

data_set = []

with open('video_2013-2016.csv', 'rb') as f:

    reader = csv.reader(f)

    for row in reader:
        # Only record videos with at least 100 views
        if int(row[1]) > 99:

            # A test list that holds whether the regex passes or fails
            test_list = []

            for ex in exclude_list:
                regex = re.compile(".*("+ex+").*")

                if regex.search(row[0]):
                    test_list.append(False)
                else:
                    test_list.append(True)

            # Depending on the results, see if the row is worthy of saving
            if all(result for result in test_list):
                data_set.append(row)

I know the code I wrote above is quite inefficient, and I've seen examples of list comprehensions that can do a better job, but I do not quite understand how list comprehension can work in this case. I just hate it that I have to create the regex variable many times and it feels like a waste of resource.

The CSV file contains text in some text encoding, and should not be opened in binary mode.

You should construct one regular expression to find any of the forbidden words.  It appears that you intended to do a case-insensitive search, but didn't write the code that way.  When constructing the regex, you should escape the strings, in case they contain any regex metacharacters. You don't need .*, since re.search() will look for the pattern anywhere in the string, nor do you need capturing parentheses.

If your comment says 100, then your code should have 100 rather than 99.

I suggest doing a destructuring assignment title, view_count = row to make it clear what each column represents.

with open('video_2013-2016.csv') as f:
    forbidden = re.compile('|'.join(re.escape(w) for w in exclude_list), re.I)
    for row in csv.reader(f):
        # Only record videos with at least 100 views and none of the bad words
        title, view_count = row
        if int(view_count) >= 100 and not forbidden.search(title):
            data_set.append(row)


Json type-safe builders using jackson-annotations I have created these builders to help creating fluent acceptance tests for my api.

I would really like suggestions for improvements because this is supposed to be a "how to" project on creating acceptance tests.

Questions:
Could this be improved?
Should asJson be catching the exceptions to avoid polluting it's users?
Should the static factory methods be creating the default values or the builders?
Do you like the naming conventions Builder, I feel like they are silly when there is no asJson method but they are still only there to be a part of creating json...

public class HolidayBuilder {

    @JsonProperty
    private String name;

    @JsonProperty
    private String date;

    @JsonProperty
    private String duration;

    public HolidayBuilder withName(String name) {
        this.name = name;
        return this;
    }

    public HolidayBuilder withDate(String date) {
        this.date = date;
        return this;
    }

    public HolidayBuilder withDuration(String duration) {
        this.duration = duration;
        return this;
    }

    public String asJson() {
        try {
            return new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Could not create json: " + e.getMessage());
        }
    }

    public static HolidayBuilder aHoliday() {
        return new HolidayBuilder().withDuration("1d");
    }
}

public class WorkAttributeBuilder {

    @JsonProperty
    private int id;

    @JsonProperty
    private String key;

    @JsonProperty
    private WorkAttributeTypeBuilder type;

    @JsonProperty
    private String name;

    public WorkAttributeBuilder() {
        type = aAttributeType();
    }

    public WorkAttributeBuilder withId(int id) {
        this.id = id;
        return this;
    }

    public WorkAttributeBuilder withKey(String key) {
        this.key = key;
        return this;
    }

    public WorkAttributeBuilder withoutKey() {
        this.key = null;
        return this;
    }

    public WorkAttributeBuilder withType(WorkAttributeTypeBuilder type) {
        this.type = type;
        return this;
    }

    public WorkAttributeBuilder withName(String name) {
        this.name = name;
        return this;
    }

    public String asJson() {
        try {
            return new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Could not create json: " + e.getMessage());
        }
    }

    public static WorkAttributeBuilder aWorkAttribute() {
        return new WorkAttributeBuilder().withName("Some Name");
    }
}

public class WorkAttributeTypeBuilder {

    @JsonProperty
    private String value;

    public WorkAttributeTypeBuilder(String value) {
       this.value = value;
    }

    public String getValue() {
       return value;
    }

    public static WorkAttributeTypeBuilder aAttributeType() {
        return new WorkAttributeTypeBuilder("ACCOUNT");
    }
}

public class WorkAttributeValueBuilder {

    @JsonProperty
    private long worklogId;

    @JsonProperty
    private String value;

    @JsonProperty
    private WorkAttributeBuilder workAttribute;

    public WorkAttributeValueBuilder withWorklogId(long worklogId) {
        this.worklogId = worklogId;
        return this;
    }

    public WorkAttributeValueBuilder withValue(String value) {
        this.value = value;
        return this;
    }

    public WorkAttributeValueBuilder withWorkAttribute(WorkAttributeBuilder workAttribute) {
        this.workAttribute = workAttribute;
        return this;
    }

    public String asJson() {
        try {
            return new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Could not create json: " + e.getMessage());
        }
    }

    public static WorkAttributeValueBuilder aWorkAttributeValue() {
        return new WorkAttributeValueBuilder();
    }
}

Your code is overall pretty nice. A few things I noted:

Upon first reading, I did a double-take at reading the withFoo methods that your fluent API uses. This is because there's an idiom where withFoo is sometimes a "setter" for an immutable object (which creates a new version with the update info). But after that, I read the contents of the methods and it made sense.
This is not the best way to rethrow exceptions:

public String asJson() {
    try {
        return new ObjectMapper().writeValueAsString(this);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Could not create json: " + e.getMessage());
    }
}

Notice that RuntimeException has a constructor which takes a throwable reason as well. Thus it would be much better to implement this like so:

public String asJson() {
    try {
        return new ObjectMapper().writeValueAsString(this);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Could not create json.", e);
    }
}

Don't worry; it still has the message from e. Note that your other classes also have this problem.
What's with the name of this method?

public static HolidayBuilder aHoliday() {
    return new HolidayBuilder().withDuration("1d");
}

What does aHoliday mean? Your other classes have similarly named methods, and I don't understand what they are supposed to do. You should give them proper names.


Authorization checks for editing attributes of a task Model:

class Task extends Model {
}

with fields

protected $fillable = ['message', 'due_time', 'status'];

I've added special functions public function getEditableStateForAttributeName().

In my helper function I check that if method_exists($class, 'getEditableStateForFieldName'), then I check the boolean value returned by this method to decide whether to allow editing this field.

Example:

if( ! $cls->getEditableStateForDueTime() ) {
    return "You can not edit field due time";
}

Real code:

private function isCreator() {
     $user = Auth::user();
     if($user) {
         return $user->id === $this->creator_id;
     }
     return false;
}

public function getEditableStateForMessage() {
     return $this->isCreator();
 }

public function getEditableStateForDueTime() {
     return $this->isCreator();
}

public function getEditableStateForStatus() {
    return $this->isCreator() && $this->status === 'CREATED';
}

Is this a good way to do it or it is very bad design because of hidden dependency on Auth::user()?

What is a better way?

I do not want to put this logic inside controllers because this logic propagates to another models and is universal across application.

I've written some helper functions which facilitates validation of my models

Inside controller I simply write

createValidatorForModel(Task::class)

and it returns new validator with custom errors/custom attributes names/additional checks/etc.

Just like you say, you are hiding dependencies if you have new or call a non-pure function with the x::y($z) syntax.

One way to go around this, is to acknowledge the dependency and take it as a constructor argument, so that the current object doesn't care where it gets its user from, but it knows that it can call isCreator() or such. Some would advice you to take dependencies through setUser(User $u)-like methods, but that would make the object useless between its constructor is called, and until the setUser() method is called, because getEditableStateForMessage() and friends will fail in the meantime.

You should consider attacking problems like this from a TDD point of view: how do I test the current code without having to resort to real data?


Personal questionnaire using JavaScript prompts This is just playing around and practicing javascript. I am learning JavaScript from Codecademy and I practice coding everyday so I can learn much as possible. I have a lot of if statements, prompt boxes, some alert boxes. I just got finished learning about functions and returns. I just don't know how to use the return in a browser for like document.write or even an alert box.

function prompter() {
    var toc = prompt("What do you prefer? Tea or Coffee");
    if ((toc == "tea") || (toc == "Tea")) {

    } else if ((toc == "coffee") || (toc == "Coffee")) {

    }
    var foc = prompt("What do you prefer? Facebook or MySpace");
    if ((foc == "facebook") || (foc == "Facebook")) {

    } else if ((foc == "myspace") || (foc == "Myspace")) {

    }
    document.write("
So you like " + toc + " and " + foc + " that is awesome.
");
}

function pickAColour() {
    var fun = prompt("What is your favorite colour? , mine is red.");
    document.write("
You like the colour " + fun + " that is a nice colour
");
}

function pickANumber() {
    alert("Lets do some math, do you like Math?");
    var pan = prompt("Please pick a number");
    var nap = prompt("Please pick another number");
    var symbol = prompt("Please pick one of the following symbols +  -  *  /");
    pan = parseInt(pan); //The parseInt() function parses a string and returns an integer.
    nap = parseInt(nap); //The parseInt() function parses a string and returns an integer.
    if (symbol == "+") {
        alert("You picked the Add symbol");
        alert("Lets add both these numbers together. " + pan + " " + symbol + " " + nap);
        document.write("Your number is " + (pan + nap) + "");
    }
    if (symbol == "-") {
        alert("You picked the Minus symbol");
        alert("Lets Minus both of these numbers. " + pan + " " + symbol + " " + nap);
        document.write("Your number is " + (pan - nap) + "");
    }
    if (symbol == "*") {
        alert("You picked the Multiply symbol");
        alert("Lets Multiply both these numbers. " + pan + " " + symbol + " " + nap);
        document.write("Your number is " + (pan * nap) + "");
    }
    if (symbol == "/") {
        alert("You picked the Divide symbol");
        alert("Lets Divide both these numbers. " + pan + " " + symbol + " " + nap);
        document.write("Your number is " + (pan / nap) + "");
    }
}

function run() {
    var name = prompt("What is your name?");
    document.write("
Welcome to this special JavaScript page " + name + "
");
    prompter();
    pickAColour();
    pickANumber();
    document.write("Thank You for visting this page");
}

run();

You seem to be on the right track, at least with grasping how to do some basic coding.

Right now, I only see one major issue: document.write()

document.write() is used to build pages out of javascript, something that is both impractical and ill-advised (in almost every situation). Moving forward, you should start building your pages in HTML and use javascript to tweak the page from that point.

To do this, you will want to replace document.write() with document.getElementById(). Lets look at an example:

You have the following HTML block:

Now, to insert text into this block, we would do something like this:

var welcomeElement = document.getElementById('welcome');
welcomeElement.innerHTML = "This is my welcome message!";

There's many things you can do with elements once you have gotten them, but I'll leave that for a later experiment.

At this point, I'll leave you to learn how to update your code. If you get confused or stuck however, you can view my rendition of your code here:

http://jsfiddle.net/danthegoodman/v7gLE/


Python script to extract columns from a CSV file I have a very basic python script that reads a CSV file. I'm importing the csv module setting some empty list variables and getting the data I want. The problem is that I know there is a much more efficient way to get the data I just don't know how to do it and I feel very redundant in creating a reader object multiple times.
The goal of the script is to read the csv and extract fields (header) and column cells under it.
What I'm doing to accomplish this is creating multiple reader objects and looping each object to extract the data.
The csv file is simple and will have more columns in the future:
routers,servers
192.168.1.1,10.0.1.1
192.168.1.2,10.0.1.2

The code is simple:
import csv
filename='Book2.csv'
fields=[]
rows=[]

with open(filename, 'r') as csvfile_field:
    csvreader_group = csv.reader(csvfile_field)
    fields=next(csvreader_group)
    group1=fields[0]
    group2=fields[1]

 with open(filename, newline='') as csvfile_row1:
    csvreader_server = csv.DictReader(csvfile_row1)
    #print(str(group))
    print(group1)
    for row1 in csvreader_server:
        server1 = row1[group1]
        print(server1)

 print('\n')
 with open(filename, newline='') as csvfile_row2:
    csvreader_server = csv.DictReader(csvfile_row2)
    print(group2)
    for row2 in csvreader_server:
        server2 = row2[group2]
        print(server2)

The results are:
routers
192.168.1.1
192.168.1.2

servers
10.0.1.1
10.0.1.2

Can someone review this and suggest a more efficient way to extract the data without the opening of the same file multiple times with the same results?

Here's how I would do it, without Pandas:
import csv

filename = 'Book2.csv'

with open(filename, 'r') as csvfile:
    reader = csv.reader(csvfile)
    fields = next(reader) # Reads header row as a list
    rows = list(reader)   # Reads all subsequent rows as a list of lists

for column_number, field in enumerate(fields): # (0, routers), (1, servers)
    print(field)
    for row in rows:
        print(row[column_number])
    print('\n')


"Best before" puzzle I'm new To C++ and decided to have a go at the Spotify challenges on their website.

I have now finished but I get the feeling my code is just terrible. I'm guessing it would be very hard for someone else to read and I feel like there are much better ways to code this.

Their "Best Before" puzzle asks: Given a possibly ambiguous date written in "A/B/C" format, where A,B,C are integers between 0 and 2999, interpret them as M/D/Y or D/M/Y or whatever common date format. Pick the interpretation that yields the earliest possible legal date between Jan 1, 2000 and Dec 31, 2999 (inclusive) in "YYYY-MM-DD" format.  If the string cannot be interpreted as a valid date, state so.

Here is my code for the best before puzzle:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;

int Year;
int Month;
int Day;

stringstream ss;
string input;
string in;
bool loop=true;
int date[4];
bool DateFound=false;

void Check_date();
void Check_date()
{

    if(DateFound==false)
    {
    //Check if valid Year
    if (date[1]<2999 && date[1]>0 && date[2]>0 && date[3]>0)
    {   //check months & days are valid
        if(date[2]==1 || date[2]==3 || date[2]==5 || date[2]==7 || date[2]==8 || date[2]==10 || date[2]==12){if(date[3]<=31){DateFound=true;}}
        if(date[2]==4 || date[2]==6 || date[2]==9 || date[2]==11){if(date[3]<=30){DateFound=true;}}
        //Check For Leap Year
        if (date[2]==2)
        {   if(date[3]<28)DateFound=true;
            if(date[1]%4==0 && date[3]<=29)DateFound=true;
            if(date[1]%100==0 && date[1]%400!=0 && date[3]>28)DateFound=false;
        }

    }
    if(DateFound==true){Year=date[1]; Month=date[2]; Day=date[3];if(Year<1000){Year=Year+2000;} if(Month<10){}}

    }

}

void SwitchDate(){int temp; temp=date[2]; date[2]=date[3]; date[3]=temp; Check_date();};
void ShiftDate(int places)
{   if(places==1)
    {
    int temp; temp=date[3]; date[3]=date[2]; date[2]=temp; temp=date[1]; date[1]=date[2]; date[2]=temp;  Check_date();
    }
    if(places==2)
    {
    int temp; temp=date[1]; date[1]=date[2]; date[2]=temp; temp=date[2]; date[2]=date[3]; date[3]=temp; Check_date();
    }
};

int main ()
{
    //Main Loop
    while(loop==true)
    {

    cout <<"Please Enter a date \n";
    cin>>input;
    cout<<endl;

    for (int x=0, y=1; y<=3; y++, x++)
        {
            while (input[x] !='/' && x !=input.length()) ss<<input[x++];
            ss>> date[y];
            ss.clear();
        }

    //order small medium large
    for (int x=3, temp; x!=0; x--)
    {
        if (date[x] < date[x-1])
            {   temp=date[x-1];
                date[x-1]=date[x];
                date[x]=temp;
            }
        if (x==1 && (date[2] > date[3] ))
                {
                    temp=date[3];
                    date[3]=date[2];
                    date[2]=temp;
                }

    }

    Check_date();
    SwitchDate();
    ShiftDate(1);
    SwitchDate();
    ShiftDate(2);
    SwitchDate();

    //PRINT
    if(DateFound==true)
    {
    cout <<"The smallest valid date is: ";
    cout <<setw(2)<<setfill('0')<<Year; cout<<"-";
    cout <<setw(2)<<setfill('0')<<Month; cout<<"-" ;
    cout <<setw(2)<<setfill('0')<<Day;
    cout<<endl;
    }
    else cout<<date[1]<<"/"<<date[2]<<"/"<<date[3]<<" Is illegal \n";

    DateFound=false;
    cout <<"Again? 'Y' or 'N' \n";
    cin >>in;
    cout << endl;
    if(in=="y" || in=="Y"){loop=true;}
    if(in=="n" || in=="N"){loop=false;}
    }//End of Loop
}

You should avoid using global variables. If you import this code into a future project it might cause problems -- name conflicts etc.

If you must do this, put them in an anonymous namespace so that they're only in scope for this file:

namespace
{
    int my;
    int globals;
    int defined;
    int here;
}

The declaration of Check_date() is not necessary here:

void Check_date();
void Check_date()
{

This could perhaps written better:

for (int x=0, y=1; y<=3; y++, x++)
{
    while (input[x] !='/' && x !=input.length()) ss<<input[x++];
    ss>> date[y];
    ss.clear();
}

There is little point using x in the for loop as you don't have an exit condition for it. Also, I would prefer a more meaningful name.

Instead, perhaps:

int inputPos = 0;
for(int dateIndex = 1; dateIndex <= 3; ++dateIndex)
{
    while(input[inputPos] != '/' && inputPos != input.length())
    {
        ss >> date[dateIndex];
        ss.clear();
    }
    ++inputPos;
}

More generally you've written this in a very C-like style -- I would have defined a type (class) for Date, which would have month and day members. Then the logic for whether month lengths are valid can be encapsulated properly.

You could also encapsulate the read-from-stream code using an iostreams extractor.


Improving a JS object "framework" I have this simple object setup in JavaScript - Full code on jsbin

I'll break it up below, but the question(s) -

Does it break? I mean, I'm sure we can find a interesting case where this would be broken, but how much work do we have to do before it breaks?
I started out thinking I needed to explicitly store a list of classes (variable _heap below; yes, calling it heap is rather overdone for what it is) to keep the inheritance tree and avoid memory leaks when an object is instantiated multiple times. I've got the feeling it's unnecessary but I haven't found how to not use it...
Any points on how this could be better really! Is this very contrived code?

I'm trying to allow common object creation technique like:

function FourLegged() {

   this.CRY = "ffffhhhh!";

  // method
   this.talk = function() {
         writeln( this.CRY);
      };
}

But also to have the class, constructor and inheritance in a one block, as OO languages usually do:

function Cat() {

   // inheritance
   this._parent = FourLegged;

   // constructor
   this.construct =
      function(n) {
         // private var defined in instance
         var name;
         name = n;
         // methods that use private var - Douglas Crockford nethod
         // avoid it, it wastes memory if there are multiple instances
         this.setName = function(n) { name = n; };
         this.getName = function() { return name; };
      };

   // methods will operate in instance context (ie "this" is the instance)
   this.talk =
      function() {
         writeln( this.getName() + " says " + this.CRY);
      };

}

So to do this, I wrap the creation of a new instance:

cat1 = new instance(Cat, "felix");

The wrapper processes the function so as to use the constructor and inheritance, but also maintains the _heap (the class list):

function instance() {
   var c = getConstructor(arguments[0]);
   var args = Array.prototype.slice.call(arguments, 1);
   return new c(args);
}

var _heap = {};

function getConstructor(cls) {
   var cons;
   // try to retrieve from _heap
   if (!(cons = _heap[cls])) {
      // if not already in heap
      var c = new cls();
      if (c._parent) {
         // set up class-superclass relation
         cls.prototype = new instance(c._parent);
         // class has changed, re-intantiate
         c = new cls();
      }
      if (!c.construct) {  // if there is no constructor
         c.construct = function() {}; // make one
      }

      cons =
         function(args) {
            return c.construct.apply(this, args);
         };
      cons.prototype = c;  // set up class-instance relation

      _heap[cls] = cons;
   }
   return cons;
}

My perspective on your questions:

It breaks when you want to change the behavior of all cats, since you do not store functions in the .prototype of the classes. Also, not using .prototype makes your code consume more memory.
There is indeed a standard way of doing this, however it kind of breaks your requirement : "But also to have the class, constructor and inheritance in a one block, as OO languages usually do."
I think vanilla JS does better and is less contrived.

Most of the code I borrowed from this excellent text.

Your FourLegged class would be:

function FourLegged() {
   this.cry = "ffffhhhh!"; //default value
}
//Functions/methods should be part of prototype
FourLegged.prototype.talk = function talk(){
  writeln( this.cry);
};

If you absolutely insist on doing this in 1 block, you could do this :

var FourLegged = (function() {

  function f() {
     this.cry = "ffffhhhh!"; //default value
  }

  f.prototype.talk = function talk(){
    writeln( this.cry);
  };

  return f;
}());

Then the cat would be this ( wrapped in a function, not required )

var Cat = (function() {

  function f(name){

     FourLegged.call(this);

     (function nameProperty( o , name) {
       // private var defined in instance
       var _name = name;
       // methods that use private var - Douglas Crockford nethod
       o.setName = function(name) { _name = name; };
       o.getName = function() { return _name; };
    })(this , name);
  }

  f.prototype = new FourLegged();
  f.prototype.constructor = f;

  f.prototype.talk = function talk() {
    writeln( this.getName() + " says " + this.cry);
  };
  f.prototype.setCry = function setCry( s ) {
    this.cry = s;
  };

  return f;
}());

Your tests will perform exactly the same, except you do not need _parent, _heap, instance() or getConstructor().

Update

A clarification on 'it does not use memory'.When I create objects this way in the console in Chrome :

function FourLegged()
{
   this.CRY = "ffffhhhh!";
   this.talk = function() { writeln( this.CRY); };
}

I find that these object take 88 bytes. ( Take a head snapshot with developer tools ).

When I create objects the following way in the console in Chrome:

function FourLegged()
{
   this.CRY = "ffffhhhh!";
}
FourLegged.prototype.talk = function() { writeln( this.CRY); };

These objects take 48 bytes, and that is because the talk function remains on prototype, it does not get copied over the object.


Authenticating user/password against Active Directory using ASP.NET Identity I am trying to learn how to use ASP.NET Identity. My scenario is that I have to authenticate against Active Directory. For that purpose I am trying to use ActiveDirecotoryMembershipProvider.

What I have to do is:

Authenticate user/password against Active Directory
Check whether user is present in my own database

The way I did it is I configured in my web.config to use ActiveDirectoryMembershipProvider as default membership provider. Then I override PasswordSignInAsync method in my ApplicationSignInManager class (which inherits SignInManager) as follows:

public override Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    var adok = Membership.Provider.ValidateUser(userName, password);
    if (adok)
    {
        var user = UserManager.FindByName(userName);
        if (user == null)
            return Task.FromResult<SignInStatus>(SignInStatus.Failure);
        else
        {
            base.SignInAsync(user, isPersistent, shouldLockout);
            return Task.FromResult<SignInStatus>(SignInStatus.Success);
        }
    }
    else
        return Task.FromResult<SignInStatus>(SignInStatus.Failure);
}

This seems to work, but I think it's not the right way to do it. Can anyone suggest any better way of achieving this?

SignInAsync is an async method, and you most likely want to wait for it to complete before returning the SignInStatus. In order to await it, we must declare the method with the async keyword. This also means we can simplify the return statements:

public override async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    if (Membership.Provider.ValidateUser(userName, password))
    {
        var user = UserManager.FindByName(userName);
        if (user == null)
        {
            return SignInStatus.Failure;
        }

        await base.SignInAsync(user, isPersistent, shouldLockout);
        return SignInStatus.Success;
    }

    return SignInStatus.Failure;
}


Reading a file into memory Can you review below code for performance and stability considerations? It is supposed to take a filename or NULL. If it is a filename, read given file into memory. If it is NULL, read from stdin into memory.

struct file_data {
    char *data;
    size_t numChars;
};

/* Read whole file into memory */
struct file_data read_file(char *filename) {
    FILE *f;
    char buffer[BUFFER_SIZE];
    char *data = NULL;
    size_t current_size = 0;
    size_t totalChars = 0;
    size_t nchars;

    if(filename) {
        f = fopen(filename, "r");
    } else {
        f = stdin;
    }

    do {
        data = (char *)realloc(data, current_size + BUFFER_SIZE);
        assert(data);
        current_size+=BUFFER_SIZE;
        nchars = fread(buffer, 1, BUFFER_SIZE, f);
        memcpy(&data[totalChars], buffer, nchars);
        totalChars+=nchars;
    } while(nchars == BUFFER_SIZE);

    struct file_data fd = {data, totalChars};
    return fd;
}

Check return values

You're not making sure fopen isn't failing when opening a file:

f = fopen(filename, "r");

Also check the return value of fread for failure:

  The total number of elements successfully read is returned. If this
  number differs from the count parameter, either a reading error
  occurred or the end-of-file was reached while reading. In both cases,
  the proper indicator is set, which can be checked with ferror and
  feof, respectively. If either size or count is zero, the function
  returns zero and both the stream state and the content pointed by ptr
  remain unchanged. size_t is an unsigned integral type.

const parameters

The function should never modify the contents of the string filename, so declaring the parameter const char *filename is good practice.

How does read_file signal a failure

You're asserting on realloc failure. I usually prefer returning gracefully even on alloc failures and leave it open to the caller to be able to cope and at least shutdown nicely. But that is not necessary in all cases.

However, touching the same area is how the read_file function signals a failure to it's caller? One way would be:

struct file_data fd = {NULL, 0};
return fd;

Or changing the function to:

int read_file(const char *filename, struct file_data *fd)
{
     assert(fd);
     ...
     fd->data = data;
     fd->numChars = totalChars;
     return 0; // On success.
     ...
     return -1; // On failure.
}

Read directly into the data buffer

You're doing unnecessary copying by using memcpy and a separate temporary buffer to read the file contents into.

How you could read it into the data buffer directly instead (getting rid of buffer):

size_t offset = 0;
nchars = fread(&data[offset], 1, BUFFER_SIZE, f);
// TODO: Remember to check nchars for error condition.
offset += nchars;


Find maximum difference between values in an array My task is to use the following pseudocode and improve it (make it run faster). Also I have to analyze the runtime of the given pseudocode and of my new code that i improved.

What does this algorithm do? It finds the smallest and greatest number in an array and creates the difference of them.

Pseudocode (given in task):

Input: Array Y, length n with n >= 2
Output: x (number)
x = 0
for i = 0 to n do
   for j = i + 1 to n do
      if x < A[i] - A[j] then
      x = A[i] - A[j];
      end if
   end for
end for
return x;

My code, improved:

public class Improved
{
    public static void main (String[] args)
    {
        int A[] = {1, 2, 3, 4, 5};
        int min = A[0];
        int max = A[0];

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

            if (max < A[i])
            {
                max = A[i];
            }
        }
        System.out.println(max - min);
    }
}

The only problem I got now is counting the runtime.
I think for the pseudocode, it runs in \$\mathcal{O}(n^2)\$ because of the 2 for loops.
Then my code will run in \$\mathcal{O}(n)\$, since it only has 1 for loop, right? :P
What would be the worst case by the way?

What does this algorithm do? It finds the smallest and greatest number in an array and creates the difference of them.

Nope.

Consider {5, 2, 1}. The pseudo code returns 5 - 1 = 4 which happens to be the difference between the smallest and the largest value.

Now consider {1, 2, 5}. The pseudo code computes 1 - 2, 1 - 5, 2 - 5 and never updates x because all these values are < 0; the pseudo code then returns x, which is still 0. The difference between the largest and the smallest value, however, is still 5 - 1 = 4.


Parse atom RSS feed with xml.dom.minidom I had to parse a blogger RSS feed but I didn't have access to any third party modules like feedparser or lxml. I was stuck with the task of writing a library to parse RSS feeds; challenge accepted. I started by writing an RSS class and then an Entry class. I then realized that my classes only had two methods, one of them being __init__, so I scrapped the OOP approach and went for a more direct approach. I reduced everything down to one function parse_feed. parse_feed takes one positional argument: the URL to the RSS feed.

I'm curious what you think about the way I used type to create classes on the fly.

#-*-coding:utf8;-*-
#qpy:3
#qpy:console

import urllib.request
from xml.dom import minidom

def parse_feed(url):
    # This is what parse_feed returns.
    feed = type('Feed', (object,), {})
    feed.entries = []

    with urllib.request.urlopen(url) as res:
        dom = minidom.parseString(res.read().decode('latin-1'))
        feed.title = dom.getElementsByTagName('title')[0].firstChild.nodeValue
        feed.link = dom.getElementsByTagName('link')[0].getAttribute('href')
        feed.published = dom.getElementsByTagName('published')[0].firstChild.nodeValue

    for element in dom.getElementsByTagName('entry'):
        title = element.getElementsByTagName('title')[0].firstChild.nodeValue
        link = element.getElementsByTagName('link')[0].getAttribute('href')
        author = element.getElementsByTagName('name')[0].firstChild.nodeValue
        published = element.getElementsByTagName('published')[0].firstChild.nodeValue
        updated = element.getElementsByTagName('updated')[0].firstChild.nodeValue
        _id = element.getElementsByTagName('id')[0].firstChild.nodeValue
        category = element.getElementsByTagName('category')

        tags = []
        for node in category:
            tags.append(node.getAttribute('term'))

        article = element.getElementsByTagName('content')[0].firstChild.nodeValue

        entry_dict = dict(
                    title=title,
                    link=link,
                    author=author,
                    article=article,
                    tags=tags,
                    _id=_id)

        feed.entries.append(type('Entry', (feed,), entry_dict))

    return feed

# Example use.
feed_url = 'https://rickys-python-notes.blogspot.com/atom.xml?redirect=false&start-index=1&max-results=1000'
feed = parse_feed(feed_url)
print(feed.title)
print(feed.published)
for entry in feed.entries:
    print(entry.title)
    print(entry.link)

Nope, nope, nope.

feed = type('Feed', (object,), {})
feed.entries.append(type('Entry', (feed,), entry_dict))

The entire point of OOP is to have pre-defined classes, as contracts to follow. Since your classes are always the same, you should just define them with the class keyword.  I recommend attrs to make it look nicely.

In a good design, classes are never created on the fly, out of thin air.  They’re always defined in code, with a set of attributes that should also never change. (I’m not a fan of Python’s lenient style — Java, for example, makes it hard/impossible to create classes and new attributes at runtime.)

Or alternatively, you could make those regular lists of regular dicts.  Not everything needs to be a class.

More complaints:

Entry should not inherit from Feed. They’re two separate, unrelated things.

dom = minidom.parseString(res.read().decode('latin-1'))

99% of feeds in the wild are in UTF-8, and you should check the encoding in the <?xml ?> declaration.


Dynamic array resizing and nesting conditions This function filters a 2D VBA array base on the strKeeper value. Depending on the Boolean toggle it would either retain or skip "rows."

Two questions:

I went at length to size the arr_new in a separate loop to reDim it only once (did not want to put ReDim inside the loop). Is there a better way?
Is there a more efficient way to nest the following:

If (arr_col_k(i, 1) = strKeeper And re_Tain) Or (arr_col_k(i, 1) <> strKeeper And Not re_Tain) Then

Function RemoveRows2D(arr As Variant, k As Long, strKeeper As String, headers As Boolean, Optional re_Tain As Boolean = True) As Variant
'removes rows not equal (re_Tain=False) or equal (re_Tain=True) to strKeeper in col k

Dim i As Long, j As Long, ii As Long, up_new As Long
Dim arr_col_k, arr_new

arr_col_k = Application.Index(arr, 0, k) 'col with strings
up_new = 0 'calc Ubound(arr_new) based on matched
For i = LBound(arr_col_k) To UBound(arr_col_k)
    If (arr_col_k(i, 1) = strKeeper And re_Tain) Or (arr_col_k(i, 1) <> strKeeper And Not re_Tain) Then
        up_new = up_new + 1
    End If
Next
If headers Then up_new = up_new + 1
ReDim arr_new(LBound(arr) To up_new, LBound(arr, 2) To UBound(arr, 2))

i = LBound(arr)
ii = i
If headers Then 'handle header row
    For j = LBound(arr, 2) To UBound(arr, 2)
          arr_new(i, j) = arr(i, j)
    Next
    i = 1 + 1
    up_new = up_new + 1
End If

For i = i To UBound(arr) 'outter loop by rows to find match

    If (arr_col_k(i, 1) = strKeeper And re_Tain) Or (arr_col_k(i, 1) <> strKeeper And Not re_Tain) Then
       ii = ii + 1
       For j = LBound(arr, 2) To UBound(arr, 2) 'inner loop by columns to fill in arr_new row
           arr_new(ii, j) = arr(i, j)
       Next
    End If
Next
RemoveRows2D = Application.Transpose(arr_new)
End Function

Looping through the Array, counting the matches to avoid resizing the return Array is very efficient.

Application.Transpose is not needed because the return array is in the same shape as the original array.

  RemoveRows2D = Application.Transpose(arr_new)

This is correct:

  RemoveRows2D = arr_new

Using Application.Index to slice off the target column is a cool trick but is it really needed?  Not only does it add extra overhead but it adds an extra variable.  In my opinion, arr_col_k is just extra clutter because I don't think that  arr_col_k(i, 1) = strKeeper is any more readable than arr(i, x) = strKeeper.

  arr_col_k = Application.Index(arr, 0, k)

You can remove up_new = up_new + 1 from this loop:

If Headers Then                                   'handle header row
    For j = LBound(arr, 2) To UBound(arr, 2)
        arr_new(i, j) = arr(i, j)
    Next
    i = 1 + 1
    up_new = up_new + 1
End If

Moving forward, the main thing that I think you should focus on is the names of your variables.  Consider arr, k, strKeeper, up_new, arr_col_k, arr_new, what do the names of these variable tell you about the roles that they play?

Compare them to my alternative names.

arr: Data, DataArray, arrData, arrSource, Source, SourceArray
k: col, ColumnIndex
strKeeper:  Match

I use Match because it is used in many VBA and Excel functions.

up_new: Count
arr_col_k: Matches, arrTarget, ???I would have to think about this one.
arr_new:  Results, results, arrResults

I also use 1 or 2 character variable names for all my counters.  I prefer x, x1, y, y1 because  i or l can be tough to differentiate.

RemoveRows2D is basically a 2D version of the built in VBA.Filter function.  Whenever I write a version of a standardized method I start by copying the methods signature from the Object Browser and work from there.  Using the same structure and variable names as the built-in methods will make it easier for others to understand and use yours.

Question: Is there a more efficient way to nest the following:

If (arr_col_k(i, 1) = strKeeper And re_Tain) Or (arr_col_k(i, 1) <> strKeeper And Not re_Tain) Then

Technically, using If and EsleIf blocks is more efficient because the VBA evaluates all the conditions in an If Then statement.  In your case the difference in efficiency is negligible.  Note: In my version of function I use a flag with If and EsleIf blocks because I think that it read better and is easier to debug.

If (arr_col_k(i, 1) = strKeeper And re_Tain) Then

ElseIf (arr_col_k(i, 1) <> strKeeper And Not re_Tain) Then

End If

Function Filter2D(SourceArray, Match As String, ColumnIndex As Long, Headers As Boolean, Optional Include As Boolean = True, Optional Compare As VbCompareMethod = vbBinaryCompare) As Variant()
    Dim count As Long, x As Long, y As Long
    Dim flag As Boolean
    Dim Results() As Variant
    'Adjust the ColumnIndex based on SourceArray Lbound
    'This allows the user to refer to the 1st column of a Option Base 0 array as 1 instead of 0
    ColumnIndex = ColumnIndex - LBound(SourceArray, 2) + 1
    'First loop to count matches
    For x = LBound(SourceArray) To UBound(SourceArray)
        If x = LBound(SourceArray) And Headers Then
            count = count + 1
        ElseIf Include Then
            If StrComp(SourceArray(x, ColumnIndex), Match, Compare) = 0 Then count = count + 1
        Else
            If StrComp(SourceArray(x, ColumnIndex), Match, Compare) <> 0 Then count = count + 1
        End If
    Next

    If count = 0 Then Exit Function

    'Adjust the count based on SourceArray Lbound
    count = count - LBound(SourceArray) + 1
    'Size the Results array to fit the data
    ReDim Results(LBound(SourceArray) To count, LBound(SourceArray, 2) To UBound(SourceArray, 2))
    'Reset count for reuse
    count = LBound(SourceArray)
    'Second loop to transfer the data
    For x = LBound(SourceArray) To UBound(SourceArray)
        If x = LBound(SourceArray) And Headers Then
            flag = True
        ElseIf Include Then
            If StrComp(SourceArray(x, ColumnIndex), Match, Compare) = 0 Then flag = True
        Else
            If StrComp(SourceArray(x, ColumnIndex), Match, Compare) <> 0 Then flag = True
        End If

        If flag Then
            For y = LBound(SourceArray, 2) To UBound(SourceArray, 2)
                Results(count, y) = SourceArray(x, y)
            Next
            count = count + 1
        End If
        flag = False
    Next

    Filter2D = Results
End Function


How can I make my program that calculates π faster? For my first Raku program, I thought it might be a fun challange to port over a program I'd written in C# about two years ago, and I was right: it was.
There's just one problem: while the C# program runs in 5 seconds, the Raku program takes nearly 5 minutes. I think the Raku program is doing more or less the same as the C# code, and so it should be equally fast (or equally slow, depending on how you look at it).
Here's my code:
use v6;

class Point {
    has Num $.x;
    has Num $.y;

    method is-inside-unit-circle(--> Bool) {
        $!x²+$!y² <= 1;
    }
}

sub random-points(Int $count --> Seq) {
    gather for 0..^$count {
        take Point.new(x => 1.rand.Num, y => 1.rand.Num);
    }
}

sub compute-pi(Int $batch --> Seq) {
    my Num $total = 0e0;
    my Num $count = 0e0;

    gather for 0..^∞ {
        my Seq $pointsInside = random-points($batch).grep: *.is-inside-unit-circle;

        $total += $batch;
        $count += $pointsInside.elems;
        my Num $ratio = $count / $total;

        take $ratio * 4;
    }
}

{ say "π ≈ $_" } for compute-pi(100_000).head(500);

And here's part of the output:
% time raku estimation.raku
π ≈ 3.12912
π ≈ 3.12874
π ≈ 3.1326533333333333
…
π ≈ 3.1419357429718877
π ≈ 3.1419323446893785
π ≈ 3.14193696
raku estimation.raku  272,98s user 1,78s system 100% cpu 4:34,76 total

My two questions are:

How can I make it faster?
Is my code idiomatic, and how could I make it more idiomatic?

For completeness' sake, here's the C# code:
using System;
using System.Collections.Generic;
using System.Linq;

internal class Program
{
    internal readonly struct Point
    {
        private readonly double _x;
        private readonly double _y;

        internal Point(double x, double y)
        {
            _x = x;
            _y = y;
        }

        internal bool IsInsideUnitCircle()
        {
            return Math.Pow(_x, 2) + Math.Pow(_y, 2) <= 1;
        }
    }

    internal class PointGenerator
    {
        private readonly Random _random;

        public PointGenerator() => _random = new Random();

        public IEnumerable<Point> GeneratePoints(int count)
        {
            for (var i = 0; i < count; i++)
            {
                yield return new Point(_random.NextDouble(), _random.NextDouble());
            }
        }
    }

    private static IEnumerable<double> ComputePi(int batch)
    {
        var pointGenerator = new PointGenerator();

        var total = 0.0;
        var count = 0.0;

        while (true)
        {
            var pointsInside = pointGenerator.GeneratePoints(batch)
                .Where(point => point.IsInsideUnitCircle());

            total += batch;
            count += pointsInside.Count();
            var ratio = count / total;

            yield return ratio * 4;
        }
    }

    private static void Main()
    {
        foreach (var estimate in ComputePi(100_000).Take(500))
        {
            Console.WriteLine($"π ≈ {estimate}");
        }
    }
}

And part of its output:
% time dotnet run -c Release
π ≈ 3,13948
π ≈ 3,13904
π ≈ 3,138786666666667
…
π ≈ 3,1415373493975904
π ≈ 3,14154501002004
π ≈ 3,14155416
dotnet run -c Release  5,43s user 0,30s system 103% cpu 5,555 total

You random-points sub has a few things which can be removed or simplified.

1.rand returns a Num, so there is no reason to call the method .Num on its result.
Rather than gather for take you can use the xx operator.
You only want a positive number for the count, so declare that with UInt

sub random-points(UInt $count --> Seq) {
    Point.new(x => 1.rand, y => 1.rand) xx $count
}

xx seems to be on the order of 10× faster than gather for take.
The reason is mostly that take works by throwing a CONTROL and gather captures that message.
On my computer that change alone takes it from nearly 9 minutes (8m49.881s) to around 2 and a half minutes (2m27.582s). (The other changes have no meaningful effect on the run time.)
The sweet spot for the gather take feature is where there isn't already a built-in for what you are doing, and the speed doesn't matter as much as the ease of writing it.
You could go to the work of creating your own Iterator class which could speed it up. That is why xx is so much faster, there is already an Iterator class that was created specifically for it.
(Note that I did actually test to see if writing a new Iterator class would help. It didn't help, in fact it was slower.)

There are similar issues in compute-pi.
To start off, there are improvements to be made to gather for 0..^∞.

Don't mix Int and Num endpoints for Range objects if you can help it. 0e0..∞
Don't use for for infinite loops, just use loop

gather loop {

    ...

    take $ratio * 4;
}

I would not store the filtered random-points Seq in a variable, because the only thing you need from it is the count.
my Int $points-inside = +random-points($batch).grep: *.is-inside-unit-circle;

The prefix + operator just coerces to a Numeric value. Obviously the only number that makes sense for a Seq is the same as .elems, the count of elements.
.elems could potentially return a Num, specifically Inf. Considering that would break the rest of the code anyway, I think it's fine to store it in an Int scalar.

Ok now that we are done with the more obvious cleanups we can try to make it faster.
Thankfully changing from gather for take in random-points to xx helped a lot. (No other change had any meaningful change on the amount of time taken.)
The first thing I did at this point was to run the profiler
raku --profile test.raku

There were no obvious slow parts of our code. In fact a good ⅔ of the run time was in the Raku runtime, not our code.
So let's add parallelism to see if we can reduce the time by using more CPU cores.
We could just make the sequence returned from random-points a race sequence to see if it helps.
my Int $pointsInside = +random-points($batch).race.grep(*.is-inside-unit-circle);

After that change it now takes 4 minutes, almost twice the time it took from before that change.
I did mess around with the batch and degree arguments to race, but no combination seemed to improve it meaningfully. At best I made it match the original timing.
So now we know that was a dead-end. random-points.grep was already about as fast as possible.

So let's add the asynchrony to compute-pi instead.
One obvious thing we could do is have a bunch of threads creating the sequences of random-points.grep.
Of course we don't know how many we need to create. So let's give that as an argument.
sub compute-pi(UInt $batch-size, UInt $batch-count --> Seq) {

Now we want to have an existing sequence that we can call race on.
my \batches = ^$batch-count;

Add race to it.
(We don't care about the order of random-points.grep values we get.)
my \batches = (^$batch-count).race(batch => 1);

The reason for the batch argument of 1 is that we know each random-points.grep takes a long time, so we don't want it to batch them together. We also don't want to wait for 64 of them to be calculated before we get any results.
Now to turn that into the sequence of values that we want by using map.
my \batches = (^$batch-count).race(batch => 1).map: {
    +random-points($batch-size).grep(*.is-inside-unit-circle)
}

Rather than have an infinite loop, we will loop over those batches
gather for batches -> Int $pointsInside {

So the last part of the file now looks like this:
sub compute-pi(UInt $batch-size, UInt $batch-count --> Seq) {

    my \batches = (^$batch-count).race(batch => 1).map: {
        +random-points($batch-size).grep(*.is-inside-unit-circle)
    }

    my Num $total = 0e0;
    my Num $count = 0e0;

    gather for batches -> Int $pointsInside {

        $total += $batch;
        $count += $pointsInside;
        my Num $ratio = $count / $total;

        take $ratio * 4;
    }
}

{ say "π ≈ $_" } for compute-pi(100_000, 500);

It now takes just over a minute (1m13.905s) with a cpu time of over 5 minutes (5m19.237s).
Which means we have more than 400% utilization. Which is fairly good on a 4 core CPU, with hyperthreading.

We can gain a bit more if we use native num variables instead of boxed Num variables.
You have to be careful with this as you can actually make it take more time if the value ends up needing to be boxed for an operation.
class Point {
    has num $.x;
    has num $.y;
    ...
}

...

sub compute-pi(UInt $batch-size, UInt $batch-count --> Seq) {

    my \batches = (^$batch-count).race(batch => 1).map: {
        random-points($batch-size).grep(*.is-inside-unit-circle).Num
    }

    my num $total = 0e0;
    my num $count = 0e0;

    gather for batches -> num $pointsInside {

        $total += $batch;
        $count += $pointsInside;
        my num $ratio = $count / $total;

        take $ratio * 4;
    }
}

That final change brings it down to about 42 seconds (0m42.771s) with 4 minutes of CPU time (4m0.929s).
Which also seems to increase the CPU utilization up over 500%.

The biggest improvement was going from gather for take to just xx. Which I'd argue was warranted just for how much it improved the clarity of the code. The other changes were of minimal benefit.
I think to get any significant improvement would require improving the compiler, runtime, or the VM.
Really what we ended up with is fairly fast considering how much of higher level language Raku is than C#, and how few people are working on it.


Chaining promises into a callback I wrote a AWS lambda function which buys €X worth of some currency on an exchange. For this I first have to find out the current price (getAskPrice), then calculate the amount to buy and post the order (buyLimitOrder). I've implemented both operations as promises, buyLimitOrder gets the result of getAskPrice as one of the arguments. The result of buyLimitOrder (if successful) should be returned as the result of the lambda function.

Here's the relevant code fragment:

const getAskPrice = new Promise(function(resolve, reject){

        got(TICKER_URL).then(response => {
            let result = JSON.parse(response.body);
            let ask = Number(result.ask);
            if (!isNaN(ask)) {
                resolve(ask);
            } else {
                throw new Error("Could not parse the ask price from [" + BTCEUR_TICKER_URL + "] response:\n" + response.body);
            }
        }).catch(reject);
});

const buyLimitOrder = function(customerId, key, secret, value, askPrice) {

    let amount = value / askPrice;

    let roundedAmount = Math.ceil(amount * Math.pow(10,5)) / Math.pow(10,5);

    let order = createAuthData(customerId, key, secret);
    order.amount = roundedAmount;
    order.price = askPrice;
    return new Promise(function(resolve, reject) {
        console.log("Buying " + roundedAmount + " of BTC for price " + askPrice + " for total value of " + (roundedAmount * askPrice) + ".");
        got.post(BUY_LIMIT_ORDER_URL, {
            body : order,
            form: true
        }).then(response => {
            let result = JSON.parse(response.body);
            resolve(result);
        }).catch(reject);
    });
};

const getAskPriceAndBuyLimitOrder = function(customerId, key, secret, value) {
    return new Promise(function(resolve, reject) {
        getAskPrice
            .then(askPrice => buyLimitOrder(customerId, key, secret, value, askPrice).then(resolve).catch(reject))
            .catch(reject);
    });
};

exports.handler = (event, context, callback) => {
    doWithBitstampProperties()
        .then(bitstampProperties =>
            getAskPriceAndBuyLimitOrder(bitstampProperties.customerId, bitstampProperties.key, bitstampProperties.secret, VALUE)
                .then(result => callback(null, result))
                .catch(error => callback(error)))
        .catch(error => callback(error));
};

Full code can be found here.

This works, but I was not sure this is how promises should be chained. For instance, calling .then(resolve).catch(reject) on buyLimitOrder(...) does not feel right:

    return new Promise(function(resolve, reject) {
        getAskPrice
            .then(askPrice => buyLimitOrder(customerId, key, secret, value, askPrice).then(resolve).catch(reject))
            .catch(reject);
    });

Generally, the code does not feel elegant.

Removing Promise constructor wrappers

As @Peilonrayz mentioned in his comment, we can return the promises directly instead of wrapping them in Promise constructors.

From the MDN: Promise docs:

  The constructor is primarily used to wrap functions that do not already support promises.

Since we are already returning promises (and not wrapping callbacks, for example) we can remove the constructors.

For example, doWithBitstampProperties:

const doWithBitstampProperties = function() {
    return new Promise(function(resolve, reject){
        if (BITSTAMP_PROPERTIES) {
            resolve(BITSTAMP_PROPERTIES);
        } else {
            decryptBitstampProperties().then(resolve).catch(reject);
        }
    });
};

Could be rewritten to return the promise directly:

const doWithBitstampProperties = function() {
  if (BITSTAMP_PROPERTIES) {
    return Promise.resolve(BITSTAMP_PROPERTIES);
  }

  return decryptBitstampProperties();
};

Or, using the conditional operator if you preferred to be more terse:

const doWithBitstampProperties = function() {
  return BITSTAMP_PROPERTIES
    ? Promise.resolve(BITSTAMP_PROPERTIES)
    : decryptBitstampProperties();
};

We can repeat this pattern for the other functions and reduce the noise that all the resolve/rejects added:

const AWS = require('aws-sdk');
const crypto = require('crypto');
const got = require('got');

const CURRENCY_PAIR = 'btceur';
const TICKER_URL = `https://www.bitstamp.net/api/v2/ticker/${CURRENCY_PAIR}/`;
const BUY_LIMIT_ORDER_URL = `https://www.bitstamp.net/api/v2/buy/${CURRENCY_PAIR}/`;

if (!AWS.config.region) {
    AWS.config.update({ region: 'eu-central-1' });
}

const ENCRYPTED_BITSTAMP_CUSTOMER_ID = process.env.BITSTAMP_CUSTOMER_ID;
const ENCRYPTED_BITSTAMP_KEY = process.env.BITSTAMP_KEY;
const ENCRYPTED_BITSTAMP_SECRET = process.env.BITSTAMP_SECRET;
const VALUE = Number(process.env.VALUE);
const MINIMUM_VALUE = 5;

if (isNaN(VALUE) || VALUE < MINIMUM_VALUE) {
    throw new Error(`Invalid value [${value}], must be a number not less than [${MINIMUM_VALUE}].`);
}

const kms = new AWS.KMS();

const decrypt = function(encrypted) {
    return kms
        .decrypt({ CiphertextBlob: new Buffer(encrypted, 'base64') })
        .promise()
        .then(data => data.Plaintext.toString('ascii'))
};

let BITSTAMP_PROPERTIES;

const decryptBitstampProperties = function() {
    return Promise.all([
        decrypt(ENCRYPTED_BITSTAMP_CUSTOMER_ID),
        decrypt(ENCRYPTED_BITSTAMP_KEY),
        decrypt(ENCRYPTED_BITSTAMP_SECRET)
    ]).then(([customerId, key, secret]) =>
        BITSTAMP_PROPERTIES = { customerId, key, secret }
    );
})};

const doWithBitstampProperties = function() {
    return BITSTAMP_PROPERTIES
        ? Promise.resolve(BITSTAMP_PROPERTIES)
        : decryptBitstampProperties();
};

const createAuthData = function(customerId, key, secret) {
    const nonce = Date.now();
    const message = nonce + customerId + key;
    const signature = crypto
    .createHmac('sha256', new Buffer(secret, 'utf8'))
    .update(message)
    .digest('hex')
    .toUpperCase();

    return { key, signature, nonce };
};

const getAskPrice = function() {
  return got(TICKET_URL).then(response => {
    const result = JSON.parse(result);
    const ask = Number(result.ask);

    if (!isNaN(ask)) {
      return ask;
    }

    throw new Error(`Could not parse the ask price from [${BTCEUR_TICKER_URL}] response:\n${response.body}`);
  });
});

const buyLimitOrder = function(customerId, key, secret, value, askPrice) {
    const amount = value / askPrice;
    const roundedAmount = Math.ceil(amount * Math.pow(10,5)) / Math.pow(10,5);

    const order = {
        ...createAuthData(customerId, key, secret),
        amount: roundedAmount,
        price: askPrice
    };

    console.log(`Buying ${roundedAmount} of BTC for price ${askPrice} for total value of ${roundedAmount * askPrice}.`);

    return got.post(BUY_LIMIT_ORDER_URL, {
        body: order,
        form: true
    }).then(response => {
        return JSON.parse(response.body);
    });
};

const getAskPriceAndBuyLimitOrder = function(customerId, key, secret, value) {
    return getAskPrice()
        .then(askPrice => buyLimitOrder(customerId, key, secret, value, askPrice));
};

exports.handler = (event, context, callback) => {
    doWithBitstampProperties()
        .then(bitstampProperties =>
            getAskPriceAndBuyLimitOrder(bitstampProperties.customerId, bitstampProperties.key, bitstampProperties.secret, VALUE)
                .then(result => callback(null, result))
                .catch(error => callback(error)))
        .catch(error => callback(error));
};

A few other potential changes...

Preferring const over let to denote a variable can't be reassigned (but still mutable)
Date.now() can be used instead of (new Date()).getTime()
Returning early to prevent else blocks
Moving BITSTAMP_PROPERTIES declaration closer to where it's assigned
Using the spread operator to prevent mutating orders (Note: this is currently a stage 3 draft at time of writing)
Using template literals for more succinct strings
Using array matching instead of indices to for customerId, key and secret
Using node-fetch instead of got to be consistent with the browser's Fetch API. JSON requests would be of the form fetch(...).then(res => res.json()).then(data => ...) instead of calling JSON.parse


Schema.org combining different categories This is the follow up version of a previous question on combining different categories and their properties.

The home page contains the overarching company information.
The product page contains product information and links to the home page.

I do not get any error messages in Google testing tool. But I feel that the code is clunky. I am concerned that a lot of the information is hidden and that search prefer to index information that is also visible to the user.

Home page

Organization
<meta itemprop="name" content="Organizaton name" />

short description on home page

Product page

<link itemprop="url" href="http://www.sub-company-url/">
<meta itemprop="name" content="Sub-company name" />

NAME OF PRODUCT
The cost of

NAME OF PRODUCT
<meta itemprop="priceCurrency" content="EUR">€600

Home page

The Microdata is fine.

I don’t know if it’s possible with the design of your page, but typically you would link the name/logo (then you could omit the meta and you wouldn’t need alt content), so it could look like:

    Organizaton

short description on home page

Product page

You are using the name property (from TravelAgency) on a meta element, but do you really have no visible name of the travel agency on your page (e.g., in the header)? If you have one, you could use that element instead of meta.
The itemOffered property expects a Product item as value, but you are using text.

As you are already using Product → offers → Offer, there is no need for the reverse relation Offer → itemOffered → Product.

You probably want to use the name property instead, however, if the Product has the same name as the Offer, omit this property altogether.
If the only data about the Product is the name, consider omitting this item. You could use Offer directly (unless you have several offers for the same Product).
There is a superfluous .
Your span element has a content attribute, which is not allowed. Use a meta or data element (or in your specific case, just the content of the span.)


Improvement of a regular expression pattern I created this script to take informations "at-the-moment" of this site:

Pictures of name channel
Name of channel
Pictures channel
Times
Title
Type

My script (Work):

<?php

$url="http://www.programme-tv.net/programme/toutes-les-chaines/en-ce-moment.html#Grandes%20cha%C3%AEnes";
$code_page = file_get_contents($url);

preg_match_all('/
(.*?)/is', $code_page, $chaines);
preg_match_all('/
(.*?)
(.*?)<\/div>/is', $code_page, $channels);

$i=0;
foreach ($channels as $channel) {
    if($i==3){
        for ($j=0; $j < 38; $j++) {
            preg_match_all('/<\/span>/', $channel[$j], $image[$j]);
        }
    }

if($i==4){
        for ($j=0; $j < 38; $j++) {
            preg_match_all('/
(.*?)<\/p>/', $channel[$j], $time[$j]);
            preg_match_all('/
(.*?)<\/p>/', $channel[$j], $title[$j]);
            preg_match_all('/
(.*?)<\/p>/', $channel[$j], $type[$j]);
        }
    }
    $i++;
}

for ($i=0; $i < 38; $i++) {
    $test = strpos($chaines[2][$i],'
');
    if($test != true){
        echo 'Chaines images:
';
        echo 'Chaines: '.$chaines[3][$i].'
';
        echo 'image :
';
        echo 'Temps : '.trim($time[$i][1][0]).'
';
        echo 'Titre : '.substr($title[$i][1][0], strpos($title[$i][1][0], '>') + 1, strrpos($title[$i][1][0], '<')).'
';
        echo 'Type : '.$type[$i][1][0].'
';
        echo '
';
    }
}
?>

I would like to improve and find a better regular expression pattern because I use 6 regular expression pattern.

To be honest I don't think your current way of handling is 'clean'.
But I would suggest you to use a HTML DOM parser. I took the liberty to google it for you and http://simplehtmldom.sourceforge.net/ seems quite what you need.

It's a PHP HTML parser, which allows you to write

// Find all element which class=foo
$ret = $html->find('.at-the-moment');

instead of

preg_match_all('/
(.*?)
(.*?)<\/div>/is', $code_page, $channels);

Also your other regexes can be switched (read the documentation)

To be honest, I never used this library before, but I've worked with beautifulsoup which is a Python equivalent, which would do the trick for you perfectly.
(source: http://www.givegoodweb.com/post/210/html-parser-for-php)

Wishing you the best!


Speed performance of picking unique value from binary matrix file I wrote this code to read a square matrix saved as binary file, that it can be int, uint, float etc... to pick a value from the matrix at given row y and given column x.
Could this code be faster to pick this value, better than 20 seconds.
The maximum row and column number in matrix is 3601 for each one.

import struct

#convert x,y indexes of 2D array into index i of 1D array
#x: index for cols in the 2D
#y: index for rows in the 2D
def to1D(y,x,width):
    i = x + width*y
    return i

def readBinary_as(filename,x,y,file_type,width=3601):
    with open(filename,'rb') as file_data:

        #initialize, how many bytes to be read
        nbByte = 0
        #data type of the file, uint, int, float, etc...
        coding = ''
        if file_type == "signed int":
            nbByte = 2
            coding = '>h'  #2B Signed Int - BE

        if file_type == "unsigned int":
            nbByte = 2
            coding = '>H' #2B Unsigned Int - BE

        if file_type == "unsigned byte":
            nbByte = 1
            coding = '>B' #1B Unsigned Byte - BE

        if file_type == "float":
            nbByte = 4
            coding = '>f' #4B float32 - BE

        #index of my value in 1D array
        i = to1D(y,x,width)
        for each_cell in range(0,i):
            file_data.read(nbByte)

        #read and save the picked value
        my_value_pos = file_data.read(nbByte)
        val = struct.unpack(coding,my_value_pos)[0]
    return val

Try using seek() instead of a loop that reads 1 value at a time.

import io
import struct

#convert x,y indexes of 2D array into index i of 1D array
#x: index for cols in the 2D
#y: index for rows in the 2D
def to1D(y,x,width):
    i = x + width*y
    return i

def readBinary_as(filename,x,y,file_type,width=3601):
    with open(filename,'rb') as file_data:

        #initialize, how many bytes to be read
        nbByte = 0
        #data type of the file, uint, int, float, etc...
        coding = ''
        if file_type == "signed int":
            nbByte = 2
            coding = '>h'  #2B Signed Int - BE

        if file_type == "unsigned int":
            nbByte = 2
            coding = '>H' #2B Unsigned Int - BE

        if file_type == "unsigned byte":
            nbByte = 1
            coding = '>B' #1B Unsigned Byte - BE

        if file_type == "float":
            nbByte = 4
            coding = '>f' #4B float32 - BE

        #index of my value in 1D array
        i = to1D(y,x,width)
        offset = i * nbByte

        # seek to byte offset of desired data
        file_data.seek(offset)

        #read and save the picked value
        my_value_pos = file_data.read(nbByte)
        val = struct.unpack(coding,my_value_pos)[0]
    return val


Add spaces around variable with $ symbol bookends I have some code in a particular coding language, and I am trying to clean it up by adding spaces around the variables. I wrote this code, and it works on small amounts of text and if I set a break point and run through it manually for large amounts of text. But when I try to run through it without frequently stopping the macro, Word stops responding and I have to restart the program. I think it is because the code is inefficient, but I don't have enough knowledge of vba to make it more efficient.

My code

Sub SpaceVarsAndEqns()

Dim i As Long
Dim paragraphIndex As Long
Dim characterIndex As Long
Dim isVar As Boolean
Dim varIndexBegin As Long
Dim varIndexEnd As Long
Dim Doc As Range
Dim Par As Range
Dim Char As Range

Set Doc = ActiveDocument.Range

For paragraphIndex = 1 To Doc.Paragraphs.Count

    Set Par = Doc.Paragraphs(paragraphIndex).Range
    isVar = False

    characterIndex = 1
    Do

        Set Char = Par.Characters(characterIndex)

        If isVar Then
            If Char.Text = "$" Then
                varIndexEnd = characterIndex

                If Not Par.Characters(varIndexEnd + 1).Text = " " Then
                    Par.Characters(varIndexEnd).InsertAfter (" ")
                    characterIndex = characterIndex + 1
                End If
                If Not Par.Characters(varIndexBegin - 1).Text = " " Then
                    Par.Characters(varIndexBegin).InsertBefore (" ")
                    characterIndex = characterIndex + 1
                End If

                varIndexBegin = 0
                varIndexEnd = 0
                isVar = False
            ElseIf Not (IsAlphaNumber(Char.Text) Or (Char.Text = ".")) Then
                varIndexBegin = 0
                varIndexEnd = 0
                isVar = False
            End If
        Else
            If Par.Characters(characterIndex).Text = "$" Then
                varIndexBegin = characterIndex
                isVar = True
            End If
        End If

        characterIndex = characterIndex + 1
    Loop While (characterIndex <= Par.Characters.Count)

Next paragraphIndex

End Sub

Text Before

\begin{bmatrix} $eval(($d$*$d.pmv$)/(|$d.et$|)*($d.et$*$xm$) + (($b$*-1)*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$) + $dist5$,0.###)\\ $eval((((($a$*$d$)-$d.et$)/($b$))*$d.pmv$*-1)/(|$d.et$|)*($d.et$*$xm$) + ($a$*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$)+ $dist6$,0.###) \end{bmatrix}

Text After

\begin{bmatrix} $eval(( $d$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $xm$ ) + (( $b$ *-1)* $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ ) + $dist5$ ,0.###)\\ $eval((((( $a$ * $d$ )- $d.et$ )/( $b$ ))* $d.pmv$ *-1)/(| $d.et$ |)*( $d.et$ * $xm$ ) + ( $a$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ )+ $dist6$ ,0.###) \end{bmatrix}

I think it could be improved by using a find method to find two consecutive $ symbols, and checking if the characters in between are consistent with a variable. However, I don't know how I would add spaces doing it this way.

Here's a version using Regular Expressions.

Option Explicit

Sub SpaceVarsAndEqns()

    Dim DocumentRange As Range, ParagraphRange As Range
    Dim i As Long, P As Paragraph
    Dim Pattern As String, Replace As String, RegEx As New RegExp
    Dim ParagraphText As String

    Pattern = "(?:\s?)\$[^$(]*\$(?:\s?)"
    Replace = " $& "

    With RegEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = True
        .Pattern = Pattern
    End With

    Set DocumentRange = ActiveDocument.Range
    For i = 1 To DocumentRange.Paragraphs.Count
        Set P = DocumentRange.Paragraphs(i)
        ParagraphText = P.Range.Text
        If RegEx.Test(ParagraphText) Then
            P.Range.Text = RegEx.Replace(ParagraphText, Replace)
        End If

    Next

End Sub

Before:

\begin{bmatrix} $eval(($d$*$d.pmv$)/(|$d.et$|)*($d.et$*$xm$) + (($b$*-1)*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$) + $dist5$,0.###)\\ $eval((((($a$*$d$)-$d.et$)/($b$))*$d.pmv$*-1)/(|$d.et$|)*($d.et$*$xm$) + ($a$*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$)+ $dist6$,0.###) \end{bmatrix}

After:

\begin{bmatrix} $eval(( $d$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $xm$ ) + (( $b$ *-1)* $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ ) +  $dist5$ ,0.###)\\ $eval((((( $a$ * $d$ )- $d.et$ )/( $b$ ))* $d.pmv$ *-1)/(| $d.et$ |)*( $d.et$ * $xm$ ) + ( $a$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ )+  $dist6$ ,0.###) \end{bmatrix}

This requires adding a reference to the Microsoft VBScript Regular Expressions 5.5 by going to Tools > References and checking that box:

You can read more on Regular Expressions in VBA in this Stack Overflow answer.


Processing a large number of files in a folder I have a folder which contains lots of files. I need to write C# code that will open and read and display the content of it. Is this efficient code or should something be changed?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Text;

using System.Collections;

class Program
{
    static void Main()
    {
        var sw = Stopwatch.StartNew();
        ProcessRead().Wait();
        Console.Write("Done ");

        Console.WriteLine("Elapsed Time" + sw.ElapsedMilliseconds+"and"+sw.ElapsedTicks);
        Console.ReadKey();
    }

    static async Task ProcessRead()
    {

        string folder = @"Directory";

        string[] fileEntries = Directory.GetFiles(folder);
        int count = 0;

        foreach (string fname in fileEntries)

        {

            if (File.Exists(fname) == false)
            {
                Console.WriteLine("file not found: " + fname);
            }
            else
            {
                try
                {
                    count++;
                    string text = await ReadTextAsync(fname);
                    Console.WriteLine(text);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        Console.WriteLine(count);
    }

    static async Task<string> ReadTextAsync(string filePath)
    {

        using (FileStream sourceStream = new FileStream(filePath,
            FileMode.Open, FileAccess.Read, FileShare.Read,
            bufferSize: 4096, useAsync: true))
        {
            StringBuilder sb = new StringBuilder();

            byte[] buffer = new byte[0x1000];
            int numRead;
            while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
            {
                string text = Encoding.UTF8.GetString(buffer, 0, numRead);
                sb.Append(text);
            }

            return sb.ToString();
        }
    }
}

You could use Directory.EnumerateFiles to allow processing of each path without loading all the paths to memory.
It is not required to check if the file exists because you just checked that (getting the path with GetFiles).
Instead of implementing your own ReadTextAsync, just use File.ReadAllText.
There is no need to use a new synchronization context (async call) for each file. If you want to process the files in the background, it is better processing all files in one single Task than using one task for each file. Remember that each context switch produces a little overhead.
If you want to use an async API that way, consider using ConfigureAwait(true) to avoid context switches:

await sourceStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(true)

I suppose the following code will do the same faster and with less memory consumption:

static async Task ProcessRead()
{
    await Task.Run(() =>
    {
        IEnumerable<string> fileEntries = Directory.EnumerateFiles(@"Directory");
        int count = 0;
        foreach (string fname in fileEntries)
        {
            try
            {
                count++;
                string text = File.ReadAllText(fname);
                    Console.WriteLine(text);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        Console.WriteLine(count);
    }
}


Idiomatic Ruby FizzBuzz Can anyone offer any criticism on the following at a simple FizzBuzz in terms of Ruby idioms or otherwise?

class FizzBuzz

  def initialize(fizz = 'Fizz', buzz = 'Buzz')
    @fizz = fizz
    @buzz = buzz
  end

  def is_number_divisible_by?(number, divisor)
    number % divisor == 0
  end

  def get_text(number)
    fizz_buzz_text = ''
    if is_number_divisible_by?(number, 3)
      fizz_buzz_text += @fizz
    end
    if is_number_divisible_by?(number, 5)
      fizz_buzz_text += @buzz
    end
    return fizz_buzz_text
  end

end

fb = FizzBuzz.new
(1...101).each do |i|
  fb_text = fb.get_text(i)
  puts fb_text.empty? ? i : fb_text
end

First off: If you want a range that goes from 1 to x, inclusive, write (1..x), not (1...x+1).

Second, if it's the last line executed in a method, it's automatically returned -- so in get_text, you don't need return in the last line, just the actual code.

Also, get_text should return the text to be printed, not what it might be. Move the empty check (fb_text.empty ? i : fb_text) to get_text instead of having it at the puts call. See the code at the end for clarification.

if statements with just one line should be expressions at the end. Again, see the modified code for what I mean.

Methods defined in a class are generally talking about the object they're run on. I'd pull is_number_divisible_by? out of the class and dropping it at the beginning of your code instead, and renaming it to something like divisible_by? instead (since it's shorter and carries the same information).

Aside from that (and an odd extra newline at the beginning of your class definition), it looks good! Here's your code with these suggestions:

def divisible_by?(number, divisor)
  number % divisor == 0
end

class FizzBuzz
  def initialize(fizz = 'Fizz', buzz = 'Buzz')
    @fizz = fizz
    @buzz = buzz
  end

  def get_text(number)
    fizz_buzz_text = ''
    fizz_buzz_text += @fizz if divisible_by? number, 3
    fizz_buzz_text += @buzz if divisible_by? number, 5
    fizz_buzz_text.empty? ? number : fizz_buzz_text
  end

end

fb = FizzBuzz.new
(1..100).each do |i|
  puts fb.get_text i
end

Note: Personally, I wouldn't do this in an OOP way. Ruby is much more oriented towards functional programming, though of course OOP is perfectly valid; besides, functional is a bit simpler. My preferred way to do it would be something like this:

(1..100).each do |num|
  output = ''
  output += 'Fizz' if num % 3 == 0
  output += 'Buzz' if num % 5 == 0
  puts output.empty? ? num : output
end


Demonstration of Kaprekar's Constant Given any four-digit number that consists of at least two different digits, if you form a number by arranging its digits in descending order, and subtract the number formed by arranging its digits in ascending order, and repeat, you should eventually arrive at 6174, Kaprekar's Constant.

How can I make improvements to my code? Is my code readable and simple to understand?

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <functional>

//at least two digits must be distinct
bool isUnique(int num)
{
constexpr int numlength = 4;
std::vector<int> digits;

for(int i = 0; i < numlength ; ++i)
{
    int digit = num%10;
    digits.push_back(digit);
    num /= 10;
}

//If digits are all equal return false.
if ( std::adjacent_find( digits.begin(), digits.end(), std::not_equal_to<int>() ) == digits.end() )
{
    return false;
}else
{
    return true;
}

}

int KaprekarsConstant(int num)
{
constexpr int kaprekarsConst = 6174;
constexpr int lengthRequirement = 4;

static int iteration = 0;

if(std::to_string(num).length() == lengthRequirement && isUnique(num))
{
    int difference = num;
    std::string sNum;

        while(difference != kaprekarsConst)
        {
            sNum = std::to_string(difference);

            std::sort(sNum.begin(),sNum.end(),std::greater<int>());
            int ascendNum = stoi(sNum);

            std::sort(sNum.begin(),sNum.end(),std::less<int>());
            int descendNum = stoi(sNum);

            difference = ascendNum - descendNum;

            ++iteration;
        }
}
return iteration;
}

I'm assuming the indenting is cut and paste problems, but going through this:

#include <iostream>

You don't use iostream, so don't include it

#include <string>
#include <algorithm>
#include <vector>
#include <functional>

I'd recommend you sorted the #includes. It makes it a lot easier to find things if you have a lot of them and avoids a certain class of problem with merging file changes

//at least two digits must be distinct
bool isUnique(int num)

Given the comment, isUnique is not a good name. It's looking for 2 distinct digits, not - well, it's not looking for anything unique. contains_2_distinct_digits perhaps?

{
    constexpr int numlength = 4;
    std::vector<int> digits;

    for(int i = 0; i < numlength ; ++i)

for is not a function call. It's a keyword. Put a space after it.

    {
        int digit = num%10;
        digits.push_back(digit);
        num /= 10;
    }

The 4 doesn't really belong here (see below).

    //If digits are all equal return false.
    if ( std::adjacent_find( digits.begin(), digits.end(), std::not_equal_to<int>() ) == digits.end() )

I wouldn't have the space after the ( there.

This code is somewhat inconsistent with the use of spaces. You have a space after commas and brackets here, but not further down. Pick a style and stick to it.

    {
        return false;
    }else

I'd recommend against dangling the else off the }. Either put it on its own line or use '} else {'

    {
        return true;
    }

You don't really need that if. Just

    return std::adjacent_find(digits.begin(), digits.end(), std::not_equal_to<int>()) != digits.end();

}

int KaprekarsConstant(int num)

TBH I'd expect a name like that to return the constant (actually I wouldn't expect with that name it'd even be a function). This isn't returning that. It's returning how many iterations it takes to stabilise.

{
    constexpr int kaprekarsConst = 6174;
    constexpr int lengthRequirement = 4;

You have this 4 here and you use 4 for the passing in isUnique. This is fragile, should you ever want to deal with a similar property for numbers with digits other than 4.

    static int iteration = 0;

There's no need for this to be static

    if(std::to_string(num).length() == lengthRequirement && isUnique(num))

if is not a function call

    {
        int difference = num;
        std::string sNum;

sNum only needs to exist in the while loop, so put it there. You should attempt to declare variables at the point of use where possible.

            while(difference != kaprekarsConst)

while is not a function call. Put a space after it.

If you wanted to generalise this to n digits, I wouldn't define kaprekarsConst. You'd just check if the newly evaluated difference matched the previous difference.

            {
                sNum = std::to_string(difference);

                std::sort(sNum.begin(),sNum.end(),std::greater<int>());
                int ascendNum = stoi(sNum);

                std::sort(sNum.begin(),sNum.end(),std::less<int>());
                int descendNum = stoi(sNum);

As has been suggested, this is already sorted, so you could just reverse it.

                difference = ascendNum - descendNum;

                ++iteration;
            }
    }
    return iteration;
}


PHP Single Type Collection I have implemented a collection class that stores a single type of value.

At the moment it is immutable.

abstract class Collection implements Iterator
{

    /** @var int */
    protected $position = 0;
    /** @var array */
    private $items = [];

    public function next()
    {
        ++$this->position;
    }

    public function key()
    {
        return $this->position;
    }

    public function valid()
    {
        return isset($this->items[$this->position]);
    }

    public function rewind()
    {
        $this->position = 0;
    }

    protected function add($item)
    {
        return $this->items[] = $item;
    }

    protected function get($index)
    {
        return $this->items[$index];
    }
}

DateTimeIterator guarantees that when iterated over it will only return the specified type.

interface DateTimeIterator extends Iterator
{

    public function current(): DateTimeInterface;
}

The constructor of DateTimeCollection ensures that the collection only stores values that implement DateTimeInterface.

class DateTimeCollection extends Collection implements DateTimeIterator
{

    public function __construct(iterable $values = [])
    {
        foreach ($values as $value) {
            if (!$value instanceof DateTimeInterface) {
                throw new TypeError('DateTimeCollection only accepts ' .
                    'items that implement DateTimeInterface');
            }
            $this->add($value);
        }
    }

    public function current(): DateTimeInterface
    {
        return $this->get($this->key());
    }
}

The Collection is not really immutable if you can add items to it :)

You should explicitly define either abstract or simple default implementation (i.e. that doesn't enforce return data type) for current() method on Collection.

I would suggest using $this->key() within valid()

public function valid()
{
    return isset($this->items[$this->key()]);
}

This is consistent with your usage in current() in inheriting classes and consistent with iterator interface.  This also allows for override of key() in inheriting classes if there ever was such a need for this.

Consider explicitly specifying abstract constructor in Collection class (or again a simple default constructor (i.e. just setting position to O)).  You should explicitly set position to 0 in constructor in some manner.

You might consider exposing a length() function on your collection since you are providing functionality beyond basic iteration.  This would allow you to do things like perhaps return new index value to caller on add().

public function length() {
    return count($this->items[]);
}

protected function add($item)
{
    $this->items[] = $item;
    // return index of new item
    return $this->length() - 1;
}

You also should consider validating input parameter passed to get against valid method as being within range of keys.

protected function get($index)
{
    if(!$this->valid($index)) {
        throw new OutOfBoundsException(
            'Index passed to get() is invalid.'
        );
    }
    return $this->items[$index];
}


Random number generator based on a hash of the time from time import time

def baseRandom():
    return hash(str(time()))

def randFromZero(maximum):
    return baseRandom() % maximum

def randRange(minimum, maximum):
    return randFromZero(maximum - minimum) + minimum

I ask what's wrong because it seems so simple and stupid. This is something I just thought up one day and put together in 5 minutes, but it seems to generate even and unpredictable results. I've done a couple of simple tests like generating a lot of numbers and looking at the variance between the amount of times each number is generated, and using it to create a little grid which has tiles that are either black or white with equal probability, in which I saw no clear patterns. Hopefully someone who knows a thing or two about this can educate me.

It looks like you're relying on running this on a system where the granularity of the time() function is smaller than the amount of time it takes to execute baseRandom(), do what you want with the results, and come back to call baseRandom() again.  If not, you'll get more repeating numbers than you should.  You're also relying on the result of the hash() function to be sufficiently pseudorandom given the input you're feeding to it.

Detecting an obvious pattern depends on how you look for it.  I think Knuth gave an example of a RNG that looked OK when you plotted pairs of numbers on an x-y plane, but if you took three numbers in a row as x-y-z coordinates, and look at the resulting cube from the right direction, you can clearly see a finite number of planes where all the outcomes lie.  In other words, just because you tried a couple of things and didn't see a pattern doesn't mean a non-random pattern isn't there.

There are fifteen tests for randomness listed here, if you're interested: http://csrc.nist.gov/groups/ST/toolkit/rng/stats_tests.html