texts: Send multiple individualised emails via a limited number of SMTP clients

texts:
This is my first foray into multi-threading, and I'm keen to know if I have fallen into any traps or have room for optimisation/improvement.

Example usage:

var success = new ConcurrentBag<CourseParticipant>();
var fail = new ConcurrentBag<CourseParticipant>();
using (var parallelEmails = new ParallelSmtpEmails())
{
     foreach (var cp in courseParticipants)
     {
        var mail = new MailMessage{
            From = new MailAddress("from@example.com"),
            To = cp.email,
            Subject = "come and attend course",
            BodyFormat = MailFormat.Html
        }
        string token = await GetRegistrationTokenAsync(cp);
        mail.Body = $"
let me come
"
        parallelEmails.Send(mail, s=>
        {
            if (s == null)
            {
                success.Add(cp);
            }
            else
            {
                fail.Add(cp);
            }
            mail.Dispose();
        });
     }
     await parallelEmails.SendingComplete();
}

In the code below, I am particularly wondering about the RunWorker method, the do while loop, and if workList.TryGet. If there is nothing in the worklist, this thread will remain looping until CompletedAdding is called or more emails are added. Is this looping an acceptable way to wait the thread?

Being an amateur, I am also grateful for any other code improvements or style points.

public class ParallelSmtpEmails : IDisposable
{
    BlockingCollection<MailTask> _workList;
    List<Task> _tasks;
    int _maxClientCount;

    public ParallelSmtpEmails(int maxSmtpClients = 5)
    {
         //removing the boundedCapacity := maxSmtpClients from BlockingCollection instantiator - the collection can be filled up without blocking
        _workList = new BlockingCollection<MailTask>(new ConcurrentQueue<MailTask>());
        _tasks = new List<Task>(maxSmtpClients);
        _maxClientCount = maxSmtpClients;
    }

    public void CompletedAdding()
    {
        _workList.CompleteAdding();
    }

    public void Send(MailMessage message)
    {
        Send(message, null);
    }

    public void Send(MailMessage message, Action<SmtpException> onComplete)
    {
        _workList.Add(new MailTask() { Message = message, OnComplete = onComplete });
        if (_tasks.Count < _maxClientCount && _workList.Count > 0)
        {
            _tasks.Add(Task.Factory.StartNew(RunWorker));
        }
    }

    public Task SendingComplete()
    {
        CompletedAdding();
        return Task.WhenAll(_tasks);
    }

    public void RunWorker()
    {
        using (var client = new SmtpClient())
        {
            do
            {
                MailTask m;
                if (_workList.TryTake(out m))
                {
                    try
                    {
                        client.Send(m.Message);
                        m.OnComplete?.Invoke(null);
                    }
                    catch (SmtpException ex)
                    {
                        m.OnComplete?.Invoke(ex);
                    }
                }
            } while (!_workList.IsCompleted);
        }
    }

    #region IDisposable
    bool _disposed;
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~ParallelSmtpEmails()
    {
        Dispose(false);
    }

    void Dispose(bool disposing)
    {
        if (_disposed)
            return;

        if (disposing)
        {
            // free other managed objects that implement
            // IDisposable only
            _workList.Dispose();
        }

        // release any unmanaged objects
        // set the object references to null

        _disposed = true;
    }
    #endregion //IDisposable

    private class MailTask
    {
        public MailMessage Message { get; set; }
        public Action<SmtpException> OnComplete { get; set; }
    }
}


texts: strend, function that checks the occurence of a pattern at the end of a string

texts:
Write a function strend(s, t) which returns 1 if the string t occurs at the end of s, and 0 otherwise.

Here is my solution:

unsigned int strend(char *source, char *pattern) {
    char *saver = pattern;

    while(*source)
        source++;

    while(*saver)
        saver++;

    while(saver >= pattern)
        if(*saver-- != *source--)
        return 0;

    return 1;
}

There are 2 while loops that will run until source and saver will point to the end of the string that they are representing. You will notice the presence of the variable saver, at the end of the second while loop this variable will have the value pattern + X, where X represent the number of charachters in the string pattern.

By using the variable saver I know when to stop the third loop. When saver is less than pattern that means that every charachter in the string pattern was compared with the coresponding one in source. At each iteration of the loop I check if the current charachter that saver points to is equal to the coresponding charachter in source.

Here is my second version:

unsigned int strend(char *source, char *pattern) {
    char *saver = pattern + strlen(pattern);
    source += strlen(source);

    while(saver >= pattern)
        if(*source-- != *saver--)
            return 0;
    return 1;
}

There is a dependency between my second implementation of strend and strlen. I, also, have some problems with the naming of the variable saver. What would be a more suggestive name for its purpose?

The exercise can be found at page 121 in K&R second edition.


texts: Converting string array to string (and vice-versa) for storing via XML

texts:
I'm using XML to store data and I need to store a string array in it. The best way (that I can think of) to store a string array is by converting it to a single string. In order to do that, I'm using string.Join to join the strings with \0 and then use Base64 so that the \0 (and any other special character) can be retrieved easier. Because it's possible that a string in a array already has \0 in it (causing another string to be the array when they're converted back to an array), I'm escaping the existing \0 by first adding another backslash to existing backslashes and changing \0 to \\0. Is there any better way to do this? Should I be using \r\n instead (but wouldn't that also be the same as using \0)? I should also note that its so I can use IXmlSerializable and it is also storing byte[], uint, ulong and string in the XML as well.

Retrieving String Array (Via XML)

this.Name = reader.GetAttribute("Name");

string strType = reader.GetAttribute("Type");

byte[] buffer = new byte[1000];
int readBytes = 0;
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
while ((readBytes = reader.ReadElementContentAsBase64(buffer, 0, 50)) > 0)
{
    bw.Write(buffer, 0, readBytes);
}

bw.Close();

List<string> unescapedStrs = new List<string>();
string[] val = strValue.Split('\0');
string newStr;

foreach (string s in val)
{
    newStr = Regex.Replace(s, @"([^\\])(\\0)", "$1\0").Replace("\\\\", "\\");

    unescapedStrs.Add(newStr);
}

if (val.Length > 0)
    this.Value = unescapedStrs.ToArray();

Storing String Array (Via XML)

writer.WriteAttributeString("Name", this.Name);

writer.WriteAttributeString("Type", this.Type);

string strValue = string.Empty;

string[] val = (string[])this.Value;

List<string> escapedStrs = new List<string>();

foreach (string s in val)
{
    string newStr = s;

    // Escape backslashes so existing \\0 don't get mixed up
    if (newStr.IndexOf('\\') > 0)
        newStr = newStr.Replace("\\", "\\\\");

    // If theres NULL chars in strings already, escape them
    if (newStr.IndexOf('\0') > 0)
        newStr = newStr.Replace("\0", "\\0");

    escapedStrs.Add(newStr);
}

strValue = string.Join("\0", escapedStrs.ToArray());

int byteLen = Encoding.Unicode.GetByteCount(strValue);
byte[] bytes = Encoding.Unicode.GetBytes(strValue);
writer.WriteBase64(bytes, 0, byteLen);


texts: Multithreading decouple update-logic and render-logic

texts:
I want to improve my multithreading competence and tried to build a compact doublebuffered way to separate two threads where one is only displaying the state and the other one updates the state. So I am here to hear whether I done it "right" and what to improve.

#include <thread>
#include <mutex>
#include <iostream>
#include <fstream>

template <class T> class StateBuffer
{
public:
    typedef T value_t;

    void Swap()
    {
        {
            std::lock_guard<std::mutex> _(swapMutex);
            index = 1 - index;
        }
        Write() = Read();
    }
    value_t& Write()
    {
        std::lock_guard<std::mutex> _(swapMutex);
        return states[index];
    }
    const value_t Read()
    {
        std::lock_guard<std::mutex> _(swapMutex);
        return states[1-index];
    }
    const value_t&& ReadRef()
    {
        std::lock_guard<std::mutex> _(swapMutex);
        return std::ref(states[1-index]);
    }
private:
    mutable std::mutex swapMutex;
    T states[2];
    uint8_t index = 0; // index = write, 1-index = read
};

struct state_t
{
    int count = 0;
    bool stop = false;
};
typedef StateBuffer<state_t> TestStateBuffer;
TestStateBuffer state;

auto constexpr NO_TIME = std::chrono::seconds(0);

void r()
{
    std::ofstream log("log.txt");
    bool run = true;
    while (run)
    {
        state_t display = state.Read();

        log << display.count << "\n";
        run = !display.stop;

        std::this_thread::sleep_for(NO_TIME);
    }
    log.flush();
}

void u()
{
    bool run = true;

    while (run)
    {
        state_t& write = state.Write();

        run = !write.stop;
        write.stop = ++write.count > 1000000;

        state.Swap();
        std::this_thread::sleep_for(NO_TIME);
    }
}

int main(int, char**)
{
    std::thread render(r);
    std::thread update(u);

    update.join();
    render.join();

    std::cout << "ende" << std::endl;
    std::cin.get();

    return 0;
}

Yes, this is intended to find use in gamedev.

Questions that have gone through my mind:

I use sleep(0) to force a thread swap. Do I need this?
Is there a way how to solve this with a conditional_variable as I read that locking a mutex is expensive in comparison to check with a conditional_variable (although one still need a mutex)?
As I am using references is this really safe?
Have I left anything out?

Environment: Windows 7 x64 g++ on MinGW / Mint 17 x64 clang++ (both C++11 enabled)


texts:
I have the following SQL. I want to make that the SP should work under load. Means it should not have any synchronization issues.

ALTER PROCEDURE [dbo].[DeleteOldDeviceID]
(
    @OldDeviceID VARCHAR(500)
    ,@NewDeviceID  VARCHAR(500)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @TranCount INT;
SET @TranCount = @@TRANCOUNT;

BEGIN TRY
    IF @TranCount = 0
        BEGIN TRANSACTION
    ELSE
        SAVE TRANSACTION DeleteOldDeviceID;

    IF @NewDeviceID <> '-1' AND NOT EXISTS(SELECT 1 FROM DeviceCatalog WHERE [UniqueID] = @NewDeviceID)
        BEGIN
        INSERT INTO [DeviceCatalog]
                ([os]
                ,[uniqueid]
                ,[address]
                ,[location]
                ,[culture]
                ,[city]
                ,[country]
                ,[other]
                ,[lastmodifieddate]
                ,[createddate]
                ,[IsActive]
                ,[IPAddress]
                ,[NativeDeviceID]
                ,[IsDeleted])
        SELECT  [os]
            ,@NewDeviceID
            ,[address]
            ,[location]
            ,[culture]
            ,[city]
            ,[country]
            ,[other]
            ,GETDATE()
            ,GETDATE()
            ,[IsActive]
            ,[IPAddress]
            ,[NativeDeviceID]
            ,[IsDeleted]
        FROM    [DeviceCatalog]
        WHERE   [UniqueID] = @OldDeviceID;
    END
    DELETE FROM DeviceCatalog WHERE [UniqueID] = @OldDeviceID; -- Always Delete old one
        LBEXIT:
    IF @TranCount = 0
        COMMIT;
END TRY
BEGIN CATCH
    DECLARE @Error INT, @Message VARCHAR(4000), @XState INT;
    SELECT  @Error = ERROR_NUMBER() ,@Message = ERROR_MESSAGE() ,@XState = XACT_STATE();

        IF @XState = -1
            ROLLBACK;
        IF @XState = 1 AND @TranCount = 0
            rollback
        IF @XState = 1 AND @TranCount > 0
            ROLLBACK TRANSACTION DeleteOldDeviceID;

        RAISERROR ('DeleteOldDeviceID: %d: %s', 16, 1, @error, @message) ;
    END CATCH
 END

Edit:, Is this equal to above SQL?

ALTER PROCEDURE [dbo].[DeleteOldDeviceID]
(
    @OldDeviceID VARCHAR(500)
    ,@NewDeviceID  VARCHAR(500)
)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @TranCount INT;
    SET @TranCount = @@TRANCOUNT;

    BEGIN TRY
        IF @TranCount = 0
            BEGIN TRANSACTION
        ELSE
            SAVE TRANSACTION DeleteOldDeviceID;

        IF @NewDeviceID <> '-1' AND NOT EXISTS(SELECT 1 FROM DeviceCatalog WHERE [UniqueID] = @NewDeviceID)
            BEGIN
                UPDATE  [DeviceCatalog]
                SET [UniqueID] = @NewDeviceID
                WHERE   [UniqueID] = @OldDeviceID;
            END
        ELSE
        BEGIN
            DELETE FROM DeviceCatalog WHERE [UniqueID] = @OldDeviceID; -- Always Delete old one
        END
        LBEXIT:
            IF @TranCount = 0
                COMMIT;
    END TRY
    BEGIN CATCH
        DECLARE @Error INT, @Message VARCHAR(4000), @XState INT;
        SELECT  @Error = ERROR_NUMBER() ,@Message = ERROR_MESSAGE() ,@XState = XACT_STATE();
            IF @XState = -1
                ROLLBACK;
            IF @XState = 1 AND @TranCount = 0
                ROLLBACK
            IF @XState = 1 AND @TranCount > 0
                ROLLBACK TRANSACTION DeleteOldDeviceID;

            RAISERROR ('DeleteOldDeviceID: %d: %s', 16, 1, @error, @message) ;
    END CATCH
END


texts: My take on implementing the Repository Design Pattern in PHP

texts:
The past few weeks I've been trying to grasp on nearly any Design Pattern ever invented, but the repository pattern is one I could understand and implement it myself in my project. My application uses the MVC pattern where I've got the "V" and the "C" part covered in a very basic way, and I want to get rid of a single model "M" doing everything the view needs. I would like to know if I'm somewhat in the right direction. Along with that I ask some questions on parts of the approach.

Let's get started with some code, the whole operation is to get the latest log events from an external data source (database):

Controller

My controller creates a new Repository object, which takes the Database wrapper and the Data Mapper as its arguments. The Data Mapper takes a Domain Entity.

How would I take care of these 4 require_once statements in my Controller functions?

public function index() {
    // need a way to not have to require these classes all the time
    require_once '../app/domain/repositories/EventRepository.php';
    require_once '../app/domain/interfaces/EventRepositoryInterface.php';
    require_once '../app/domain/mappers/EventMapper.php';
    require_once '../app/domain/entities/Event.php';

    $events = new EventRepository(new Database('db'), new EventMapper(new Event()));

    try {
        $return = $events->fetchAll();
    } catch (DatabaseException $e) {
        $return = $e->getErrorMessage();
    }

    $this->view('/home/dashboard', ['return' => $return]);
}

Repository

class EventRepository implements EventRepositoryInterface {

    protected $dbh;
    protected $eventMapper;

    public function __construct(Database $dbh, EventMapper $eventMapper) {
        $this->dbh = $dbh;
        $this->eventMapper = $eventMapper;
    }

    public function fetchAll() {
        $data = $this->dbh->sql_select('SELECT datetime, message FROM eventlog');

        return $this->eventMapper->toEvent($data);
    }

}

Repository Interface

interface EventRepositoryInterface {
    public function fetchAll();
}

Data Mapper

I'm using a Data Mapper in my Repository Pattern approach. Not sure if this is a right way to do it, but I've seen examples of implementing Data Mappers with repositories.

class EventMapper {

    protected $collection = [];
    protected $event;

    public function __construct(Event $event) {
        $this->event = $event;
    }

    public function toEvent($data) {
        foreach($data as $value) {
            $this->event->setDateTime($value['datetime']);
            $this->event->setMessage($value['message']);

            $this->collection[] = $this->event;
        }

        return $this->collection;
    }
}

Domain Entity

class Event {

    protected $id;
    protected $dateTime;
    protected $message;
    protected $type;

    public function setDateTime($dateTime) {
         $this->dateTime = $dateTime;
    }

    public function getDateTime() {
         return $this->dateTime;
    }

    public function setMessage($message) {
        $this->message = $message;
    }

    public function getMessage() {
        return $this->message;
    }

}

This code leaves me with an array of objects which I can do other stuff with it. Eventually the data from this array needs to be converted to an HTML table. Where would I put such a class (like TablePrinter.php) in my application?


texts:
The following piece of code averages the ante-diagonal elements of a 2d array  x of size (m,n) with, for my purpose, m > n.

import numpy as np

def average_adiag(x):
    """Average antidiagonal elements of a 2d array
    Parameters:
    -----------
    x : np.array
        2d numpy array of size

    Return:
    -------
    x1d : np.array
        1d numpy array representing averaged antediangonal elements of x

    """
    x1d = [np.mean(x[::-1, :].diagonal(i)) for i in
           range(-x.shape[0] + 1, x.shape[1])]
    return np.array(x1d)

Example

x = np.arange(12).reshape(4,3)
print(average_adiag(x))

yields

[  0.   2.   4.   7.   9.  11.]

I make an intensive use of this function in my code and it has been profiled as a performance bottleneck. The code was inspired from this answer. I haven't found any better way on my own. Any performance improvement would be appreciated.

General context

This code is associated with the Singular Spectrum Analysis algorithm for time series decomposition. Basically, I use time series of length 20k that are turned into a trajectory matrix of shape (10k,10k). The latter is decomposed using singular value decomposition in to 10k components. For a given number n of first singular components (usually 50), I reconstruct n 2d array and average their anti-diagonals elements to have back n time series. These are appreciated with a graphical plot of a correlation matrix.

I will not speed up the SVD algorithm, but SVD results are saved. The anti-diagonal averaging is used for exploration of the results but it is slow. Usually, the function average_diag runs n (50 by default) times on matrix of size (10k, 10k). It takes a bit more than 1 minutes on my PC. It seems slow to me, especially for generating a plot, and this is why I want to improve it if possible.


texts: Client for many similar kinds of REST requests

texts:
I have a class that makes calls to a Web API (Using RestSharp), which  works fine but the code is super ugly. What would be the best way to refactor it? I thought of just doing a Facade pattern so all the calls that goes to cart will be in a separate class and order will be in an order class and so on.

All the methods looks very similar maybe I can extract something.

 public class ApiRestClient : IApiRestClient
    {

        private readonly RestClient _client;
        private readonly string _url = ConfigurationManager.AppSettings["webapibaseurl"];

        public ApiRestClient()
        {
            _client = new RestClient(_url);
        }

        public TokenDto Get(Guid id)
        {
            var request = new RestRequest("/cart/{id}", Method.GET) {RequestFormat = DataFormat.Json};
            request.AddParameter("id", id, ParameterType.UrlSegment);

            var response = _client.Execute(request);
            return JsonConvert.DeserializeObject<TokenDto>(response.Content);
        }

        public void SaveOrder(OrderDto order)
        {
            var request = new RestRequest("/order/", Method.POST) {RequestFormat = DataFormat.Json};
            request.AddObject(order);
            _client.Execute<TokenDto>(request);
        }

        public string GetLayout(int? id)
        {
            var request = new RestRequest("/customer/{id}", Method.GET) {RequestFormat = DataFormat.Json};
            request.AddParameter("id", id, ParameterType.UrlSegment);
            var response = _client.Execute(request);
            return JsonConvert.DeserializeObject<CustomerDto>(response.Content).Layout;
        }

        public void UpdateUser(UserDto userMap)
        {
            var request = new RestRequest("/user/", Method.POST) {RequestFormat = DataFormat.Json};
            request.AddObject(userMap);
            _client.Execute<UserDto>(request);
        }

        public IEnumerable<TokenDto> GetInvoices(Guid id)
        {
            var request = new RestRequest("/receipt/{id}", Method.GET) {RequestFormat = DataFormat.Json};
            request.AddParameter("id", id, ParameterType.UrlSegment);

            var response = _client.Execute(request);
            return JsonConvert.DeserializeObject<IEnumerable<TokenDto>>(response.Content);
        }

        public TokenDto GetInvoice(Guid id)
        {
            var request = new RestRequest("/receipt/invoice/{id}", Method.GET) {RequestFormat = DataFormat.Json};
            request.AddParameter("id", id, ParameterType.UrlSegment);

            var response = _client.Execute(request);
            return JsonConvert.DeserializeObject<TokenDto>(response.Content);
        }
    }


texts: Create and open a file to take lecture notes depending on day and time

texts:
I am just wondering what, if any, more elegant ways might exist to write a script to accomplish the task that the script below accomplishes. The script works, so I don't need it to be debugged, but I want to learn more. Other commands to be used, other ways of structuring it, etc. I have taken it through shellcheck.

Yesterday I decided to try my hand at a shell script that would create and open a file to take notes for each of my classes in the folder designated for notes from that class. It was pretty satisfying to do; I started with basically no knowledge and over the course of an hour or two I went from a script that would prompt me to enter the class and the desired file title (read Class read Title if [[ $Class = "X]] then touch /path/"$Title".docx etc) to something that would just create the file in the right place based on the time/date the command is invoked, since the title is always today's date anyhow.

Again, it works. I just know that there must be more ways to skin this cat and I was wondering what those might be. The version below has been revised once after input from some good samaritans.

Also, FWIW, this is running on OS X Sierra.

#!/bin/bash

read date hour day month <<< $(date +"%-d %-H %a %B")
if [[ $hour -lt 11 && $day = "Tue" ]] || [[ $hour -lt 11 && $day = "Thu" ]]; then
    dir="/path/to/first"
elif [[ $hour -gt 12 && $hour -lt 15 && $day = "Tue" ]] || [[ $hour -gt 12 && $hour -lt 15 && $day = "Thu" ]]; then
    dir="path/to/second"
elif [[ $hour -ge 16 && $hour -le 17 && $day = "Wed" ]]; then
    dir="/path/to/third/"
else
    echo "I am of no use to you right now"
    exit 1
fi
file="$dir/$month $date".docx
touch "$file"
open "$file"
killall Terminal


texts:
This is an image representation of my code below:

This is what they do:

CellWithImageX: Subclasses of UITableViewCell. They have an image and an loading indicator. Only 1 can be shown at the time.

ImageRequester: Downloads the images and gives ImageCache a callback when it's done.

FileExplorer: Saves the images.

ImageCache: Manages everything. Since I am most concerned about the current design, I think the code for the ImageCache is only relevant:

// Used to weakly hold the CellWithImageX image classes. (Is this bad?)
open class WeakObjectWrapper<T: AnyObject> {
    public weak var obj: T?

    public init(obj: T) {
        self.obj = obj
    }

}

class ImageCache {

    // I can not understand how it can work if it isn't a singleton.
    // From every cell, I can easily pass the reference without to much hassle.
    // I am not sure for an singleton alternative.
    static let sharedInstance = ImageCache()

    // TODO: Maybe remove some elements from time to time?
    // Yes, this is an array of the images in the table view cell...
    private var loadableImages: [WeakObjectWrapper<LoadableImage>] = []

    private init() {}

    func handleImage(photoIdentifier: Int64, loadableImage: LoadableImage) {
        // Bit concenered about a race condition.
        // I read about DispatchQueues and Semaphores, can't really
        // decide what would be the best way.
        assert(Thread.isMainThread)
        // LoadableImage has an identifier which we can use to later on match the downloaded image.
        loadableImage.identifier = photoIdentifier

        guard photoIdentifier != 0 else {
            loadableImage.show(image: #imageLiteral(resourceName: "anonymous"))

            return
        }

        guard let image = determineImage(photoIdentifier: photoIdentifier) else {
            loadableImages.append(WeakObjectWrapper(obj: loadableImage))
            loadableImage.showIndicator()

            return
        }

        loadableImage.show(image: image)
    }

    func received(image: UIImage, forPhotoIdentifier: Int64) {
        assert(Thread.isMainThread)

        FileExplorer.sharedInstance.save(image: image.pngData()!, photoIdentifier: forPhotoIdentifier) // This is validated that this works, we can safely force unwrap.

        for loadableImage in loadableImages.filter({ $0.obj?.identifier == forPhotoIdentifier }) {
            // While iterating it may occur that the reference is gone.
            loadableImage.obj?.show(image: image)
        }
    }

    private func determineImage(photoIdentifier: Int64) -> UIImage? {
        guard let image = FileExplorer.sharedInstance.determineImage(photoIdentifier: photoIdentifier) else {
            ImageRequester.sharedInstance.download(photoIdentifier: photoIdentifier)

            return nil
        }

        return image
    }
}

In my cellForRowAt method in my tableView, I am calling the ImageCache handleImage method on my cell.loadableImage property.

My concerns:

I am using a few singletons: ImageRequester, ImageCache and
FileExplorer. I am not sure if this is the best approach, but I can
not imagine a better way because this way, all my cells can easily
register themselfs.
I have a array of weak objects which references
to the loadable images inside of a tableViewCell. Isn't there a
better way?
I am asserting I am on the main thread. If I am on multiple threads, race conditions may occur while I loop through the array. I looked into DispatchQueues and Semaphores. I just didn't found the right way to do it, and what the best way would be in my case. Does someone has a suggestion about what way would be a good way in my case?


texts: Check existence of matching key,value pair

texts:
I recently was in an interview where I was asked to implement a snippet that finds the matching key:value pair among two JavaScript arrays in which each member is an object:

var a = [{color:'blue'},{color:'green'}, {color:'brown'}, {color:'black'}]
var b = [{color:'white'},{color:'yellow'}, {color:'black'}, {color:'blue'}]
var expectedOutput = [{color:'blue'}, {color:'black'}]

Here's my implementation:

var a = [{color:'blue'},{color:'green'}, {color:'brown'}, {color:'black'}]
var b = [{color:'white'},{color:'yellow'}, {color:'black'}, {color:'blue'}]
var expectedOutput = [];
for(var i=0; i<a.length; i++){
 if(b[i].hasOwnProperty('color') && a[i].color===b[i].color){
  expectedOutput.push(a[i]);
 }
}

document.write(expectedOutput.toString());

In the interview, I communicated that using .hasOwnProperty() provides \$O(1)\$ lookup for keys (but not for values) from array b, and unfortunately, I wasn't able to fully implement this as my mind wandered across other possibilities there might be, not to mention the pressure.

I believe this still has \$O(n^2)\$ complexity as it simply checks the existence of child .color key as well as a supplementary check against values being equivalent. All in all, I suspect the interviewer was pointing me into this implementation for \$O(n)\$ complexity.

Do you think otherwise? If you do, could you kindly explain why and how? If my question is unclear, how would you solve it in \$O(n)\$ time in JavaScript?


texts: Program to determine total stops taken by elevator

texts:
I was asked a question to write a optimal program that would determine the total number of stops a elevator has taken to serve X number of people.

There is a elevator in a building with M floors. This elevator can take a max of X people at a time or max of total weight Y. Given that a set of people has arrived and their weight and the floor they need to stop given how many stops has the elevator taken to serve all the people. Consider elevator serves in the first come first serve basis.

Example:

Let Array A be the weight of people to be considered A[] = {60, 80, 40 }.

Let Array B be the floors where person needs to be dropped respectively B[] = {2, 3, 5}.

Total building floors be 5,max allowed person in elevator be 2 at a time with max weight capacity being 200. For this example, the elevator would take total of 5 stops floors ground, 2, 3, ground, 5, ground.

What would be the optimal code for this? Is there any other better solutions or ways to improve my code?

class Solution
{
    /// <summary>
    /// Return total stops used
    /// </summary>
    /// <param name="A">weight of people</param>
    /// <param name="B">floors they need to get down</param>
    /// <param name="M">total floors in the building</param>
    /// <param name="X">Max people to carry at a time</param>
    /// <param name="Y">max weight to carry at a time</param>
    /// <returns></returns>
    public int solution(int[] A, int[] B, int M, int X, int Y)
    {
        // initialize variables
        int totalStops = 0;
        long totalWeightPerRound = 0;
        int maxPersonsCount = 0;
        List<int> lstFloors = new List<int>();
        int currPerson = 0;
        bool startLift = false;
        while (currPerson < A.Length)
        {
            //Should current person be considered?
            if ((totalWeightPerRound + A[currPerson]) <= Y && (maxPersonsCount+1) <= X)
            {
                totalWeightPerRound += A[currPerson];
                maxPersonsCount++;
                lstFloors.Add(B[currPerson]);
                //If curr person is last person then start the lift
                if (currPerson == A.Length - 1)
                    startLift = true;

                currPerson++;
            }
            else
            {
                startLift = true;
            }

            if (startLift)
            {
                totalStops += lstFloors.Distinct().Count() + 1;
                //reset variable
                lstFloors.Clear();
                maxPersonsCount = 0;
                totalWeightPerRound = 0;
                startLift = false;
            }
        }

        return totalStops;
    }
}


texts:
This post builds on my post about quickly evaluating analytic Jacobian in Matlab.

The key difference is that I am now working with the Hessian and I have to evaluate close to 700 matlabFunctions (instead of one matlabFunction like I did for the Jacobian) each time the hessian is evaluated. So there is an opportunity to do things a little differently.

I have tried to do this two ways so far and I am thinking about implementing a third. I will go through each method with a toy example, but first some preprocessing to generate these matlabFunctions:

PreProcessing:

% This part of the code is calculated once, it is not the issue
dvs = 5;
X=sym('X',[dvs,1]);
num = dvs - 1; % number of constraints

% multiple functions
for k = 1:num
    f1(X(k+1),X(k)) = (X(k+1)^3 - X(k)^2*k^2);
    c(k) = f1;
end

gradc = jacobian(c,X).'; % .' performs transpose

parfor k = 1:num
    hessc{k} = jacobian(gradc(:,k),X);
end

parfor k = 1:num
    hess_name = strcat('hessian_',num2str(k));
    matlabFunction(hessc{k},'file',hess_name,'vars',X);
end

METHOD #1 : Evaluate functions in series

%% Now we use the functions to run an "optimization." Just for an example the "optimization" is just a for loop

fprintf('This is test A, where the functions are evaluated in series!\n');
tic
for q = 1:10

    x_dv = rand(dvs,1);   % these are the design variables
    lambda = rand(num,1); % these are the lagrange multipliers

    x_dv_cell = num2cell(x_dv); % for passing large design variables

    for k = 1:num
        hess_name = strcat('hessian_',num2str(k));
        function_handle = str2func(hess_name);
        H_temp(:,:,k) = lambda(k)*function_handle(x_dv_cell{:});
    end

    H = sum(H_temp,3);

end
fprintf('The time for test A was:\n')
toc

METHOD # 2: Evaluate functions in parallel

%% Try to run a parfor loop

fprintf('This is test B, where the functions are evaluated in parallel!\n');
tic
for q = 1:10

    x_dv = rand(dvs,1);   % these are the design variables
    lambda = rand(num,1); % these are the lagrange multipliers

    x_dv_cell = num2cell(x_dv); % for passing large design variables

    parfor k = 1:num
        hess_name = strcat('hessian_',num2str(k));
        function_handle = str2func(hess_name);
        H_temp(:,:,k) = lambda(k)*function_handle(x_dv_cell{:});
    end

    H = sum(H_temp,3);

end
fprintf('The time for test B was:\n')
toc

RESULTS:

METHOD #1 = 0.008691 seconds

METHOD #2 = 0.464786 seconds

DISCUSSION of RESULTS

This result makes sense because, the functions evaluate very quickly and running them in parallel waists a lot of time setting up and sending out the jobs to the different Matlabs ( and then getting the data back from them). I see the same result on my actual problem.

METHOD # 3: Evaluating the functions using the GPU

I have not tried this yet, but I am interested to see what the performance difference is. I am not yet familiar with doing this in Matlab and will add it once I am done.

Any other thoughts?


texts: Separate combined words in a sentence and convert them into Pig Latin

texts:
My program is complete and working, but I would like second opinions on it.

Here are the instructions for the assignment:

  The program will accept a string as input in which all of the words are run together, but the first character of each word is uppercase.
  Convert the string to a string in which the words are separated by
  spaces and only the first word starts with an uppercase letter. For
  example, the string "StopAndSmellTheRoses" would be converted to "Stop
  and smell the roses".
  Then the program will convert each word in the result string of task 1 into "Pig Latin". In one version of Pig Latin, you convert a
  word by removing the first letter, placing that letter at the end of
  the word, and then appending "ay" to the word.

  For example, for the result string "Stop and smell the roses" in task
  1, the Pig Latin string should be "topSay ndaay mellsay hetay osesray".

  Requirements:

  Your program should have 3 methods: a main method, a method for task    1, and a method for task2.
  The method for task 1 should return the result string of task1.
  The method for task 2 should display the Pig Latin string.

import java.util.Scanner;
public class Assignment9
{
    public static void main(String[] args)
    {
    // Variables
    String sentence, revisedSentence, latin = " ";

    // Create a Scanner object for keyboard input
    Scanner keyboard = new Scanner(System.in);

    // Get the input string
    System.out.print("Enter sentence: ");
    sentence = keyboard.nextLine();

    //Close keyboard
    keyboard.close();

    // Task 1
    revisedSentence = WordSeparator(sentence);

    System.out.print("Revised Sentence: " +revisedSentence);

    // Task 2
    PigLatin(revisedSentence, latin);

    System.exit(0);
}

private static String WordSeparator(String sentence)
{
    // Variables
    StringBuilder str = new StringBuilder(sentence);
    int i = 1;

    // While loop repeats until the end of the sentence
    while (i < str.length())
    {
        // Checks for upper case characters
        if(Character.isUpperCase(str.charAt(i)))
        {
            //Inserting space
            str.insert(i, ' ');
            char ch = Character.toLowerCase(str.charAt(i+1));
            str.setCharAt((i+1), ch);
        }
        i++;
    }
    return str.toString();
}

private static void PigLatin(String revisedSentence, String latin)
{
    // Split sentence by spaces
    String[] tokens = revisedSentence.split(" ");

    // Store all the words into an array
    String[] arr = new String[tokens.length];

    // Convert English sentence into Pig Latin
    for (int i = 0; i < tokens.length; i++)
    {
        // Get string from array
        String str = tokens[i];

        // Get first letter from string
        String str1 = str.substring(0, 1);

        // Get substring from string
        String str2 = str.substring(1, str.length());

        // Concatenate the two strings in a required format
        str2 = str2.concat(str1);

        // Concatenate the result and "AY"
        str2 = str2.concat("ay");

        // Store all of the strings into an array
        arr[i] = str2;

        // Make a sentence with all the words
        latin = latin.concat(str2 + " ");
    }

    // Display pig latin verison
    System.out.println("\nPig Latin Version:" +latin );
    }

}


texts: Implementing "Pierre the Tight-rope" Walker from LYAH

texts:
Learn You a Haskell presents an excellent introduction to >>= with an example.

Basically, Pierre is a tight-rope walker that has Birds (Int) on each side of his tight-rope (represented by a tuple (Int, Int)). Birds can land on each side (only one side at a time) with addRight and addLeft. If the difference of birds on left and right is > 4, then Pierre falls.

LYAH says to use the Error Monad:

  As an exercise, you can rewrite that with the error monad so that when the
  tightrope walker slips and falls, we remember how many birds were on each side
  of the pole when he fell.

Here's how I implemented it (but LYAH provided the type synonyms):

-- @author: LYAH
type Birds = Int
type Pole = (Birds, Birds)

addLeft :: Birds -> Pole -> Either Pole Pole
addLeft n (x, y) = let newLeft = x + n
                       newPole = (newLeft, y)
                       diff    = abs (newLeft - y)
                   in if (diff > 4) then Left  newPole
                      else               Right newPole

addRight :: Birds -> Pole -> Either Pole Pole
addRight n (x, y) = let newRight = y + n
                        newPole = (x, newRight)
                        diff    = abs (x - newRight)
                    in if (diff > 4) then Left  newPole
                       else               Right newPole

walkTightRope :: Either Pole Pole
walkTightRope = addLeft 2 (0,0) >>= addRight 4

walkTightRopeFailed :: Either Pole Pole
walkTightRopeFailed = addLeft 2 (0,0) >>= addRight 10 >>= addLeft 2

walkTightRopeDo :: Either Pole Pole
walkTightRopeDo = do
    p1 <- addLeft 2 (0,0)
    p2 <- addRight 1 p1
    return p2

Please critique my implementation.


texts: Implementing Functor Instance for `ITree`

texts:
Looking at this Typeclassopedia exercise, I typed out foldTree on the following type:

data ITree a = Leaf (Int -> a) | Node [ITree a]

And my implementation of Functor:

instance Functor (ITree) where
    fmap = iTreeMap

iTreeMap :: (a -> b) -> ITree a -> ITree b
iTreeMap f (Leaf x)  = Leaf $ fmap f x
iTreeMap f (Node xs) = Node $ map (iTreeMap f) xs

Please critique its signature, correctness and style.


texts:
I have coded a sudoku grid validator as a problem set from an online course.

My input to the validator is a list of lists, that represents a sudoku grid. For reference, below are examples of an ill-formed sudoku grid, an invalid one, and a valid one.

# check_sudoku should return None
ill_formed = [[5,3,4,6,7,8,9,1,2],
              [6,7,2,1,9,5,3,4,8],
              [1,9,8,3,4,2,5,6,7],
              [8,5,9,7,6,1,4,2,3],
              [4,2,6,8,5,3,7,9],  # <---
              [7,1,3,9,2,4,8,5,6],
              [9,6,1,5,3,7,2,8,4],
              [2,8,7,4,1,9,6,3,5],
              [3,4,5,2,8,6,1,7,9]]

# check_sudoku should return True
valid = [[5,3,4,6,7,8,9,1,2],
         [6,7,2,1,9,5,3,4,8],
         [1,9,8,3,4,2,5,6,7],
         [8,5,9,7,6,1,4,2,3],
         [4,2,6,8,5,3,7,9,1],
         [7,1,3,9,2,4,8,5,6],
         [9,6,1,5,3,7,2,8,4],
         [2,8,7,4,1,9,6,3,5],
         [3,4,5,2,8,6,1,7,9]]

# check_sudoku should return False
invalid = [[5,3,4,6,7,8,9,1,2],
           [6,7,2,1,9,5,3,4,8],
           [1,9,8,3,8,2,5,6,7],
           [8,5,9,7,6,1,4,2,3],
           [4,2,6,8,5,3,7,9,1],
           [7,1,3,9,2,4,8,5,6],
           [9,6,1,5,3,7,2,8,4],
           [2,8,7,4,1,9,6,3,5],
           [3,4,5,2,8,6,1,7,9]]

My code for the validator is the following:

def check_sudoku(grid):
    """ Gets a list of lists as input, and returns None for ill-formed
    Sudoku grids, False for invalid ones, and True for valid.
    """
    assert type(grid) == list

    # First, we need to make sure that the grid is 9x9.
    if len(grid) != 9:
        return None
    row_len = map(lambda x: len(x) == 9, grid)
    if False in row_len:
        return None

    # next we need to make sure that the numbers are between 0 and 9
    max_len = map(max, grid)
    min_len = map(min, grid)
    more_than_ten  = filter(lambda x: x > 9, max_len)
    less_than_zero = filter(lambda x: x < 0, min_len)
    if len(more_than_ten) or len(less_than_zero):
        return False

    # now we need to make sure that each number is present only one time in a row
    one_per_row = map(lambda x: len(set(x)) == 9, grid)
    if False in one_per_row:
        return False

    # and next up is making sure that each number is present only one time in a column
    # to do that, we want to follow the previous procedure, but for it to be valid, we
    # shall first need to turn each column into a line
    columns_to_lines = []
    for i in range(0, 9):
        column = []
        for z in range(0, 9):
            column.append(grid[i][z])
        columns_to_lines.append(column)
    one_per_column = map(lambda x: len(set(x)) == 9, columns_to_lines)
    if False in one_per_column:
        return False

    # for the last check, we need to ensure that each number is unique in the 3x3 grids
    # we can do this by creating a single 9 list element out of the 3x3 grid, and perform
    # the same procedure as above.
    three_times_three = []
    first_one   = []
    second_one  = []
    third_one   = []
    times_break = 0
    for i in range(0, 9):
        first_one.append(grid[i][0:3])
        second_one.append(grid[i][3:6])
        third_one.append(grid[i][6:9])
        times_break += 1
        if times_break > 2:
            three_times_three.append(first_one)
            three_times_three.append(second_one)
            three_times_three.append(third_one)
            first_one  = []
            second_one = []
            third_one  = []
            times_break = 0

    # collapse the lists because they now contain sublists, making it
    # slightly icky for the rest of the pipeline
    three_times_three = map(lambda l: sum(l, []), three_times_three)
    one_per_three_box = map(lambda x: len(set(x)) == 9, three_times_three)
    if False in one_per_three_box:
        return False

    return True

I wrote it all in functional style - that's what you get after a whole summer full of Scheme. My question is, is this considered high quality readable code? Would you consider it hard to read instead? If so why? What could you do better?


texts:
using System;

namespace Friendly_Bot
{
    internal class Program
    {
        private static string[] Greetings = { "Hello, you have a", "Hey, you have a", "Hi, you have a" };
        private static string[] Compliments = { "cool", "fashionable", "stylish" };
        private static string[] Garments = { "coat.", "dress.", "shirt.", "skirt.", "suit.", "swimsuit." };
        private static string[] Farewells = { "ADIOS!", "BYE!", "BYE-BYE!", "FAREWELL!", "GOODBYE!" };

        private static string Greeting;
        private static string Compliment;
        private static string Garment;
        private static string Farewell;
        private static string Message;

        private static void Main(string[] args)
        {
            GenerateMessage();
        }

        private static void GenerateMessage()
        {
            int i = new Random().Next(1, 11);

            //20% chance of including a farewell in the message.
            if (i < 3)
            {
                Greeting = Greetings[new Random().Next(0, Greetings.Length)];
                Compliment = Compliments[new Random().Next(0, Compliments.Length)];
                Garment = Garments[new Random().Next(0, Garments.Length)];
                Farewell = Farewells[new Random().Next(0, Farewells.Length)];
                Message = Greeting + " " + Compliment + " " + Garment + " " + Farewell;
                Console.WriteLine(Message);
                Console.ReadLine();
            }
            //80% chance of NOT including a farewell in the message.
            else
            {
                Greeting = Greetings[new Random().Next(0, Greetings.Length)];
                Compliment = Compliments[new Random().Next(0, Compliments.Length)];
                Garment = Garments[new Random().Next(0, Garments.Length)];
                Message = Greeting + " " + Compliment + " " + Garment;
                Console.WriteLine(Message);
                Console.ReadLine();
            }
        }
    }
}

This code will piece together a random message with the contents in 4 separate arrays: Greetings, Compliments, Garments, Farewells.

There is a 20% chance of the randomly generated message including a farewell at the end of the message. There is an 80% chance for the message not to include a farewell exclamation in the message.

How can I clean this code up and make it produce the same product, but more efficiently? Any help is greatly appreciated! :)


texts: Best C# idiom to convert the items on an object array to a string?

texts:
I have something akin to

object[] values = getValues();
string renderedValues = string.Join("-",
                          Array.ConvertAll<object,string>(values,
                          new Converter<object,string>(o2s)
                        ));

where o2s is

public static string o2s(object o) { return o.ToString(); }

Comments welcome!


texts: Scraping the Bundesliga table and saving it to CSV

texts:
Wrote my first mini-script to get data from the german football league table and save the data to a csv file. Do you like the approach or could I be more efficient? Thanks in advance!

from bs4 import BeautifulSoup
import requests
import csv

url = "https://www.bundesliga.com/de/bundesliga/tabelle"

r = requests.get(url)

r_soup = BeautifulSoup(r.content, "lxml")

table = r_soup.find_all("tr")

csv_file = open("bundesliga_table.csv", "w")

csv_writer = csv.writer(csv_file)
csv_writer.writerow(["Rank", "Team", "Matches", "Points", "Goal Difference"])

for club in table:
    try:
        rank = club.find("td", class_="rank").text
        team = club.find("span", class_="d-none d-lg-inline").text

        matches = club.find("td", class_="matches").text
        points = club.find("td", class_="pts").text
        difference = club.find("td", class_="difference").text

        print(str(rank) + " " + str(team) + " " + str(matches) + " " + str(points) + " " + str(difference))
        csv_writer.writerow([rank, team, matches, points, difference])

    except:
        print("One team not found")

csv_file.close()


texts:
Consider, please, my code of the finalizer template:

#include <functional>

template<typename F, typename... Args>
class finally
{
public:

  finally(F action, const Args&... args) :
      _action(std::bind(action, args...))
  {}
  ~finally()
  {
    if(enabled)
      _action();
  }

  bool enabled = true;

private:

  std::function<void()> _action;
};

In particular I would enhance this template to avoid of using a typenames twice. Let's say we need to close some file on leaving some block of code. Then we declare an object:

finally<int(int), int> f(close, some_file);

Here I used the standard close function as an action. But I should use int twice in the <int(**int**), **int**>. Is there any way to avoid this?


texts:
This is my first validator I have created myself and I was wondering if there is anything about it that I could improve as far as:

Code readability
Code efficiency

Note: The reason why I put an underscore before each validation method name is so that non-validation methods cannot be called. E.g. setRule() can't be called if it's specified in the rule unless there is an actual validation method called "_setRule".

Any other suggestions are also welcome!

Validator class:

class Validator
{
    private $rules  = [];
    private $errors = [];

    public function setRule($id, Array $methods)
    {
        if (!array_key_exists($id, $this->rules)) {
            $this->rules[$id] = $methods;
        } else {
            throw new Exception('Rule "' . $id . '" already exists.');
        }
    }

    public function setRules(Array $rules) {
        foreach ($rules as $key => $value) {
            $this->setRule($key, $value);
        }
    }

    public function validate($rule, $input)
    {
        foreach ($this->rules[$rule] as $key => $value) {
            if (is_int($key)) { //$key => rule
                $value     = '_' . $value;
                $method    = $value;
                $arguments = [$input];
            } else {            //rule => [args]
                $key       = '_' . $key;
                $method    = $key;
                $arguments = array_merge([$input], is_array($value) ? $value : [$value]);
            }

            return call_user_func_array([$this, $method], $arguments);
        }
    }

    public function setError($error)
    {
        return $this->errors[] = $error;
    }

    public function getErrors()
    {
        return $this->errors;
    }

    private function _required($input)
    {
        return empty($input) ?: $this->errors[] = substr(__FUNCTION__, 1);
    }

    private function _min($input, $min)
    {
        return mb_strlen($input, 'utf8') >= $min ?: $this->errors[] = substr(__FUNCTION__, 1);
    }

    private function _max($input, $max)
    {
        return mb_strlen($input, 'utf8') <= $max ?: $this->errors[] = substr(__FUNCTION__, 1);
    }

    private function _between($input, $min, $max)
    {
        if ($return = $this->_min($input, $min) !== true) {
            return $this->errors[] = $return;
        }

        if ($return = $this->_max($input, $max) !== true) {
            return $this->errors[] = $return;
        }

        return true;
    }

    private function _email($input)
    {
        $sanitizedInput = filter_var($input, FILTER_SANITIZE_EMAIL);
        $vInput         = filter_var($sanitizedInput, FILTER_VALIDATE_EMAIL);

        return $input === $sanitizedInput && $vInput ?: $this->errors[] = substr(__FUNCTION__, 1);
    }

    private function _alnum($input)
    {
        return ctype_alnum($input) ?: $this->errors[] = substr(__FUNCTION__, 1);
    }
}

Sample usage:

$v = new Validator();

$v->setRule('email', ['required', 'between' => [5, 255], 'email']);
$v->setRule('password', ['required']);

$vEmail        = $v->validate('email', $_POST['email']);
$vEmailConfirm = $v->validate('email', $_POST['emailConfirm']);
$vPassword     = $v->validate('password', $_POST['password']);

if ($vEmailConfirm === true && $_POST['email'] !== $_POST['emailConfirm']) {
    $vEmailConfirm = $v->setError('match');
}

if (!$v->getErrors()) {
    # Input(s) have passed validation
} else {
   # Input(s) have not passed validation
   # $vEmail, $vEmailConfirm and $vPassword contain the errors
   # You can do something with that, like displaying an error message
}


texts: Object pool with linked list of available objects implementation

texts:
I was reading some gameprogrammingpatterns (awesome book, by the way, would recommend) and was very excited when I learned that unions are a thing that exists, so I decided to implement an object pool as outlined there.

I'm looking for a review of the usual culprits. Poor readability, not making use of standard library stuff/language features. But more than that, I'd love it if someone could point out how I could improve the access and removal algorithms, as well as an elegant way that I could have duplicates in the list.

What I mean by "doesn't allow duplicates", by the way, is that duplicates are considered equally, so if it's of type int, and there are the values {1, 2, 3, 3, 4, 5} in the pool, and you call removeObj(3), the first 3 that is come across will be "deleted", regardless of what you actually wanted.

#include <vector>

//Doesn't allow duplicates
//O(1) insertion
//O(n) removal
//O(n) access

template <class T>
class Pool
{
    private:

        struct Object
        {
            bool available;
            union
            {
                T data;
                Object* next;
            }state;
        };

        int size = 0;
        int numAlive = 0;

        Object* nextAvailable = nullptr;
        std::vector< Object > objs;

    public:
        Pool();
        Pool(int size);

        bool create(T newObj);
        std::vector<T*> getAlive();
        bool removeObj(T toDel);
};

template <class T>
Pool<T>::Pool()
{
}

template <class T>
Pool<T>::Pool(int size):size(size)
{
    objs = std::vector< Object >(size);

    //All are available
    for(int i = 0; i < objs.size() - 1; i++)
    {
         objs[i].state.next = &objs[i+1];
    }

    objs[objs.size()-1].state.next = nullptr; //Last one terminates list

    nextAvailable = &objs[0];
}

template <class T>
bool Pool<T>::create(T newObj)
{
    if(nextAvailable == nullptr)
    {
        return false;
    }

    Object* newO = nextAvailable;
    nextAvailable = nextAvailable->state.next;

    newO->state.data = newObj;
    newO->available = false;
    numAlive++;

    return true;
}

template <class T>
std::vector<T*> Pool<T>::getAlive()
{
    std::vector<T*> avl = std::vector<T*>(numAlive);
    int cnt = 0;
    for(auto& o : objs)
    {
        if(!o.available)
        {
            avl.at(cnt++) = &(o.state.data);
        }
    }

    return avl;
}

template <class T>
bool Pool<T>::removeObj(T toDel)
{
    for(auto& ob: objs)
    {
        if(!ob.available && ob.state.data == toDel)
        {
            ob.state.next = nextAvailable;
            ob.available = true;
            nextAvailable = &ob;
            numAlive--;
            break;
        }
    }
}


texts: Singleton Design Pattern implementation in a not traditional way

texts:
For implementing Singleton we can use Traditional way like this Article,
but i think that to write it in another way:

 public class Person
 {
    private static Person personInstance;
    static Person()
    {
        personInstance = new Person();
    }
    private Person() { }

    public static Person GetPersonInstance()
    {
        return personInstance;
    }
}

As we know a Static Constructor will call automatically before the first instance is created or any static members are referenced and just once only. so if i write singleton like above, is it true (i mean this class is singleton)? or not?


texts:
Working on a project that parses through an excel document to find price changes off of a webservice that is in place. The code works but is slower than expected. At first it was processing 28 products a minute, and now after some work I have it up to 80 products a minute.

I've used Jetbrains dottrace to determine the bottleneck is on this line of code

 xmlstr = wc.DownloadString(@"http://awebsiteservice/prices?SearchString=" + UPC);

I used System.Net.WebClient to make the calls thinking it was the fastest way.

I've done some research and do not know if there is a way to eliminate this bottleneck or not. I am posting the code below for general code review, and also in hopes that there is something simple I am missing that can help the API calls go faster or smoother.

 private static void PriceDifferences(ExcelWorksheet ws, int maxval)
    {
        bool looping = true;
        int i = 2;
        var wc = new WebClient();
        XmlDocument xml = new XmlDocument();
        string xmlstr;
        Console.WriteLine("Press X to save results and stop process");
        do
        {
            if (Console.KeyAvailable)
            {
                if (Console.ReadKey(true).Key == ConsoleKey.X)
                {
                    looping = false;
                }
            }

            if (ws.Cells[i, 8].Value != null)
            {
                if (DateTime.ParseExact(ws.Cells[i, 8].Value.ToString(), "M/dd/yyyy", null) >= DateTime.Now.AddDays(-5).Date)   //If analysis ran in last 5 days skip
                {
                    i++;
                    continue;
                }
            }

            var UPC = ws.Cells[i, 1].Value;
            var cPrice = ws.Cells[i, 2].Value;

            ws.Cells[i, 8].Value = DateTime.Now.Date.ToShortDateString();

            //Console.WriteLine("UPC is {0}, Current Price is {1}, and Lowest Price known is {2}", UPC, cPrice, lPrice);
            //Console.WriteLine("Checking for price differences");

            try
            {
                xmlstr = wc.DownloadString(@"http://awebsiteservice/prices?SearchString=" + UPC);
            }
            catch
            {
                continue;
            }

            xml.LoadXml(xmlstr);

            XmlNodeList refList = xml.GetElementsByTagName("Store");
            List<string> pricelist = new List<string>();

            GetTrustedPrices(refList, pricelist);
            UpdatePrices(ws, pricelist, i, cPrice);

            i++;
            Console.WriteLine(i);

        }
        while (looping && i < maxval);
    }

The functions GetTrustedPrices and UpdatePrices are below

private static void GetTrustedPrices(XmlNodeList refList, List<string> pricelist)
    {
        foreach (XmlNode node in refList)
        {
            if (node.ChildNodes[2].InnerText == "Trusted")
            {
                pricelist.Add(node.ChildNodes[4].ChildNodes[2].InnerText);
            }
        }
    }

private static void UpdatePrices(ExcelWorksheet ws, List<string> pricelist, int i, object cPrice)
    {
        List<double> result = pricelist.Select(x => double.Parse(x)).ToList();

        if (result.Count <= 0) return;
        result = result.Where(itm => itm >= 1).ToList();
        if (result.Count <= 0) return;

        var lowest = result.Min();
        if (!((double) cPrice > lowest)) return;
        ws.Cells[i, 6].Value = lowest;
        ws.Cells[i, 7].Value = lowest - (double) cPrice;
    }


texts: Parsing NSDictionary from NSJSONSerialization

texts:
playerObject is an NSDictionary from JSONObjectWithData:options:error.

I'm trying to update a CoreData entity.

if ([results count] > 0)
{
    newPlayer = (Player *)[results objectAtIndex:0];
} else {
    //Add a new player
    newPlayer = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:temporaryContext];
}
//Assume these exist and are not null
newPlayer.email = [playerObject objectForKey:@"email"];
newPlayer.username = [playerObject objectForKey:@"username"];
newPlayer.continent = [playerObject objectForKey:@"continent"];

//Dates
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
newPlayer.created = [df dateFromString: [playerObject objectForKey:@"created"]];

//Optional properties
if ([[playerObject objectForKey:@"title"] isKindOfClass:[NSNull class]])
{
    newPlayer.title = nil;
} else {
    newPlayer.title = [[playerObject objectForKey:@"title"] stringValue];
}

Is there any way to make it less verbose?  Have I left myself open to any issues?


texts:
I'm working on a clicker game in Tkinter that is very different from Bubble Blaster:

from tkinter import *
from tkinter.messagebox import *
from time import sleep
import math

extraCashCost = 50

class AppUI(Frame):

    def __init__(self, master=None):
        self.saves = open("self.saves.log", "r")
        self.savesEdit = open("self.saves.log", "a")
        self.saveSring = ''.join(self.saves.read())

        Frame.__init__(self, master, relief=SUNKEN, bd=2)

        self.menubar = Menu(self)

        menu = Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Game", menu=menu)
        menu.add_command(label="Open Store", command=lambda:storewin())
        menu.add_command(label="Browse Saves", command=lambda:showinfo("WIP", "This is a work in progress game"))

        menu = Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Edit", menu=menu)
        menu.add_command(label="Open the developer window", command=lambda:devwin())

        try:
            self.master.config(menu=self.menubar)
        except AttributeError:
            # master is a toplevel window (Python 1.4/Tkinter 1.63)
            self.master.tk.call(master, "config", "-menu", self.menubar)

        self.money = 0
        self.cashGet = 1
        self.moneyShow = Label(root, text="$" + str(self.money))
        self.moneyGet = Button(root, text="Get Money!", command=lambda:cashin(self.cashGet))
        self.moneyGet.pack(side=BOTTOM)
        self.moneyShow.pack()

def cashin(cash):
    sleep(0.125)
    app.money += int(cash)
    app.moneyShow.config(text="$" + str(app.money))
def devcashadd(moneyz):
    app.money += int(moneyz)
    app.moneyShow.config(text="$" + str(app.money))
def devwin():
    dev = Tk()
    dl = Label(dev, text="Welcome to the developer window. \n Here you will have access to developer tools. \n This is available only in developer versions.").pack()
    mcl = Label(dev, text="Enter a number below and press the button under it to get free money!")
    mc = Entry(dev)
    mca = Button(dev, text="Get Money", command=lambda:devcashadd(mc.get())).pack()
    mc.pack()
    dev.mainloop()
def ec(cs):
    global extraCashCost
    if app.money >= extraCashCost:
        extraCashCost = math.ceil(extraCashCost * 2.2)
        app.money -= extraCashCost
        app.cashGet *= 1.6
        app.moneyShow.config(text="$" + str(app.money))
        cs.config(text="$" + str(extraCashCost))

def storewin():
    global extraCashCost
    store = Tk()
    extraCashShow = Label(store, text="$" + str(extraCashCost))
    extraCash = Button(store, text="More Money!", command=lambda:ec(extraCashShow))
    extraCashShow.pack()
    extraCash.pack()
    store.mainloop()

root = Tk()

app = AppUI(root)
app.pack()

root.mainloop()

It is going to be on GitHub soon. Anything that could be changed to make it run faster?
And also, how can I put custom styles on the widgets?
Like background gradients, images, etc...


texts: Python 3.6 Dice Histogram: Using random.seed effectively

texts:
I am not 100% sure that I am using the random.seed correctly for this assignment, or if there is a more efficient way to write the code. Any feedback is appreciated.

Assignment Description:
Simulate rolling 2 die one hundred times. Keep track of the total of the two die. Print a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character, such as *, that number of times

import random
random.seed(2)
# declaring an array to count the occurrences
a= [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

# looping for 100 times and saving the count in array
for i in range(100):
    x = random.randint(1,6)
    y = random.randint(1,6)
    a[x+y] = a[x+y] + 1

# printing histogram
for i in range(2, 13):
    print(str(i).rjust(2)+"s: ","*"*a[i])


texts: Implementation of calculation of gamma for RBF SVM

texts:
I have implemented the calculation of gamma value for RBF SVM as described in Liu et al (2012) [https://ieeexplore.ieee.org/abstract/document/6246300]. Here's a snapshot of the example from the paper:

Here is my implementation in MATLAB:

% Let data be a table type variable with 1st column having class label and
% variables X1 ... Xn from 2nd column onwards

% Split data by class
data_class0 = data{data.Class==0,2:end};
data_class1 = data{data.Class==1,2:end};

% Calculate within class squared Euclidean distances
d_within_class0 = squareform(pdist(data_class0, 'squaredeuclidean'));
d_within_class1 = squareform(pdist(data_class1, 'squaredeuclidean'));

% Calculate between class squared Euclidean distances
d_between_class = pdist2(data_class0, data_class1, 'squaredeuclidean');

% Calculate average W and B values
W = mean([d_within_class0(:); d_within_class1(:)], 'all');
B = mean(d_between_class(:));

% Calculate optimal gamma
if B > W
    gamma = sqrt((B-W)/(4*log(B/W)));
else
    disp('Gamma cannot be calculated as B < W');
end

I am looking for feedback on whether or not this implementation is correct and any thing that might need improvement.


texts: Merge sort implementation using iterators

texts:
Here is my first try to implement merge sort using iterators -

#include <algorithm>
#include <iterator>
#include <vector>

namespace base {
namespace merge {

    template <typename Iterator, typename Compare>
    void mergeBack(Iterator begin, Iterator mid, Iterator end, Compare comp)
    {
        typedef typename std::iterator_traits<Iterator>::value_type ElemType;
        std::vector<ElemType> left, right;

        left.reserve(mid - begin);
        right.reserve(end - mid);

        std::copy(begin, mid, std::back_inserter(left));
        std::copy(mid, end, std::back_inserter(right));

        size_t j = 0, k = 0;
        auto i = begin;
        for (; i != end && j < left.size() && k < right.size(); ++i) {
            *i = comp(left[j], right[k]) ? left[j++] : right[k++];
        }

        while (j < left.size()) {
            *(i++) = left[j++];
        }

        while (k < right.size()) {
            *(i++) = right[k++];
        }
    }

    template <typename Iterator, typename Compare = std::less<>>
    void sort(Iterator begin, Iterator end, Compare comp = Compare())
    {
        if (end - begin > 1) {
            const auto middle = (end - begin) / 2;
            merge::sort(begin, begin + middle, comp);
            merge::sort(begin + middle, end, comp);
            mergeBack(begin, begin + middle, end, comp);
        }
    }
}
}

I'm open to advice/suggestions about the implementation and would love to hear how I could make it better.


texts: SPOJ ADDREV challenge - Adding reversed numbers

texts:
I'm a beginner Python (2.7) programmer, and I've just started solving basic problems on SPOJ. I correctly solved the ADDREV problem (http://www.spoj.com/problems/ADDREV/), however my code takes 0.06s time and 8.8M memory to run. The top Python 2.7 rankers for the problem take <0.005s and 4.00M. Since I am starting out and this is a simple code snippet, I would love to get specific tips on how I can optimise the code below to reach these levels of efficiency. I am reading popularly available tips to optimise Python code, including the use of profilers, however I would really appreciate any tips I can already get here.
The problem as described there:

Input
The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.
Output
For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.

(Source: http://www.spoj.com/problems/ADDREV/)
Here's the code:
def reverse(num):   # Takes a string as input and reverses it, removing any leading or trailing zeros
    num = num.strip("0")
    return num[::-1]

num_cases = input()

for i in range(0, num_cases):
    usr_input = raw_input()
    arr = usr_input.split()
    reversed_sum = int(reverse(arr[0])) + int(reverse(arr[1]))
    print reverse(str(reversed_sum))


texts: Check if array contains contiguous integers with duplicates allowed in Java

texts:
Given an array of n integers(duplicates allowed). Print “Yes” if it is
  a set of contiguous integers else print “No”.

  INPUT: The first line consists of an integer T i.e. the number of test
  cases. First line of each test case consists of an integer n, denoting
  the size of array. Next line consists of n spaced integers, denoting
  elements of array.

  OUTPUT:  Print “Yes” if it is a set of contiguous integers else print
  “No”.

  CONSTRAINTS: 1<=T<=100 1<=n<100000 a[i]<=105

  Example:

2
8
5  2  3  6  4  4  6  6
7
10  14  10  12  12  13  15

  Output :  Yes  No

  Explanation: Test Case 1 : The elements  of array form a contiguous
  set of integers which is {2, 3, 4, 5, 6} so the output is Yes. Test
  Case 2: We are unable to form contiguous set of integers using
  elements of array.

My approach:

/*package whatever //do not write package name here */

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

class GFG {

    private static void checkContig (int [] arr, int n)
        {
            Set <Integer> set = new HashSet <>();

            for (int elem:arr)
                {
                    set.add(elem);
                }

            List <Integer> arrNoReps = new ArrayList <>();
            arrNoReps.addAll(set);
            Collections.sort(arrNoReps);

            int first = arrNoReps.get(0);
            int last = first + arrNoReps.size() - 1;

            for (int i = first; i <= last; i++)
                {
                    if( !arrNoReps.contains(i))
                        {
                            System.out.println("No");
                            return;
                        }
                }
            System.out.println("Yes");
        }

    public static void main (String[] args) throws IOException {
        BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
        String line = br.readLine();

        int T = Integer.parseInt(line);
        String line2;
        String line3;
        String [] inps;
        int n;
        for (int i = 0; i < T; i++)
            {
                line2 = br.readLine();
                n = Integer.parseInt(line2);
                int [] arr = new int[n];
                line3 = br.readLine();
                inps = line3.split(" ");
               // System.out.println(n);
                for (int j = 0; j < n; j++)
                    {
                        arr[j] = Integer.parseInt(inps[j]);
                        //System.out.println(inps[j]);
                    }
                checkContig(arr,n);
            }
    }
}

I have the following questions with regards to the code written above:

1) Does there exist a smarter way to solve this question?

2) Am I violating some serious Java coding conventions?

3) How can I improve my time and space complexity?

4) Can I use some different data structures which can solve the question faster?

Source


texts: Move image files according to watermark identified by a neural networks

texts:
I have created a neural network that can identify watermarks and can classify them to which company do they belong. Now I created a script that will identify watermark from a folder and move them to different folders where they belong. But this script is quite slow and consumes too much RAM. What should I do to improve it?

from keras.preprocessing.image import img_to_array
from keras.models import load_model
import numpy as np
import argparse
import imutils
import pickle
import cv2
import os
import time
import glob
import shutil
import csv
d = glob.glob("colabData/Krishna/*.jpg")
print("Total Number of Images are :" ,len(d))

count = 0
final_data = []
def convertToRGB(img):
    return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

for images in d:
    count += 1
    test1 = cv2.imread(images)
    sublist = []
    output = test1.copy()
    image = cv2.resize(test1, (96, 96))
    image = image.astype("float") / 255.0
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)

    model = load_model("colabData/pokedex.model")
    lb = pickle.loads(open("colabData/lb.pickle", "rb").read())
    proba = model.predict(image)
    idx = np.argmax(proba)
    label = lb.classes_[idx]
    if not os.path.exists(label):
        os.makedirs(label)
    sublist.append(label)
    if label=="Commonfloor":
        shutil.move(images, "colabData/commonfloorr")
        print("WaterMark is Available", images, label)
    elif label=="Housing":
        shutil.move(images, "colabData/housingg")
        print("WaterMark is Available", images, label)
    elif label=="Sulekha":
        shutil.move(images, "colabData/sulekhaa")
        print("WaterMark is Available", images, label)
    elif label=="Magicbricks":
        shutil.move(images, "colabData/magicbrickss")
        print("WaterMark is Available",images, label)
    elif label=="Property_Wala":
        shutil.move(images, "colabData/propertywalaa")
        print("WaterMark is Available", images, label)
    elif label=="Non-Watermark":
        shutil.move(images, "colabData/nonwatermarkk")
        print("WaterMark is Not Available", images, label)
    elif label=="FloorPlans":
        shutil.move(images, "colabData/floorplann")
        print("WaterMark is Not Available", images, label)
    elif label=="MasterPlan":
        shutil.move(images, "colabData/masterplann")
        print("WaterMark is Not Available", images, label)
    else:
        print("Unable to classify")
    print(count)
    final_data.append(sublist)

filename = "data.csv"
with open("colabData/"+filename,'w') as csvfile:
    csvfile = csv.writer(csvfile, delimiter=',')
    csvfile.writerow("")
    for i in range(0, len( final_data )):
        csvfile.writerow( final_data[i]  )


texts:
The Collatz's Conjecture states that any number can either be halved (if it is even) or multiplied by three and added one to (if it is odd) and eventually reach 1.

I was wondering if there was a more efficient way to work out the series that a number takes to get to one and the amount of steps it takes.  The Python (3.x) code is:

i, k = 1, 1
fh=open("results.txt", "w")
print("Started")
def colapatz(x):
    seq = [x]
    j = 0
    while x > 1:
       if x % 2 == 0:
         x = x / 2
         j = j + 1
       else:
         x = 3 * x + 1
         j = j + 1
       seq.append(x)
    fh.write("Value number " + str(i) + " takes "+ str(j) + " steps.\n")
    fh.write("It takes the sequence: " + str(seq) + "\n")

#Call the function
while k<10000:
    k+=1
    i+=1
    colapatz(i)
print("Finished")
fh.close()

The is one of my first python programs that I've ever written, so any improvements would be great.


texts:
How could this be improved style-wise (if this isn't good enough) when the need is just to have a console replacement for PrintWriter.format() with backwards compatibility?

class CCConsole // not to be confused with any Java class with a similar name
{
    static PrintWriter pw = new PrintWriter(System.out, true);

    static void redirect(LongRunningWorker longRunningWorker) {
        pw = new PrintWriter(new LongRunningWorkerWriter(longRunningWorker));
    }
}

class LongRunningWorkerWriter extends Writer
{
    LongRunningWorker longRunningWorker;

    LongRunningWorkerWriter(LongRunningWorker longRunningWorker) {
        this.longRunningWorker = longRunningWorker;
    }

    @Override
    public void close() throws IOException { }

    @Override
    public void flush() throws IOException { }

    @Override
    public void write(char[] chars, int offset, int length) throws IOException {
        this.longRunningWorker.rePublish(new String(chars, offset, length));
    }
}

abstract class LongRunningWorker extends SwingWorker<Boolean, String>
{
    ColorSwingConsole colorSwingConsole;

    LongRunningWorker(ColorSwingConsole colorSwingConsole) {
        CCConsole.redirect(this);
        this.colorSwingConsole = colorSwingConsole;
    }

    public Boolean doInBackground() // concrete for abstract
        throws Exception {
        go();
        return true;
    }

    abstract void go() throws Exception;

    void rePublish(String s) {
        publish(s); // protected final = inherit or same package, cannot override
    }

    @Override
    public void process(List<String> chunks) {
        for (String s : chunks)
            this.colorSwingConsole.append(s);
    }
}

class RealWorker extends LongRunningWorker
{
    RealWorker(ColorSwingConsole css) {
        super(css);
        // constructor stuff
    }

    void go() throws Exception {
        CCConsole.pw.format("%s\n", "hello world");
        // application stuff
    }
}


texts: Generating user ids on a random forum website

texts:
Will this code be random enough to generate user ids for a website where people can create posts? Would there be a better method other than running this function and validating it doesn't exist in the database? I would prefer to have a method that I don't need to run a database check but the resulting UID should be 8 characters at most.

/**
 * Creates a UID
 * @return string 64 Character UID
 */
public static function createUid($length) {
    $bytes = random_bytes($length / 2);
    $uid = bin2hex($bytes);

    return $uid;
}


texts: Shunting-yard algorithm for expression parser

texts:
After reading about the Shunting-yard algorithm, I decided to try to make a expression parser, before trying to make a actual language parser, using it. The way i translated the algorithm into C++ code seems pretty compact, so  there is really not much code to post:

Shunting-yard algorithm(in C++):

#include <iostream>
#include <string>
#include<vector>
#include<map>
#include "list.h"

bool isInteger(char &c) {
    return (c >= '0') && (c <= '9');
}

int main() {
    std::vector<char> output;
    List<char> stack;
    List<char>::iterator it = stack.begin();

    std::string expr("2-2*3/6");
    std::map<char, int> op_precedence;
    op_precedence['+'] = 10;
    op_precedence['-'] = 10;
    op_precedence['*'] = 20;
    op_precedence['/'] = 20;

    for (char &c : expr) {
        if (isInteger(c)) {
            output.push_back(c);
        } else {
            if ((stack.size() > 0)) {
                if ((op_precedence[stack.top()] >= op_precedence[c])) {
                    output.push_back(stack.top());
                    stack.pop();
                    stack.push(c);
                } else if ((op_precedence[stack.top()] < op_precedence[c])) {
                    stack.push(c);
                }
            } else {
                stack.push(c);
            }
        }
    }
    for (it = stack.begin(); it != stack.end(); it++) {
        output.push_back(*it);
    }

    for (auto &i : output) {
        std::cout << i << ' ';
    }

    return 0;
}

The only thing I should note, is that the list.h I include, is not part of the standard library. That is a linked list class I finished up a few hours ago. If the code for the linked list is really necessary, I'll post it, but I don't think it will. I pretty much behaves like a normal linked list. In fact, you could exchange it with the standard linked list. Just replace pop() with pop_front(), push() with push_back(), and stack.top() with stack.front().

I also should mention that I have not included parenthesis yet, as I'm just trying to get the basics down first.


texts:
The Problem

As an ASP.NET MVC4 developper, I'm using Entity Framework a lot. Considering performance I often use lazy loading for my models.

public class Result {
    public int Id { get; set; }
    public decimal Grade { get; set; }
    public virtual Skill Skill { get; set; }
    public int SkillId { get; set; }
    public virtual Player Player { get; set; }
    public int PlayerId { get; set; }
    public virtual Category { get; set; }
    public int CategoryId { get; set; }
}

If I want to include all navigation models I'll have to include all those models.

public ActionResult Details(int id = 0)
{
    Result result = db.Results
                      .Include(r => r.Skill)
                      .Include(r => r.Player)
                      .Include(r => r.Category)
                      .SingleOrDefault(r => r.Id == id);
    //some viewmodel mapping
    return View(viewmodel);
}

My solution

I built an extension method to remove this from my controller code.

public static class IncludeExtensions
{
    public static IQueryable<Result> IncludeAll(this IQueryable<Result> results)
    {
        return results.Include(r => r.Skill)
                      .Include(r => r.Player)
                      .Include(r => r.Category);
    }

    public static Result IncludedFind(this IQueryable<Result> results, int id)
    {
        return results.IncludeAll().SingleOrDefault(r => r.Id == id);
    }
}

public ActionResult Details(int id = 0)
{
    Result result = db.Results.IncludedFind(id);
    //some viewmodel mapping
    return View(viewmodel);
}

There are a few problems with this:

I can't create an abstract extension class to force IncludeAll() and IncludedFind() method.
I still have to update the extension method if my models change.
I'll have a proliferation of extension methods/classes.
Isn't there an IncludeAll() like method available for Entity Framework?

Is there something like this on NuGet?

It just feels wrong...


texts:
I've made a little function to eliminate continuous duplicate from a std::vector. I have to use C++03.

For example, if a vector of ints is composed of: 1,1,2,3,,3,1,1,2 my function should return 1,2,3,1,2. I've tried to use templates (I've just began to use c++) and made it as fast as possible!

template<class T>
vector<T> remove_duplicate(vector<T>& vec) {
    int length = vec.size();
    vector<T> result(length);
    result[0] = vec[0];
    int last = 0;
    for(int i=0; i<length; i++)
        if(vec[i] != result[last]){
            last++;
            result[last] = vec[i];
        }
    result.resize(last+1);
    return result;
}

Here's a simple test case:

static
void test_remove_duplicate() {
    vector<int> v;
    v.push_back(1); //123131
    v.push_back(1);
    v.push_back(2);
    v.push_back(2);
    v.push_back(3);
    v.push_back(1);
    v.push_back(3);
    v.push_back(3);
    v.push_back(1);
    v.push_back(1);

    vector<int> v1;
    v1 = remove_duplicate(v);
    for(int i=0; i<v1.size(); i++) {
        cout << v1[i];
    } cout << endl;
}

What do you think about it?


texts:
Mostly for the experience (but also so I could waste hours playing it), I made a simple memory card game in JavaScript. I built it so it has a backbone framework that could be easily extended by stripping off my actual implementation. It's the backbone I'd like reviewed here, and mostly:

My OO - anything wrong; anything that could be improved on?
Obvious code efficiency: is there anything that could make it more efficient?
Structure: Is the structure of the game a good idea?

var Card = (function() {
    var self = Object.create({}, {
        val: {
            value: -1
        },
        index: {
            value: -1
        },
        addTo: {
            value: function(game) {
                var random = -1;
                counter = 0; //break counter to stop infinite loop. :)
                while ((game.cards[random] !== undefined && counter <= 100) | random === -1) {
                    random = Math.round(game.cards.length * Math.random());
                    counter++;
                }
                this.index = random;
                game.cards[random] = this;
            }
        },
        isMatch: {
            value: function(game) {
                if (this.val == game.selected.val) {
                    game.matches++;
                    return true;
                }
                return false;
            }
        }
    });
    return self;
})();
var Game = (function() {
    var self = Object.create({}, {
        cards: {
            value: new Array(30)
        },
        matches: {
            value: 0
        },
        init: {
            value: function(func) {
                for (i = 0; i < this.cards.length / 2; i++) {
                    var card = Object.create(Card, {
                        val: {
                            value: i
                        }
                    });
                    var card2 = Object.create(Card, {
                        val: {
                            value: i
                        }
                    });
                    card.addTo(this);
                    card2.addTo(this);
                }
                if (typeof func === 'function') {
                    func();
                }
            }
        },
        selected: {
            value: null
        }
    });
    return self;
})();

Sorry about the length; that's partly why I want it reviewed.

To see how to implement it and the full code, see here

EDIT: FYI, I realize the game isn't currently extensible.  For example, if I wanted there to be multiple types of matches, I can't do that quite yet. I'm pretty sure I know how to add that in, but I wanted to make sure my design structure was solid first.


texts:
I've written the following enum and have added a function, fromValue that allows the caller to map given int into the enum value. I was wondering if the value passed to the function can be validated, or is returning a null in case the value isn't present in the map (is an invalid enum) sufficient?

public enum TestEnum {

    A(0x00),
    B(0x01),
    C(0x02);

    int test;

    private static final Map<Integer, TestEnum> VALUE_TO_TEST_ENUM;
    static {
        final Map<Integer, TestEnum> tmpMap = new HashMap<>();
        for (TestEnum testEnum : TestEnum.values()) {
            tmpMap.put(testEnum.test, testEnum);
        }
        VALUE_TO_TEST_ENUM = ImmutableMap.copyOf(tmpMap);
    }

    TestEnum(final int test) {
        this.test = test;
    }

    public static TestEnum fromValue(final int value) {
        // Add validation?
        return VALUE_TO_TEST_ENUM.get(value);
    }
}


texts:
The following code ingests 10k-20k records per second and I want to improve the performance of it. I'm reading json and ingesting it into the database using Kafka. I'm running it on the cluster of five nodes with zookeeper and Kafka installed on it.

Can you give me some tips to improve?

import os
import json
from multiprocessing import Pool
from kafka.client import KafkaClient
from kafka.producer import SimpleProducer

def process_line(line):
    producer = SimpleProducer(client)
    try:
       jrec = json.loads(line.strip())
       producer.send_messages('twitter2613',json.dumps(jrec))
    except ValueError, e:
                {}

if __name__ == "__main__":
    client = KafkaClient('10.62.84.35:9092')
    myloop=True
    pool = Pool(30)

    direcToData = os.listdir("/FullData/RowData")
    for loop in direcToData:
        mydir2=os.listdir("/FullData/RowData/"+loop)

        for i in mydir2:
            if  myloop:
                 with open("/FullData/RowData/"+loop+"/"+i) as source_file:
                     # chunk the work into batches of 4 lines at a time
                     results = pool.map(process_line, source_file, 30)


texts:
I'm implementing a lazy constructor in C++. The goal is that for a type T, lazy<T>(args...) returns a callable object which, when called, returns T(args...).

This is what I have done so far:

#include <functional>
#include <utility>

/**
 * Returns an object of type `T` constructed from `args`.
 */
template<typename T, typename... Args>
T make(Args&&... args)
{
    return T(std::forward<Args>(args)...);
}

/**
 * Wrap a value of type `T` and perfect-forward it when accessed.
 */
template<typename T>
class Forward {
public:
    Forward(T &&value) noexcept : value_(std::forward<T>(value))
    {}

    operator T()
    {
        return std::forward<T>(value_);
    }

private:
    T value_;
};

/**
 * Returns a callable object which, when called, returns
 * an object of type `T` constructed from `args`.
 */
template<typename T, typename... Args>
auto lazy(Args&&... args) -> decltype(
        std::bind(
            make<T, Args...>,
            Forward<Args>(std::forward<Args>(args))...))
{
    return std::bind(
            make<T, Args...>,
            Forward<Args>(std::forward<Args>(args))...);
}

(Contrived) Examples:

// rvalue arguments
auto makePtr = lazy<std::unique_ptr<int>>(new int(123));
auto ptr = makePtr();

// lvalue arguments
int *rawPtr = new int(456);
auto makePtr2 = lazy<std::unique_ptr<int>>(rawPtr);
auto ptr2 = makePtr2();

Can this code be improved (particularly in terms of efficiency)?

UPDATE: The Forward class is used only as arguments to std::bind. Rationale:

Suppose we have a type Foo with constructor Foo(const std::unique_ptr<int> &). We can construct it by calling make<Foo, const std::unique_ptr<int> &>(someUniquePtr), for example.

However, std::bind(make<Foo, const std::unique_ptr<int> &>, someUniquePtr)() won't work (I think), because the reference-ness of the second argument to std::bind will be dropped. Wrapping it inside a std::cref works, but for packed arguments it seems the Forward class is the only solution I can come up with that works for all types.

It's possible that I misinterpreted the cause of this but here is an example of what I mean: https://godbolt.org/g/8w2Msa.


texts: MATLAB and Armadillo, hints on translating

texts:
i'm rewriting some Matlab code to c++ using armadillo, a libs for linear algebra. really good libs, IMHO. but i had to translate some matlab construct because armadillo isn't matlab.

i want to share my little snippet because i think there should be a better way (in terms of speed, mainly) to solve thoose little problems. i hope someone here could help me to improve my code!

static mat log(mat A) {
    /*
     * log function operates element-wise on matrix A
     * MATLAB code> log(A)
     */
    mat X(A);
    mat::iterator a = X.begin();
    mat::iterator b = X.end();

    for(mat::iterator i=a; i!=b; ++i) {
        (*i) = log(*i);
    }
    return X;
}

-

static mat vectorize(mat A) {
    /*
     * vectorise a matrix (ie. concatenate all the columns or rows)
     * MATLAB code> A(:)
     */
    mat B = mat(A);
    B.reshape(B.n_rows*B.n_cols, 1);
    return B;
}

-

static bool any(mat X, double n) {
    /*
     * check if there are some n in X
     * MATLAB code> any(X==n)
     * TODO: i'm not sure of description but it works for me
     */
    uvec _s = find(, n);
    if ( _s.is_empty() )
        return true;
    else
        return false;
}

-

static double sum(mat X) {
    /*
     * sum a matrix
     * MATLAB code> sum(X)
     */
    return sum(sum(X))
}

-

static field<rowvec num2cell(mat X) {
    /*
     *  converts matrix X into field by placing each row of X into a separate row
     *  this method assume that a cell is a field<rowvec>, mayebe a template should be used to generalize..
     *  MATLAB code> num2cell(X)
     */
    field<rowvec> data1(X.n_rows,1);
for (uint r = 0; r < X.n_rows; ++r) {
    data1(r,0) = X.row(r);
}
    return data1;
}


texts: Making sure initialization code is executed before other code using Lazy Initialization

texts:
The Problem

Recently I was told to refactor i.e. move some initialization logic from the constructor. I came up with something similar to the posted code.
In actual there are bunch of loader classes inheriting from ILoader and doing all kind of stuff (TPL, DB access,XML parsing, CSV Writing)
One of our UBER Developers reviewed my code and give some really appreciative comments particularly with the line of code marked with //<--:

  Wow – I have seen a lot but that would make the
  http://thedailywtf.com/ for sure. HOW can you think of having a Getter
  method have a initialization SIDE EFFECT??

What is your opinion guys. What should I've done to avoid such appreciative comments?

The Solution

using System;

public class Program
{
    public static void Main()
    {
        var obj = new TestLoader("testing");
        Console.WriteLine("Calling Run() first time....");
        obj.Run();
        Console.WriteLine("Calling Run() again...");
        obj.Run();
        Console.WriteLine("Calling SomeOtherMethod()...");
        obj.SomeOtherMethod();
    }
}

//Class to make sure initialize will only be called once
public abstract class DataInitializer<T>
{
    public bool IsInitialized { get { return _isInitialized.Value; } }//<--
    readonly Lazy<bool> _isInitialized;
    protected DataInitializer(T param)
    {
        Console.WriteLine("Inside DataInitializer constructor");
        _isInitialized = new Lazy<bool>(Initialize);
    }
    protected abstract bool Initialize();
}

//Some loader class
public class TestLoader :DataInitializer<string>, ILoader
{
    public TestLoader(string test):base(test)
    {
    }

    protected override bool Initialize()
    {
        Console.WriteLine("Inside Initialize()");
        return true;
    }

    public void Run()
    {
        if(IsInitialized)
        {
            Console.WriteLine("Inside Run()");
        }
    }

    public void SomeOtherMethod()
    {
        if(IsInitialized)
        {
            Console.WriteLine("Inside SomeOtherMethod()");
        }
    }

}

interface ILoader
{
    void Run();
    void SomeOtherMethod();
}


texts:
How can the time complexity of the following code be improved (assuming it's \$O(N^2)\$)? What about style and patterns?
This code is trying to find the minimum subarray size that adds up to given sum k. Elements should be adjacent.

/**
 * Created by mona on 5/24/16.
 */
public class MinSubArray {

    public static void minSubArray(int[] a, int k){

        int start=-1;
        int end=-1;
        int min=Integer.MAX_VALUE;

        for (int i=0; i<a.length; i++){
            int tmpSum=0;
            for (int j=i; j<a.length && (j-i+1)<min ; j++){
                tmpSum+=a[j];
                if (tmpSum==k){
                    start=i;
                    end=j;
                    min=end-start+1;
                    break;
                }
                if (tmpSum>k){
                    break;
                }
            }
        }

        if (start==-1 || end==-1){
            System.out.println("No such array exists with sum of "+k);
        }
        while (start<=end){
            System.out.print(a[start]+" ");
            start++;
        }

    }

    public static void main(String[] args){
        int a[] ={1,2,3,-1,2,4,8,9,5,6,-2,-3,10};
        minSubArray(a,5);

    }
}


texts:
It's a long time since I've written a Sieve of Eratosthenes (about 3 decades, I think, in ZX Basic).  So I decided to revisit in the light of experience.

Rather than allocating a vector of unknown size to sieve values, I keep an ordered set of upcoming composite values which are updated as they are reached.

#include <map>

unsigned long find_nth_prime(unsigned long n)
{
    if (!n) return 1;           // "0th prime"
    if (!--n) return 2;         // first prime

    // The map m contains one entry for each prime.  The key is the
    // next time to update it, and the value is the amount to increment
    // by each time it is reached.
    auto m = std::map<unsigned long, unsigned long>();
    // The overflow tests below are valid only for unsigned types.
    for (auto i = 3ul;  true;  i += 2) {
        if (i < 3ul)            // overflow test
            throw std::overflow_error("prime too large");

        const auto it = m.cbegin();
        if (it == m.end() || it->first != i) {
            // it's a prime
            if (!--n)
                return i;
            if (i*i > i)        // overflow test
                m.insert({i*i, 2*i});
        } else {
            // it's composite - advance the factor
            auto next = it->first;
            do {
                next += it->second;
            } while (next > i && !m.emplace(next, it->second).second);
            m.erase(it);
        }
    }
}

And the test program (not really part of the review):

#include <iostream>
#include <string>

int main(int, char **argv)
{
    std::cout.imbue(std::locale(""));
    while (*++argv) {
        try {
            std::cout << find_nth_prime(std::stoul(*argv)) << std::endl;
        } catch (std::exception&) {
            std::cerr << "Invalid argument: " << *argv << std::endl;
        }
    }
}

Compiled with GCC:

g++ -std=c++17 -O3 -Wall -Wextra -Wpedantic

Whilst the performance is acceptable (about 1.6 seconds on my hardware to find the one-millionth prime - 15,485,863), I'm unsure whether a std::map is really the best structure for keeping track.  As usual, any other critique of the code is welcome.