Throwing exception in the singleton pattern in C# I'm implementing an HTTP client shell that's going to be used for the lifetime of my application in C#.  It needs to be initialized before the instance can be accessed.  It looks something like this:

public static class AssetSyncServiceClient {
    private static object _lock = new object();
    private static bool _initialized = false;
    private static HttpClient _client = null;

    /// <summary>
    /// Indicates whether the client has been initialized.
    /// </summary>
    /// <returns>Whether the client is initialized.</returns>
    public static bool IsInitialized() {
        lock (_lock) {
            return _initialized;
        }
    }

    /// <summary>
    /// Creates and configures HTTP client.
    /// </summary>
    public static void Initialize(string baseUrl, bool onlyRequestJson = true) {
        lock (_lock) {
            if (_initialized) { throw new Exception("Client has already been initialized."); }

            _client = new HttpClient();
            _client.BaseAddress = new Uri(baseUrl);

            if (onlyRequestJson) {
                _client.DefaultRequestHeaders.Accept.Clear();
                _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }

            _initialized = true;
        }
    }

    /// <summary>
    /// Closes / disposes of the HTTP client.
    /// </summary>
    public static void Close() {
        lock (_lock) {
            if (_initialized && _client != null) {
                _client.Dispose();
            }
        }
    }

    /// <summary>
    /// Gets client instance.
    /// </summary>
    public static HttpClient Instance {
        get {
            lock (_lock) {
                if (!_initialized) { throw new Exception("HTTP client has not been initialized."); }
                return _client;
            }
        }
    }
}

The trouble is, this throws up a warning in Visual Studio because of style rule CA1065 - Microsoft say you shouldn't throw an exception in a property.  I just don't agree with this - it seems fine to me.  If you try to access .Instance before it's initialized you get an exception.  It's clearly a property whose code could throw an exception, and not a "dumb field".  I could turn Instance into a GetInstance method but I just prefer the look of accessing it from calling code as a property.

So does it make sense to just suppress the warning here, or am I designing this badly?  Is there a better way?  Should I bite the bullet and make Instance a method?

UPDATE:
It looks like I probably want something other than a singleton because singletons are hard to test (although actually MS Fakes can mock static methods so maybe it's OK), so what would be a better design pattern for this functionality that's unit testable?

The initialize dance is not nice. Requires the caller to keep track of if it has been called etc. Pit of failure.
The IsInitialized() is not very useful as it is now as there no way to lock over check and initialize. There will always be a risk that another thread calls Initialize between the check IsInitialized and the call to Initialize.
I have not used HttpClient much but my gut feeling is that the locking is not needed.
A singleton will make it hard to mock in tests. What about writing it like this:

public class AssetSyncServiceClientSettings
{
    public string BaseUrl { get; set; }
    public bool JsonOnly { get; set; }
}

public interface IAssetSyncServiceClient : IDisposable
{
    // Picked a sample method randomly, you can expose an api that makes sense in your app/lib
    Task<string> GetStringAsync(string requestUri);
}

public sealed class AssetSyncServiceClient : IAssetSyncServiceClient
{
    private readonly HttpClient _client;
    private bool _disposed;

    public AssetSyncServiceClient(AssetSyncServiceClientSettings settings)
    {
        _client = new HttpClient();
        _client.BaseAddress = new Uri(settings.BaseUrl);

        if (settings.JsonOnly)
        {
            _client.DefaultRequestHeaders.Accept.Clear();
            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
    }

    public Task<string> GetStringAsync(string requestUri)
    {
        VerifyNotDisposed();
        return _client.GetStringAsync(requestUri);
    }

    public void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        _disposed = true;
        _client.Dispose();
    }

    private void VerifyNotDisposed()
    {
        if (_disposed)
        {
            throw new ObjectDisposedException(this.GetType().FullName);
        }
    }
}

Doing it like this avoids initialization. If you need it lazy for some reason the service could handle it internally.
An interface probably makes sense for this so you can mock it in tests.
Use the Dependency Injection container to make the service a singleton instance.
Pass in the service interface in to constructors where it is needed. It makes the dependency explicit and makes it easy to mock in tests.
The settings object can perhaps contain urls so that the service can expose methods like public async Task<Stuff> GetStuffAsync()


Aggregate Pandas Columns on Geospacial Distance I have a dataframe that has 3 columns, Latitude, Longitude and Median_Income.  I need to get the average median income for all points within x km of the original point into a 4th column. I need to do this for each observation.

I have tried making 3 functions which I use apply to attempt to do this quickly.  However, the dataframes take forever to process (hours).  I haven't seen an error yet, so it appears to be working okay.

The Haversine formula, I found on here.  I am using it to calculate the distance between 2 points using lat/lon.

from math import radians, cos, sin, asin, sqrt

def haversine(lon1, lat1, lon2, lat2):

    #Calculate the great circle distance between two points
    #on the earth (specified in decimal degrees)

    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles
    return c * r

My hav_checker function will check the distance of the current row against all other rows returning a dataframe with the haversine distance in a column.

def hav_checker(row, lon, lat):

    hav = haversine(row['longitude'], row['latitude'], lon, lat)

    return hav

My value grabber fucntion uses the frame returned by hav_checker to return the mean value from my target column (median_income).

For reference, I am using the California housing dataset to build this out.

def value_grabber(row, frame, threshold, target_col):

    frame = frame.copy()

    frame['hav'] = frame.apply(hav_checker, lon = row['longitude'], lat = row['latitude'], axis=1)

    mean_tar = frame.loc[frame.loc[:,'hav'] <= threshold, target_col].mean()

    return mean_tar

I am trying to return these 3 columns to my original dataframe for a feature engineering project within a larger class project.

df['MedianIncomeWithin3KM'] = df.apply(value_grabber, frame=df, threshold=3, target_col='median_income', axis=1)

df['MedianIncomeWithin1KM'] = df.apply(value_grabber, frame=df, threshold=1, target_col='median_income', axis=1)

df['MedianIncomeWithinHalfKM'] = df.apply(value_grabber, frame=df, threshold=.5, target_col='median_income', axis=1)

I have been able to successfully do this with looping but it is extremely time intensive and need a faster solution.


Frequency analysis for counting keywords I have a CSV with around 10,000,000 lines. Each line looks like:

keyword1, keyword2, ....keywordn
keyword1, keyword2, ....keywordn
keyword1, keyword2, ....keywordn
keyword1, keyword2, ....keywordn

The script which does a frequency count and outputs to another text file:

from collections import Counter
import csv
import bz2
import sys

csv.field_size_limit(999999999)

all_terms = []

#with open('keywords.csv', 'rb') as f:
with bz2.BZ2File("keywords.csv.bz2", "r") as f:
    reader = csv.reader(f)
    for idx, row in enumerate(reader):
        for term in row:
            terms = term.split(",")
            for x in terms:
                all_terms.append( x.strip().lower() )
            if idx % 100000 == 0:
                print idx

c = Counter(all_terms)

with open("counts.txt", 'w+') as fl:
    for k,v in  c.most_common():
        fl.write( "{} | {}\n".format(k,v) )

I can't think of a way to minimize the memory utilization using generators and I'm not sure I could do a better job with the frequency counting job than the Counter class from the collections module.

The obvious issue with this is that you first build the list of all keywords and then count them. It would make more sense to count them while you process each line. collections.Counter supports this with an overridden update method:

>>> c = Counter([1, 2, 3])
>>> c
Counter({1: 1, 2: 1, 3: 1})
>>> c.update([1, 4])
>>> c
Counter({1: 2, 2: 1, 3: 1, 4: 1})

Which you can use in your case like this:

from collections import Counter
import csv
import bz2

csv.field_size_limit(999999999)

c = Counter()

with bz2.BZ2File("keywords.csv.bz2") as f:
    reader = csv.reader(f)
    for idx, row in enumerate(reader):
        c.update(term.strip().lower() for term in row)
        if idx % 100000 == 0:
            print idx

with open("counts.txt", 'w+') as fl:
    for k, v in c.most_common():
        fl.write("{} | {}\n".format(k, v))

I don't see the reason for for term in row, the CSV reader already splits the row into a list, so I left it out/moved it into the generator.

You should test the performance of

c.update(term.strip().lower() for term in row)

vs

c.update(map(lower, map(strip, row)))

vs

c.update(map(lambda term: term.strip().lower(), row))

with your file, because I'm not sure how well the double map is implemented in Python 2.x in comparison to using a lambda or a generator expression.

As an additional aside, it might makes sense to not do the update on every iteration, but buffer it for some number of counts. You could use the print as an already existing check to write it out. With this code:

from collections import Counter
import csv
import bz2

csv.field_size_limit(999999999)

c = Counter()
buf = []
with bz2.BZ2File("keywords.csv.bz2") as f:
    reader = csv.reader(f)
    for idx, row in enumerate(reader):
        buf.extend(term.strip().lower() for term in row)
        if idx % 100000 == 0:
            print idx
            c.update(buf)
            buf = []
    c.update(buf)

with open("counts.txt", 'w+') as fl:
    for k, v in c.most_common():
        fl.write("{} | {}\n".format(k, v))

I get some 25% speed increase on my local test file (which has a lot of repeated lines). At this point it becomes a trade-off between the cost of update and extend. in my normal code, this determines the runtime:

29877245 function calls (29877242 primitive calls) in 8.559 seconds
...
999181    2.756    0.000    7.515    0.000 collections.py:528(update)

For the second code it is somewhat shared between update and extend and lower in the sum

23882242 function calls (23882239 primitive calls) in 5.870 seconds
...
    12    1.421    0.118    1.791    0.149 collections.py:528(update)
...
999180    0.779    0.000    3.065    0.000 {method 'extend' of 'list' objects}

I also tried basically your approach, updating the counter only at the end. This is about another 0.2 seconds faster at the cost of potentially unlimited memory usage.


"Always stay connected" mechanism for socket connection I'm calling Connect() for the first time I connect, I am then checking if the connection is still connected every 10 seconds if it is not connected it attempts to re-connect.

public class ClientHandler : ISocketHandler, IDisposable
{
    private readonly Socket _socket;
    private readonly byte[] _buffer;

    private ISession _session;
    private bool _hasConnected;

    public ClientHandler()
    {
        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        _buffer = new byte[8192];

        var timer = new Timer
        {
            Interval = 30000
        };

        timer.Elapsed += ElapsedTimer;
        timer.Enabled = true;
    }

    private void ElapsedTimer(object sender, ElapsedEventArgs e)
    {
        if (!CoreUtilities.IsConnected(_socket))
        {
            Connect();
        }
    }

    public void Connect()
    {
        var host = _session.ConfigHandler["server.host"];
        var port = short.Parse(_session.ConfigHandler["server.port"]);

        try
        {
            _socket.Connect(new IPEndPoint(IPAddress.Parse(host), port));
            _socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, OnIncomingData, _socket);

            CoreUtilities.LogToConsole("Successfully established a connection to the server.");
        }
        catch (SocketException)
        {
            CoreUtilities.LogToConsole("Failed to establish a connection with the server.");
        }
        finally
        {
            if (_socket.Connected && CoreUtilities.IsConnected(_socket))
            {
                Send(new SocketPasswordComposer(_session.ConfigHandler["server.password"]));
            }
        }
    }
}

Here is the method I use to determine if the socket is fully connected to the server.

public static bool IsConnected(Socket socket)
{
    return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}

I feel that what I have coded above could be improved a lot.

I see there is problem in the usage to Timer. Consider the case if the server takes more time (> 5000) to connect, than the timer interval specified (3000) specified.  Then the timer elapsed event will fire again though the first elapsed event is not yet finished.  In order to avoid this stop the timer in the begin of Connect() and start the timer in end of Connect().


Custom thread-pooling Any suggestions/improvements for the following custom thread-pool code?

import threading
from Queue import Queue

class Worker(threading.Thread):
    def __init__(self, function, in_queue, out_queue):
        self.function = function
        self.in_queue, self.out_queue = in_queue, out_queue
        super(Worker, self).__init__()

    def run(self):
        while True:
            if self.in_queue.empty(): break
            data = in_queue.get()
            result = self.function(*data)
            self.out_queue.put(result)
            self.in_queue.task_done()

def process(data, function, num_workers=1):
    in_queue = Queue()
    for item in data:
        in_queue.put(item)

    out_queue = Queue(maxsize=in_queue.qsize())
    workers = [Worker(function, in_queue, out_queue) for i in xrange(num_workers)]

    for worker in workers:
        worker.start()

    in_queue.join()

    while not out_queue.empty():
        yield out_queue.get()

The function concurrent.futures.ThreadPoolExecutor.map is built into Python 3 and does almost the same thing as the code in the post. If you're still using Python 2, then there's a backport of the concurrent.futures package on PyPI.
But considered as an exercise, the code here seems basically fine (apart from the lack of documentation), and the remaining comments are minor issues.
Worker.run could be simplified slightly by writing the loop condition like this:

while not self.in_queue.empty():
    # ...

There's no need to pass a maxsize argument to the Queue constructor—the default is that the queue is unbounded, which is fine.
The only use of the workers list is to start the workers. But it would be easier to start each one as you create it:

for _ in range(num_workers):
    Worker(function, in_queue, out_queue).start()

The results come out in random(-ish) order because threads are nondeterministic. But for many use cases you would like to know which input corresponds to which output, and so you'd like the outputs to be in the same order as the inputs (as they are in the case of concurrent.futures.ThreadPoolExecutor.map).


HashTable - separate chaining collision in C++ I'm trying to implement a HashTable. In fact, I want a HashSet with Persons that have a name and a phoneNumber, both string. I understood the theory with collisions and everything but I don't know how to really implement something. This is what I've done so far:

#ifndef HASHSET_H_
#define HASHSET_H_

#include <iostream>
using namespace std;
#include <cstdio>

template <typename Element>
class HashSet{
private:
    class Node{
    private:
        Element info;
        Node* next;
    public:
        Node(){ //constructor
            this->next=NULL;
        }
        Node(Node* next, Element info){ //parameters constructor
            this->info=info;
            this->next=next;
        }
        Node(const Node& node){ //copy constructor
            this->info=node.info;
            this->next=node.next;
        }
        ~Node(){} //destructor
        Element getInfo(){
            return this->info;
        }
        Node* getNext(){
            return this->next;
        }
        void setInfo(Element newE){
            this->info=newE;
        }
        void setNext(Node* value){
            this->next=value;
        }
    };
    Node** head;
    int hashSize;
    int bucketSize; //holds the total elements of a cell
    int totElems; //total number of elements in the hashset
public:
    HashSet(){
    }
    bool IsEmptyAtGivenKey(int key);
    bool HashSetIsFull();
    int HashFunction(string e);
    int HashSetSize();
};

template<typename Element>
HashSet<Element>::HashSet(){
    this->hashSize=11;
    this->head=new Node*[hashSize];
    for(int i=0; i< hashSize; i++){
        this->head[i]=NULL;
    }
    this->totElems=0;
}

template<typename Element>
bool HashSet<Element>::IsEmptyAtGivenKey(int key){
    if(key>=0 and key < hashSize){
        return head[key]==NULL;
    }
    return true;
}

template<typename Element>
int HashSet<Element>::HashFunction(string e){
    int length = e.size();
    int sum;
    for(int i=0; i < length; i++){
        sum+=e[i];

    }
    int hashCode = sum % hashSize;
    return hashCode;
}

#endif /* HASHSET_H_ */

Is it any good? Any advice that will help me improve is welcome!

You're attempting to read values from uninitialized variables which has undefined behavior:

int sum; // uninitialized`
for(int i=0; i < length; i++){`
    sum+=e[i]; // reading from uninitialized variable "sum"

Read this
From "HASHSET_H_" I gather it's a header file.
You should never use using namespace std; in a header file (and chances are it's a bad idea to use it anywhere else, too -- unless you're porting legacy 1980s C code to C++):

Link 1
Link 2
If you can use C++11 then nullptr is a better choice than NULL: read this

// Note, however, that if you're NOT using C++11, then the following is a potential performance problem:
int HashSet<Element>::HashFunction(string e)
Pre-C++11 this can create unnecessary copy, so prefer to pass-by-const-reference in C++98/03 instead.

Compare:

copy
move
no copy (elided)
int is a wrong type for a variable holding size or count (such as hashSize, bucketSize, totElems).
In particular, this is very bad: int length = e.size();
Not only you're using a wrong type, but potentially also losing performance due to unsigned-to-signed conversion // which, perhaps more importantly, is completely unnecessary and only makes the code harder to read -- are you suggesting that length can be negative? If not, then don't use int.

Prefer std::size_t instead (defined in header <cstddef>):

Link 1
Link 2
Make sure to use meaningful variable names. This includes not using ambiguous abbreviations. totElems is not a good name. totalElementsCount is better.
Additional idea: make sure to pick a naming convention and stick to it.
For instance, some of your functions start with uppercase character, like IsEmptyAtGivenKey, but some with a lowercase character, like setInfo.
It's better if they all follow the same convention (e.g., all functions start with lowercase, all types start with uppercase, etc.).

As a hint, read the "Naming" section from Google C++ Style Guide.

// Extra hint: feel free to completely ignore the other sections, or even take them as examples of what NOT to do (like the one on exceptions), unless you're working at Google with Google's code base.
Manual memory management is troubling.

I've read from your comments that this is for school, so chances are the class / teaching methods simply aren't exactly up-to-date (thinking teaching C before C++ is a good idea is often a good indicator), but IRL invoking raw new (such as here: new Node*[hashSize];) without a very good reason is nowadays unnecessary and considered a bad practice.

If you want to learn best practices, start with this.

// Not to repeat myself from my previous answer, here's a link to it, if you'd like more information on memory management specifically: here.


Get time slots based on multiple workshops I have a list of Workshops, each having open days (Monday, Tuesday etc.) and open time and close time (which will be same for each day). Now, Based on the current time, I need to find out next 7 days available slots. A slot is of 2 hour and is available if any of the workshop is open in that 2 hour time. The first slot of each day will start at the open_time (nearest to hour time for eg. if open_time is 09:23:54 then first slot start time will be 10:00:00) of workshop opens first on that day.

My solution so far is to have a Workshop table which has off_days, open_at, close_at, name columns. There is another table which is WorkshopHolidays which has holiday_date, workshop_id.

class Workshop(models.Model):
    DAY_CHOICES = (
        (0,'Monday'),
        (1,'Tuesday'),
        (2,'Wednesday'),
        (3,'Thursday'),
        (4,'Friday'),
        (5,'Saturday'),
        (6,'Sunday')
    )
    name = models.CharField(max_length=255,null=True)
    address = models.CharField(max_length=1024)
    open_at = models.TimeField(null=True, blank=True)
    close_at = models.TimeField(null=True, blank=True)
    off_days = MultiSelectField(choices=DAY_CHOICES,null=True,blank=True)
    active = models.BooleanField(default=True)

class WorkshopHoliday(CreatedAtAbstractBase):
    workshop = models.ForeignKey(Workshop)
    holiday_date = models.DateField()
    active = models.BooleanField(default=True)

Now given a datetime, I need to find what are the two hour slots available for next seven days. If any one store is open in a slot, that slot should be part of the output.

The way I am approaching the problem now is following:

def get_slots():
    current_time = timezone.now()
    workshops = Workshop.objects.all()
    slots = {}
    for i in range(1,7):
        curdate = current_time.date()
        day = current_time.weekday()
        curdate_dict = {'start_time':None, 'end_time':None}
        for workshop in workshops:
            off_days = workshop.off_days if workshop.off_days else ''
            if day in off_days:
                continue
            wh = WorkshopHoliday.objects.filter(holiday_date=curdate,active=True)
            if wh:
                continue
            start_time = curdate_dict.get('start_time')
            if start_time:
                if start_time > current_time.time() and start_time > workshop.open_at and workshop.open_at > current_time.time():
                    start_time = workshop.open_at
            elif workshop.open_at > current_time.time():
                    start_time = workshop.open_at
            curdate_dict['start_time'] = start_time
            end_time = curdate_dict.get('end_time')
            if end_time:
                if end_time > current_time.time() and end_time < workshop.close_at and workshop.close_at > current_time.time():
                    end_time = workshop.open_at
            elif workshop.open_at > current_time.time():
                    end_time = workshop.open_at
            curdate_dict['end_time'] = end_time
        slots[curdate] = curdate_dict
        current_time.replace(hour=0,minute=0,second=0)
        current_time = current_time + timezone.timedelta(days=1)

Please suggest if there could be a better way to approach this problem (may be a better SQL query or algorithm). Also, please point out if there is some scenario in which this will give incorrect result.

You can simplify the creation of DAY_CHOICES using the calendar module:

DAY_CHOICES = tuple(enumerate(calendar.day_name))

this has the advantage of using the right locale, if need be.

You can reduce going back and forth between Python and your SQL backend using prefetching of objects, instead of querying each time you need something. Django offers the prefetch_related operation:

workshops = Workshop.objects.prefetch_related(
    Prefetch(
        'workshopholiday_set',
        queryset=WorkshopHoliday.objects.filter(
            holiday_date__ge=start_date,
            holiday_date__le=start_date + timezone.timedelta(days=7),
            active=True),
        to_attr='holidays_for_the_week'))

Where start_date is timezone.now().date(). This way, you get a list of every WorkshopHoliday for the upcoming week associated to the current workshop into workshop.holidays_for_the_week. You can test if the current date is in there with:

if curdate in {h.holiday_date for h in workshop.holidays_for_the_week}:
    continue

I would also advise to exchange the two for loops so you don't compute the set of holiday dates seven time for the same workshop.

curdate_dict is not necessary. You can replace

curdate_dict = {'start_time': None, 'end_time': None}

by

start_time, end_time = None, None

and remove all curdate_dict.get(…) and curdate_dict[…] = …. You just need to slots[curdate] = {'start_time': start_time, 'end_time': end_time} then, which will improve the memory management as well.

current_time.replace(hour=0, minute=0, second=0)

does nothing: the replace method returns a new datetime instance and since you’re not assigning it, you’re just wasting time.

for i in range(1, 7):

First of, i is never used: you should write _ instead to indicate that. Second, range(1, 7) produces 6 values. So you will perform your computations for today and the 5 next days. If you wished to compute your hours for a whole week, you should have written

for _ in range(7):

instead.

I also advise you to get the "counter" near that line. This is so the reader can grasp your intent more easily:

def get_slots():
    starting_time = timezone.now()
    start_date = starting_time.date()
    workshops = Workshop.objects.prefetch_related(
        Prefetch(
            'workshopholiday_set',
            queryset=WorkshopHoliday.objects.filter(
                holiday_date__ge=start_date,
                holiday_date__le=start_date + timezone.timedelta(days=7),
                active=True),
            to_attr='holidays_for_the_week'))
    slots = {}
    for day in range(7):
        current_time = starting_time + timezone.timedelta(days=day)
        …


Longest string in a vector — two implementations I was given this piece of code, which calculates the length of the longest string in a vector of strings:

static size_t max_line_length(std::vector<std::string> &lines) {
    size_t max = 0;
    for (auto it = lines.begin(); it != lines.end(); it++) {
        if (it->length() > max) {
            max = it->length();
        }
    }
    return max;
}

I am new to C++ with a significant background in Java. If I would write such a function myself, I would come up with something like:

static size_t max_line_length(std::vector<std::string> lines) {
    size_t max = 0;
    for (auto line : lines) {
        if (line.length() > max) {
            max = line.length();
        }
    }
    return max;
}

The difference is in the use of pointers, and the way in iterating the strings.

Is there a significant performance difference between these implementations, or are there best practices involved in this?

The first version of the algorithm uses a traditional C++03-era for loop with iterators. The only modern element is the auto used to deduce an std::vector<std::string>::iterator. The second loop uses a C++11 range-based for loop whose syntax is close to the one used in Java. The range-based for loop is now preferred for several reasons:

Its terse syntax (when iterators are fully spelled out, a traditional for loop is ugly).
Its genericity: a range-based for loop also works with C arrays and std::valarray.
end is automatically cached instead of being evaluated at each iteration.

That's it for the for loops: the range-based for loop is preferred. However, there are some things that could be improved in your second version:

You should pass lines as a const reference. When you don't need to modify an instance, a const reference is good since it avoids a useless copy.
In your range-based for loop, you should write const auto& since you don't modify line either. It currently performs many useless copies of full std::strings just to get their size. Actually, the best thing to write in range-based for loops is generally auto&&, but the explanation may be a little complicated since it involves lvalues, rvalues, const-correctness and type deduction.


Solve membership binary mask problem in Scala Imagine you have two string sequences:

val s1 = Seq("c", "a", "b", "z", "a", "b")
val s2 = Seq("a", "b")

You need to come up with an algorithm that generates a binary membership mask of s2 in s1, e.g.:

algorithm(s1, s2) => 011000

Here are some other examples:

val s1 = Seq("a", "b", "z", "c", "a")
val s2 = Seq("a", "b", "z")
11100

val s1 = Seq("z", "b", "a", "a", "b")
val s2 = Seq("a", "b")
00011

val s1 = Seq("z", "b", "a", "a", "b")
val s2 = Seq("a")
00100

val s1 = Seq("z", "b", "a", "a", "b")
val s2 = Seq("a", "a")
00110

Notice that we only count first sequence match and discard the rest sequence matches.

Basically, in case of s2 = Seq("z", "b", "a", "a", "b") and s1 = Seq("a", "b") we are trying to solve the following task:

"z"  "b"  "a"  "a"  "b"
 |    |    |    |    |
" "  " "  " "  "a"  "b"
 |    |    |    |    |
 0    0    0    1    1

Why? Imagine you have a sequence of auto-generated strings like "This is Google Inc ." but you only need to extract "Google" from it cutting everything else. It is easy when you know what you are searching for but once it is "This is ? Inc ." you have no way but to rely on binary masks that you collected from a big corpus. In order to generate such masks, you first need the algorithm described above.

I have come up with a simple while loop. This looks pretty ugly, so there should be another more Scala-like solution. How would you solve it?

def binmask(a: Seq[String], b: Seq[String]): String = {
  val x = a.sliding(b.length, 1)
  var continue = true
  var mask = ""
  while (continue && x.hasNext) {
    val g = x.next()
    if (g == b) {
      mask += "1"*b.length + "0"*x.length
      continue = false
    } else mask += "0"
  }
  if (continue) mask += "0"
  mask
}

The "never occurs" bug is still there. It stems from the fact that the length of b has an inverse relationship to the length of x. Try varying the length of a non-occurring b and see what you get.

There's also the fact that this is a rather imperative approach, whereas good Scala style tries to be more functional.

When I first saw this I thought, "Doesn't indexOfSlice() offer most of what's needed?"

def binmask(seq :Seq[String], slice :Seq[String]) :String = {
  val ios = seq indexOfSlice slice
  if (ios < 0)
    "0"*seq.length
  else {
    val slcLen = slice.length
    "0"*ios + "1"*slcLen + "0"*(seq.length-slcLen-ios)
  }
}

The slight drawback here is that indexOfSlice() will traverse the seq input until it finds a match (or completely if not found) and then seq is traversed again for its length.

The standard Scala means to achieve iteration with early termination but without mutable state, is via recursion. Preferably tail recursion, which the compiler turns into a while loop under the hood.

def binmask(seq :Seq[String], slice :Seq[String], acc :String = "") :String =
  if (seq startsWith slice) {
    val slcLen = slice.length
    acc + "1"*slcLen + "0"*(seq.length - slcLen)
  }
  else if (seq.isEmpty) acc
  else binmask(seq.tail, slice, acc + "0")

Some feel that making the accumulator a passed parameter (even though it is "hidden" behind a default value) exposes too much implementation in the public interface. For them, an inner recursion loop is preferable.

def binmask(seq :Seq[String], slice :Seq[String]) :String = {
  def loop(subseq: Seq[String], acc: String): String =
    if (subseq startsWith slice) {
      val slcLen = slice.length
      acc + "1" * slcLen + "0" * (subseq.length - slcLen)
    }
    else if (subseq.isEmpty) acc
    else loop(subseq.tail, acc + "0")

  loop(seq, "")
}


Dynamic filtering and sorting with Entity Framework I'm developing an application using ASP.NET MVC 3 and Entity Framework 4.1. In that application I have a lot of paged lists. Users can filter and sort these lists.

This results in code like the one below. I'm not really happy with this code. Is there a better way to do the filtering and sorting with Entity Framework?

Some of you might suggest putting that code into a service class and not in the controller, but that would just move the ugly code somewhere else. Instead of ugly code in a controller, I'd end up with ugly code in a service.

public UsersController : Controller
{
    private const int PageSize = 25;

    public ActionResult Index(int page = 1, string sort = "", UserSearchViewModel search)
    {
        // Get an IQueryable<UserListItem>
        var users = from user in context.Users
                    select new UserListItem
                    {
                        UserId = user.UserId,
                        Email = user.Email,
                        FirstName = user.FirstName,
                        LastName = user.LastName,
                        UsertypeId = user.UsertypeId,
                        UsertypeDescription = users.Usertype.Description,
                        UsertypeSortingOrder = users.Usertype.SortingOrder
                    };

        // Filter on fields when needed
        if (!String.IsNullOrWhiteSpace(search.Name)) users = users.Where(u => u.FirstName.Contains(search.Name) || u.LastName.Contains(search.Name));
        if (!String.IsNullOrWhiteSpace(search.Email)) users = users.Where(u => u.Email.Contains(search.Email));
        if (search.UsertypeId.HasValue) users = users.Where(u => u.UsertypeId == search.UsertypeId.Value);

        // Calculate the number of pages based on the filtering
        int filteredCount = users.Count();
        int totalPages = Convert.ToInt32(Math.Ceiling((decimal)filteredCount / (decimal)PageSize));

        // Sort the items
        switch(sort.ToLower())
        {
            default:
                users = users.OrderBy(u => u.FirstName).ThenBy(u => u.LastName);
                break;
            case "namedesc":
                users = users.OrderByDescending(u => u.FirstName).ThenByDescending(u => u.LastName);
                break;
            case "emailasc":
                users = users.OrderBy(u => u.Email);
                break;
            case "emaildesc":
                users = users.OrderByDescending(u => u.Email);
                break;
            case "typeasc":
                users = users.OrderBy(u => u.UsertypeSortingOrder);
                break;
            case "typedesc":
                users = users.OrderByDescending(u => u.UsertypeSortingOrder);
                break;
        }

        // Apply the paging
        users = users.Skip(PageSize * (page - 1)).Take(PageSize);

        var viewModel = new UsersIndexViewModel
                        {
                            Users = users.ToList(),
                            TotalPages = totalPages
                        };

        return View(viewModel);
    }
}

EDIT: I apologize from my earlier sample that didn't quite compile. I've fixed it and added a more complete example.

You could associate each condition with a strategy for changing the query. Each strategy (called SearchFieldMutator in this example) will hold two things:

A way to decide if to apply the strategy.
The strategy itself.

The first part is a delegate (of type Predicate<TSearch>) that returns true or false based on the data in the UserSearchViewModel (or any other type, since it only defines a generic type TSearch). If it return true, the strategy is applied. If it returns false, it's not applied. This is the type of the delegate:

Predicate<TSearch>

(it could also have been written as Func<TSearch, bool>)

The second part is the strategy itself. It is supposed to 'mutate' the query by applying a LINQ operator to it, but really just returns a new query with the added operator, and the caller of it should discard the old query and keep the new one. So it's not really mutation, but it has the same effect. I've created a new delegate type for it, so its usage is clear:

public delegate IQueryable<TItem> QueryMutator<TItem, TSearch>(IQueryable<TItem> items, TSearch search);

  NOTE: I've defined both the item type and the search data as generic types (as TItem and TSearch, respectively) so this code is usable in multiple locations in your code. But if this is confusing, you can remove the generics completely, and replace any TItem with UserListItem and any TSearch with UserSearchViewModel.

Now that we have defined the two types of the strategy, we can create a class that holds them both, and also does the (simulated) mutation:

public class SearchFieldMutator<TItem, TSearch>
{
    public Predicate<TSearch> Condition { get; set; }
    public QueryMutator<TItem, TSearch> Mutator { get; set; }

    public SearchFieldMutator(Predicate<TSearch> condition, QueryMutator<TItem, TSearch> mutator)
    {
        Condition = condition;
        Mutator = mutator;
    }

    public IQueryable<TItem> Apply(TSearch search, IQueryable<TItem> query)
    {
        return Condition(search) ? Mutator(query, search) : query;
    }
}

This class holds both the condition and the strategy itself, and by using the Apply() method, we can easily apply it to a query if the condition is met.

We can now go create out list of strategies. We'll define some place to hold them (on one of your classes), since they only have to be created once (they are stateless after all):

List<SearchFieldMutator<UserListItem, UserSearchViewModel>> SearchFieldMutators { get; set; }

We'll then populate the list:

SearchFieldMutators = new List<SearchFieldMutator<UserListItem, UserSearchViewModel>>
{
    new SearchFieldMutator<UserListItem, UserSearchViewModel>(search => !string.IsNullOrWhiteSpace(search.Name), (users, search) => users.Where(u => u.FirstName.Contains(search.Name) || u.LastName.Contains(search.Name))),
    new SearchFieldMutator<UserListItem, UserSearchViewModel>(search => !string.IsNullOrWhiteSpace(search.Email), (users, search) => users.Where(u => u.Email.Contains(search.Email))),
    new SearchFieldMutator<UserListItem, UserSearchViewModel>(search => search.UsertypeId.HasValue, (users, search) => users.Where(u => u.UsertypeId == search.UsertypeId.Value)),
    new SearchFieldMutator<UserListItem, UserSearchViewModel>(search => search.CurrentSort.ToLower() == "namedesc", (users, search) => users.OrderByDescending(u => u.FirstName).ThenByDescending(u => u.LastName)),
    new SearchFieldMutator<UserListItem, UserSearchViewModel>(search => search.CurrentSort.ToLower() == "emailasc", (users, search) => users.OrderBy(u => u.Email)),
    // etc...
};

We can then try to run it on a query. Instead of an actual Entity Framework query, I'm going to use a simply array of UserListItems and add a .ToQueryable() on to it. It will work the same if you replace it with an actual database query. I'm also going to create a simple search, for the sake of the example:

// This is a mock EF query.
var usersQuery = new[]
{
    new UserListItem { FirstName = "Allon", LastName = "Guralnek", Email = null, UsertypeId = 7 },
    new UserListItem { FirstName = "Kristof", LastName = "Claes", Email = "whoknows@example.com", UsertypeId = null },
    new UserListItem { FirstName = "Tugboat", LastName = "Captain", Email = "tugboat@ahoy.yarr", UsertypeId = 12 },
    new UserListItem { FirstName = "kiev", LastName = null, Email = null, UsertypeId = 7 },
}.AsQueryable();

var searchModel = new UserSearchViewModel { UsertypeId = 7, CurrentSort = "NameDESC" };

The following actually does all the work, it changes query inside the usersQuery variable to the one specified by all the search strategies:

foreach (var searchFieldMutator in SearchFieldMutators)
    usersQuery = searchFieldMutator.Apply(searchModel, usersQuery);

That's it! This is the result of the query:

You can try running it yourself. Here's a LINQPad query for you to play around with:

http://share.linqpad.net/7bud7o.linq


Short code in Python Rock Paper Scissors I am studying and practicing Python; this is my Rock-Paper-Scissors game I've built from scratch.
I saw this task is for beginners. When writing this in all the examples I saw dozens of lines of code with if elif else statements.
I decided to write the shortest program for this game.
I'm just looking for any comments, improvements or bad habits. Any comments at all are welcome!

import random

my_win = 0
my_loss = 0
my_tie = 0

def game():

    global my_tie, my_loss, my_win

    var = {'scissors':(0,1,0),
           'paper':(0,0,1),
           'rock':(1,0,0)}

    user = input("Please choice scissors, paper or rock: ")
    while user not in ['scissors', 'paper', 'rock']:
            user = input("Please choice scissors, paper or rock: ")
    computer = random.choice(['scissors','paper','rock'])

    print(f"USER - {user} \nCOMPUTER - {computer}")

    for k, v in var.items():
        if k == user:
            one = int(v.index(1))
        if k == computer:
            two = int(v.index(1))

    if one < two:
        print(f"USER with {user} - WIN!")
        my_win += 1
    elif one == two:
        print("==TIE==")
        my_tie += 1
    else:
        print(f"COMPUTER with {computer} - WIN!")
        my_loss += 1

    def results():

        print ("You win %d times!" % my_win)
        print ("You lose %d times!" % my_loss)
        print ("You tie %d times!" % my_tie)

if __name__ == "__main__":
    game()

I'll just go over some small improvements I noticed you can make.
my_win = 0
my_loss = 0
my_tie = 0

def game():

    global my_tie, my_loss, my_win

Global variables should be avoided whenever possible. The only reason I can see that these are globals is because of results() but you never actually call results(). It's probably better to just leave these as local variables.
var = {'scissors':(0,1,0),
       'paper':(0,0,1),
       'rock':(1,0,0)}

for k, v in var.items():
    if k == user:
        one = int(v.index(1))
    if k == computer:
        two = int(v.index(1))

A couple of comments here. First, you don't make use of the fact that your values in your dictionary are tuples instead of just ints. You can just use 0, 1, and 2 as values. Second, you're not taking advantage of the thing that dictionaries are best at: indexing. An improvement here would be:
var = {'scissors':1,
       'paper':2,
       'rock':0}

one = var[user]
two = var[computer]

Next:
if one < two:
    print(f"USER with {user} - WIN!")
    my_win += 1
elif one == two:
    print("==TIE==")
    my_tie += 1
else:
    print(f"COMPUTER with {computer} - WIN!")
    my_loss += 1

As I said in the comments, I don't think this is functionally correct. Either combination of the user and the computer choosing paper and rock will cause the rock to win. One of many fixes you could do is to add and abs(one - two) == 1 as a condition to your first if statement.
def results():

    print ("You win %d times!" % my_win)
    print ("You lose %d times!" % my_loss)
    print ("You tie %d times!" % my_tie)

This function is defined inside your game() function and is never called. Because your variables are local (as I suggested), you might want to put wins, losses, and ties as arguments for this function. You also don't have a way to play the game more than once, making this function pretty unhelpful. I'll leave adding a way to play multiple games to you since that's more of a code upgrade than a code review.
Here is the complete code with all my proposed changes:
import random

def game():
    my_win = 0
    my_loss = 0
    my_tie = 0

    var = {'scissors':1,
           'paper':2,
           'rock':0}

    user = input("Please choice scissors, paper or rock: ")
    while user not in ['scissors', 'paper', 'rock']:
            user = input("Please choice scissors, paper or rock: ")
    computer = random.choice(['scissors','paper','rock'])

    print(f"USER - {user} \nCOMPUTER - {computer}")

    one = var[user]
    two = var[computer]

    if one < two and abs(one - two) == 1:
        print(f"USER with {user} - WIN!")
        my_win += 1
    elif one == two:
        print("==TIE==")
        my_tie += 1
    else:
        print(f"COMPUTER with {computer} - WIN!")
        my_loss += 1

    results(my_win, my_loss, my_tie)

def results(win, loss, tie):

    print ("You win %d times!" % win)
    print ("You lose %d times!" % loss)
    print ("You tie %d times!" % tie)

if __name__ == "__main__":
    game()


Reporting new USB storage devices on Linux and macOS with Python Synopsis:
I wanted something for macOS (and Linux;  maybe eventually Windows) that would simply wait for the user to connect a storage device and automatically select, or otherwise output the information to be used, read, manipulated, etc.
In its current form, it just prints to the shell, but you could assign the output to a list or variable for read/write operations and so on. It will respond to any new entries in the /dev system directory, including most USB devices, SD Cards, Webcams, and so on. You can test it by running the script in one window, and running something like sudo touch /dev/{x,y,z} in another.
I plan to use it to help people (those of us who are less technically inclined) migrate to Linux by automating the creation of bootable flash drives, but you can do what you like with it.
Open-ended feedback and suggestions are welcome. Please try to post example code pertaining to your suggestions, and don't be afraid to say something positive.
Usage:
user@macOS:~$ ./devlisten.py
/dev/disk2
/dev/rdisk2
/dev/disk2s1
/dev/rdisk2s1

Code:
#!/usr/bin/env python3

import os
import re
import time
import difflib

try:
    os.mkdir('/tmp/dev')
except FileExistsError:
    pass
except FileNotFoundError:
    print('No /tmp directory found.')
    exit()
except OSError:
    print('Read-only file system.')
    exit()

file1 = open('/tmp/dev/1', 'w')
for x in os.listdir('/dev'):
    file1.write(x + '\n')
file1.close()

try:

    diff = False
    while diff == False:
        time.sleep(0.25)

        file2 = open('/tmp/dev/2', 'w')
        for x in os.listdir('/dev'):
            file2.write(x + '\n')
        file2.close()

        text1 = open('/tmp/dev/1').readlines()
        text2 = open('/tmp/dev/2').readlines()

        for line in difflib.unified_diff(text1, text2):
            for line in re.finditer(r'(?<=^\+)\w.*$', line, re.MULTILINE):
                print('/dev/' + line.group(0))
                diff = True

except KeyboardInterrupt:

    print()
    exit()

This script might get the job done, but it is a rather crude and inefficient hack.  Ideally, you should avoid polling every quarter second (or polling at all).  Also, I see no reason to write any files to /tmp.

The ideal way to do it in Linux is to use udev.  If you don't want to write a persistent udev rule, or you don't have root access, you can run /sbin/udevadm monitor --udev --property as a child process, and trigger your test whenever udevadm offers output.  For a smarter script, you can can look for the ACTION=add line and take advantage of the information in the SUBSYSTEM=… and DEVPATH=… lines.  DEVPATH tells you path to the device within /sys.  But, even if you simply trigger your script only when any output appears, that would be a huge improvement over polling four times a second.

import itertools
from subprocess import Popen, PIPE
import re
import sys

KEYVALUE_RE = re.compile(r'([^=]+)=(.*)')

def events(stream):
    """
    Read udev events from the stream, yielding them as dictionaries.
    """
    while True:
        event = dict(
            KEYVALUE_RE.match(line).groups()
            for line in itertools.takewhile(KEYVALUE_RE.match, stream)
        )
        if event:
            yield event

try:
    UDEVADM = ['/sbin/udevadm', 'monitor', '--udev', '--property']
    with Popen(UDEVADM, stdout=PIPE, encoding='UTF-8') as udevadm:
        for event in events(udevadm.stdout):
            if event['ACTION'] == 'add' and event.get('DRIVER') == 'usb-storage':
                print(event)
                break
except KeyboardInterrupt:
    sys.exit(1)

On macOS, you can get similar information by running and monitoring the output of /usr/sbin/diskutil activity, if you are interested in storage devices.  Look for lines starting with ***DiskAppeared.

from subprocess import Popen, PIPE
import sys

try:
    DISKUTIL = ['/usr/sbin/diskutil', 'activity']
    with Popen(DISKUTIL, stdout=PIPE, encoding='UTF-8') as diskutil:
        # Ignore events that describe the present state
        for line in diskutil.stdout:
            if line.startswith('***DAIdle'):
                break
        # Detect the first subsequent "Disk Appeared" event
        for line in diskutil.stdout:
            if line.startswith('***DiskAppeared'):
                print(line)
                break
except KeyboardInterrupt:
    sys.exit(1)

If you are interested in non-storage devices as well, then you could take advantage of the File System Events API, possibly through the MacFSEvents Python package or the cross-platform fswatch program.


What is the best to select a javascript object property at any depth? I'm looking for suggestions on how to select properties on the child level or deeper dynamically.

For example, here is the method that I am currently using. The method parameters is the object and either a string or array for the property name. If a string is passed used, it will just will get the property.  The array is iterated through in order to select the property value.

getMappedDataProperty: function(obj, map) {
  var m, result, _i, _len;
  if (typeof map === 'string') {
    return obj[map];
  }
  result = obj;
  for (_i = 0, _len = map.length; _i < _len; _i++) {
    m = map[_i];
    result = result[m];
  }
  return result;
}

Even though this works, I keep thinking to myself that there has to be a better way of accomplishing this.  Suggestions?

From a once over:

getMappedDataProperty is a clumsy name, how about getProperty.
receiving a string is functionally the same as an array with 1 entry, so you could
map = (typeof map === 'string') ? [map] : map;
There is no need for the underscores for i and len, also, I would rather see length than len
the use of the temporary variable m is overkill, you could go straight for result = result[map[i]];

I would counter propose:

getProperty: function( o, map )
{
  map = (typeof map === 'string') ? [map] : map.slice();
  var result = o;
  while ( map.length ) {
    result = result[ map.shift() ];
  }
  return result;
}

I would love to know the context in which you use this, since I cannot see a good use case for it.


Python - Predicting the probability of 6 Heads or Tails in a row from a set sample size I'm wondering whether there is a way to make this even more efficient or reduce the number of variables.
import random
numberOfStreaks = 0
results = []
head_streak = ['H'] * 6
tail_streak = ['T'] * 6
sample_size = 1000000
for i, experimentNumber in enumerate(range(sample_size)):
    # Code that creates a list of 100 'heads' or 'tails' values.
    results.append(random.choice(('H', 'T')))

    # Code that checks if there is a streak of 6 heads or tails in a row.
    try:
        temp = results[i-5:]
        if temp == head_streak or temp == tail_streak:
            numberOfStreaks += 1
    except:
        pass

print('Chance of streak: %s%%' % (numberOfStreaks / sample_size))

Eliminating useless code
Enumerating a range is really pointless
In [6]: sample_size = 5

In [7]: for i, experimentNumber in enumerate(range(sample_size)):
   ...:     print(i, experimentNumber)
   ...:
0 0
1 1
2 2
3 3
4 4

So we can easily replace one by the other. We do not even need to replace as experimentNumber is not used anywhere. Next we notice that i is also used only once where we can replace results[i-5:] by superior construct results[-6:].
We also eliminate the superfluous exception handling. So far this is already covered by @ppperys answer.
Efficiency
you create a complet list of length sample_size of random values in memory. This is not required and may be a problem on big sample sizes. As you always need the last 6 values only you could go for collections.deque which can maintain a maxlen.
from collections import deque
results = deque(maxlen=6)

For the evaluation made easy we do not use ('H', 'T') but numbers. We do not need to comare with a streak any more but do it arithmetically. Here is the only pitfall - we must check if the queue is filled completely to not accidentally accept a short sequence of zeros.
for _ in range(sample_size):
    results.append(random.choice((0, 1)))
    if len(results) == 6 and sum(results) in (0, 6):
        numberOfStreaks += 1

This not only saves memory but we also get rid of a temporary temp and the predifined head_streak and tail_streak. We notice the magic number 6 appearing multiple times - use a variable. We also make a testable function. We end up with
import random
from collections import deque

def streak_probability(streak_len, sample_size):
    results = deque(maxlen=streak_len)
    numberOfStreaks = 0
    for _ in range(sample_size):
        results.append(random.choice((0, 1)))
        if len(results) == streak_len and sum(results) in (0, streak_len):
            numberOfStreaks += 1
    return numberOfStreaks / sample_size

print('Chance of streak: %s%%' % (streak_probability(6, 1000000))

Algorithm
This simulation will give good results for big numbers of sample_size. However if the sample size was smaller than 6 it will always return 0. As you divide the final streak count by the sample size you indicate, that you would like to get the probability of a streak per "additional" coin toss. So we should fill the queue before starting to count. That way an average of a large number of runs with a small sample size would match a single run of a large sample size. If we prefill we do not have to check the fill state of the queue (yes I filled to the max while one less would be sufficient).
def prefilled_streak_probability(streak_len, sample_size):
    results = deque((random.choice((0, 1)) for _ in range(streak_len)), maxlen=streak_len)
    numberOfStreaks = 0
    for _ in range(sample_size):
        results.append(random.choice((0, 1)))
        if sum(results) in (0, streak_len):
            numberOfStreaks += 1
    return numberOfStreaks / sample_size

Now test the difference - we compare the original sample size of 1.000.000 to 100.000 repetitions of sample size 10
s=10
n=100000
print('no prefill')
print('Single big sample - Chance of streak: %s%%' % (streak_probability(6, s*n)))
probs = [streak_probability(6, s) for _ in range(n)]
print('Multiple small samples - Chance of streak: %s%%' % (sum(probs)/len(probs)))

print('with prefill')
print('Single big sample - Chance of streak: %s%%' % (prefilled_streak_probability(6, s*n)))
probs = [prefilled_streak_probability(6, s) for _ in range(n)]
print('Multiple small samples - Chance of streak: %s%%' % (sum(probs)/len(probs)))

we get
no prefill
Single big sample - Chance of streak: 0.031372%
Multiple small samples - Chance of streak: 0.01573599999999932%
with prefill
Single big sample - Chance of streak: 0.031093%
Multiple small samples - Chance of streak: 0.031131999999994574%


Integer validation in C++ I am studying C++ and after I learned about some functions of the library cctype like isdigit I decided to make a program that validates user input only to be an integer number. So input like 123as, :$ or +.234 are invalid, however I decided to keep the plus or minus sign, i.e., input like -24 or +142 are valid. Below is my code:

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

bool integer_valid(string s);
int get_integer();

int main()
{
    int number;

    number = get_integer();
    cout << "The integer number is:\t" << number << "\n" << endl;

    system("pause");
    return 0;
}

bool integer_valid(string s)
{
    int i, length_s;
    bool is_valid = true;

    length_s = s.length();

    if (length_s == 0)
        is_valid = false;
    else
    {
        if (length_s == 1)
        {
            if (!isdigit(s[0]))
                is_valid = false;
        }
        else
        {
            if (s[0] == '+' || s[0] == '-' || isdigit(s[0]) != 0)
            {
                for (i = 1; i < length_s; i++)
                {
                    if (!isdigit(s[i]))
                        is_valid = false;
                }
            }
            else
                is_valid = false;
        }
    }
    return is_valid;
}

int get_integer()
{
    int new_number;
    string number;
    bool is_valid;

    do {
        cout << "Enter an integer number:\t";
        getline(cin, number);
        cout << "\n";

        is_valid = integer_valid(number);

        if (is_valid == false)
            cout << "ERROR. The entered number must be an integer.\n" << endl;
    } while (is_valid == false);

    new_number = stoi(number);

    return new_number;
}

I'm aware that in general is a bad practice to use using namespace std, but since my program has less tan 100 lines of code I think it's really not a big issue here. Moreover, I wonder if there is another (simpler/faster) way to validate integer numbers?

EDIT: Answering to the comment made by Roland Illig, I would say yes. More exactly, any kind of integer should be valid, but as far as I know, int has a defined size, so if I want to valid long integers I should use the type long long int and also the function stoll, right?

Any feedback would be greatly appreciated.

Using a bool is_valid results in a deeply nested code. You have 5 levels of nesting, with the core of algorithm being hidden at the deepest one. I recommend an early return: as soon as you determine that the string doesn't pass a criteria, return false; immediately.
Testing for length_s == 0 is redundant. In this case s[0] is '\0', which is neither a digit nor a sign.
Passing std::string as an argument makes a copy. Prefer passing a (constant) reference.
Leaving the point of the exercise aside, the best way to validate a number is to just go ahead and directly call std:stoi with the second parameter, e.g.:

    size_t end;
    int number = std::stoi(s, &end);
    if (s[end] != '\0') {
        // The string was not parsed completely. It is not a number.
    }


Un*x terminal history wiper Using various answers from Stack Overflow and  Ask Ubuntu, I've hacked together this simple C program that wipes terminal history. It works but I'm relatively new to C so I'm not sure if everything is correct.

#include <stdio.h>

int main(void) {
  // check if the program is being executed in a terminal
  if (isatty(0)) {
    // if the program is being executed in a
    // terminal just start the wiper
    system("cat /dev/null > ~/.bash_history;history -c;history -w;rm -r ~/.bash_history;exit;");
  } else {
    // if the program is being executed as a stand-alone
    // open a new terminal window and then start the wiper
    system("gnome-terminal -x sh -c 'cat /dev/null > ~/.bash_history;history -c;history -w;rm -r ~/.bash_history;exit;'");
  }
  // stop the program
  return 0;
}

That's a lot of shell commands to do very little.

You could replace all those shell commands to get the equivalent effect with just this:

rm ~/.bash_history; HISTFILE=

Let me explain step by step why this is equivalent:

cat /dev/null > ~/.bash_history - truncate the file. Exactly the same as the shorter > ~/.bash_history. This is pointless, because later you delete the file anyway.
history -c - clear the history. Pointless because later you delete the file anyway
history -w - write the content of the history to the file. Pointless because later you delete the file anyway
rm -r ~/.bash_history - delete the file, recursively. The recursive flag is pointless, as the history file is never a directory
exit - This is pointless, as the system function will exit automatically anyway

All this can be reduced to what I gave above, by benefiting from the fact that if HISTFILE is unset, history is not saved anywhere.

Btw, I don't understand why you need a gnome terminal at all. I think you can simply remove that special treatment.

Lastly, using system is generally not recommended, it should be avoided as much as possible. If you must use it for some reason, you should call commands by their absolute paths, otherwise the program will be vulnerable to path injection attacks.


Speed up looping through slicers and .selected true if slicer item name matches input words Sub SearchSlicer()
Dim oSc As SlicerCache
Dim oSi As SlicerItem
Dim searchword As Variant
searchword = InputBox("Enter a searchword")

Set oSc = ThisWorkbook.SlicerCaches("Slicer_SEARCH_WORDS")

For Each oSi In oSc.SlicerItems
      If oSi.Name Like "*" & UCase(searchword) & "*" Then
          oSi.Selected = True
      Else: oSi.Selected = False
      End If
Next

End Sub

So I have a pivot table with two columns - a column for a verb and a column for search words containing synonyms/similar phrases. For example, if a word in the first column is 'broke', the second column will contain the list 'fell apart, broken, split'.

Running the above code asks the user for a search word which will be used to loop through the search word column and filter the search word pivot table and slicers.

This search word slicer is linked to first column slicer as the search word slicer is not visible on the input sheet.

The reason for using slicers is because I have another code for when the user clicks on a slicer choice, it automatically pastes it into the active cell.

I have a table with 350 rows and this code is already taking very long to run. How can I make this more optimal?

Invariants, variables which don't change in a loop, should be set before entering the loop. Additionally, if you want to store the value of a Boolean expression, just store the expression's return value:

Sub SearchSlicer()
    Dim oSc As SlicerCache
    Dim oSi As SlicerItem
    Dim searchword As Variant

    searchword = InputBox("Enter a searchword")
    searchword = "*" & UCase(searchword) & "*"
    Set oSc = ThisWorkbook.SlicerCaches("Slicer_SEARCH_WORDS")

    For Each oSi In oSc.SlicerItems
        oSi.Selected = oSi.Name Like searchword
    Next oSi
End Sub

But I doubt this will speed up the loop much. Most likely the 'like' operator is where most of the time is spent (and I don't see any alternative to it).


Multiple input checks, repeat if conditions are not met I've used this code to make some inputs checks. On any failed check, I need to ask again for proper input. I used labels and goto to achieve this, which they seem to be disliked by programmers as a concept.
How could I achieve the same effect without labels/goto? I considered putting all this code in a function and calling itself from inside, but it repeated only once for some reason - didn't keep asking if kept getting wrong answers.
// 0 exits
var f float64
var n int
startGame := func() {
reception:
    fmt.Println()
    fmt.Print(`Give number (1-9): `)
    _, err := fmt.Scan(&f)

    // check letters or symbols
    if err != nil {
        fmt.Println("Letters or symbols not accepted")
        goto reception
    }

    // exit
    if f == 0 {
        os.Exit(0)
    }

    // check for integers only
    if f < 1 || f > 9 || f-math.Ceil(f) != 0 {
        fmt.Println("Only integer numbers between 1-9 are accepted")
        goto reception
    }

    n = int(f)
    // check for empty cells
    if myArray[n-1] == false {
        fmt.Println("Empty cell", n)
        goto reception
    }
}

for {} (for loop without condition) loops forever until break.

Put the contents of the function in a for {}.
Remove the label and replace goto reception with continue. This will cause the current iteration of the loop to end and execution will continue with another iteration, starting from the top of the block.
Use break at the end to exit the for loop


Repository with ViewModel (ASP.NET MVC) I have db table Model.

Here is code:

public partial class Logging
{
    public string Imei { get; set; }
    public DateTime CurDateTime { get; set; }
    public Nullable<System.DateTime> GPSDateTime2 { get; set; }
    public Nullable<decimal> Latitude2 { get; set; }
    public Nullable<decimal> Longitude2 { get; set; }
    public int Speed { get; set; }
    public Nullable<int> Datatype { get; set; }
    public int Id { get; set; }

}

I want to calculate a difference

And decided to create View - Model

Here is code:

 public class HeatmapViewModel
{
    public int FirstStartDifference { get; set; }
    public int LastStartDifference { get; set; }
    public int coeff = 2;
    public int Difference;
}

And I decided to make calculations on Repository layer
Here is code:

  public List<HeatmapViewModel> GetStops()
    {
        using (var ctx = new GoogleMapTutorialEntities())
        {
            List<HeatmapViewModel> items = new List<HeatmapViewModel>();

            #region firstitem_calculation
            var firstitem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select(
                x => new Logging
                 {
                     Longitude2 = x.Longitude2,
                     Latitude2 = x.Latitude2,
                     CurDateTime = x.CurDateTime

                 }).FirstOrDefault();

             var midnight = new DateTime(firstitem.CurDateTime.Year, firstitem.CurDateTime.Month, firstitem.CurDateTime.Day, 00, 00, 00);
             TimeSpan difference = (firstitem.CurDateTime - midnight);
             var difference_after_midnight = (int) difference.TotalMinutes;

             items.Add( new HeatmapViewModel
                 {
                     FirstStartDifference = difference_after_midnight
                 });
            #endregion

            #region lastitem_calculation
            var lastItem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select(
                 x => new Logging
                 {
                     Longitude2 = x.Longitude2,
                     Latitude2 = x.Latitude2,
                     CurDateTime = x.CurDateTime

                 }).LastOrDefault();
            var before_midnight = new DateTime(lastItem.CurDateTime.Year, lastItem.CurDateTime.Month, lastItem.CurDateTime.Day, 23, 59, 00);
            TimeSpan difference_before = (before_midnight - lastItem.CurDateTime);
            var difference_before_midnight = (int)difference_before.TotalMinutes;

            items.Add(new HeatmapViewModel
            {
                LastStartDifference = difference_after_midnight
            });

            #endregion
   return items;
         }

    }

And call on Controller just method from repo.

Like this:

 public JsonResult GetStops()
        {
            var stops = repo.GetStops();

            return Json(stops.ToArray(), JsonRequestBehavior.AllowGet);

        }

I want to know if the code on the repository is okay, or can I improve it?

So here is my take on how I'd change it.
It might be over the top if the application is very simple and light, however, its how I'd rewrite it.

ExampleController

The actual implementation here would need to be updated, however this is to demonstrate how to use a new Service layer and passing in the repository.

public class ExampleController
{
    public JsonResult GetStops()
    {

        var loggingRepository = new LoggingRepository();
        var stops = new HeatMapService(loggingRepository);

        var heatMapViewModel = stops.GetMyHeatmap();

        return Json(stops.ToArray(), JsonRequestBehavior.AllowGet);

    }
}

HeatMapService

Firstly it's useful to have something to orchastrate the work, and so I'd add a HeatMapService.

public class HeatMapService
{

    private LoggingRepository LoggingRepository { get; set; }

    // Pass in the loggingRepository
    public HeatMapService(LoggingRepository loggingRepository)
    {
        LoggingRepository = loggingRepository;
    }

    // Have a service method, whos job it is to return the HeatmapViewModel for your use case
    public HeatmapViewModel GetMyHeatmap()
    {

        // We individually call the Repository for the first and last logs
        var firstLog = LoggingRepository.GetFirstLog();
        var lastLog = LoggingRepository.GetLasttLog();

        // We ask the entity to get the answer to the difference before and after midnight
        var firstDifference = firstLog.GetDifferenceAfterMidnight();
        var lastDifference = lastLog.GetDifferenceBeforeMidnight();

        // Finally we create a new HeatmapViewModel - using a factory method
        return HeatmapViewModel.CreateHeatMapFromTwoDifference(firstDifference, lastDifference);
    }

}

The Logging Model

Ask the model questions about the model

public class Logging
{
    // Id moved to the top, as this is assumed to be the unique id for this entity
    public int Id { get; set; }
    public string Imei { get; set; }
    public DateTime CurDateTime { get; set; }
    // Nullable<DateTime> replaced with more modern version DateTime?
    public DateTime? GPSDateTime2 { get; set; }
    public decimal? Latitude2 { get; set; }
    public decimal? Longitude2 { get; set; }
    public int Speed { get; set; }
    public int? Datatype { get; set; }

    // Get the difference after midnight, on the actual Model itself
    public int GetDifferenceAfterMidnight()
    {
        return (int)(this.CurDateTime - this.CurDateTime.Date).TotalMinutes;
    }

    // Get the difference before midnight, on the actual Model itself
    public int GetDifferenceBeforeMidnight()
    {
        return (int) (this.CurDateTime.Date.AddHours(23).AddMinutes(59) - this.CurDateTime).TotalMinutes;
    }

}

HeatmapViewModel

Create a new instance of HeatmapViewModel using a factory method, restricting how the model can be created.

Also note that the Properties are private set - so can only be set via the factory method (or via additional non-static methods).

public class HeatmapViewModel
{
    public int FirstStartDifference { get; private set; }
    public int LastStartDifference { get; private set; }
    public int Coeff => 2;
    public int Difference { get; private set; }

    // Just pass in your two ints to create a new HeatMapModel
    public static HeatmapViewModel CreateHeatMapFromTwoDifference(int firstStartDifference, int lastStartDifference)
    {
        return new HeatmapViewModel
        {
            FirstStartDifference = firstStartDifference,
            LastStartDifference = lastStartDifference
        };
    }
}

LoggingRepository

Simpify the repository methods, to just get the entries you need. Single Responsibilty - return individual log entries from the ctx

public class LoggingRepository {

    // Get the First Log
    public Logging GetFirstLog()
    {
        using (var ctx = new GoogleMapTutorialEntities())
        {

            var firstitem = ctx.Loggings.FirstOrDefault(x => x.Datatype == 2);
            return firstitem;
        }
    }

    // Get the Last Log
    public Logging GetLasttLog()
    {
        using (var ctx = new GoogleMapTutorialEntities())
        {

            var firstitem = ctx.Loggings.LastOrDefault(x => x.Datatype == 2);
            return firstitem;
        }
    }

}


First Python program: Tic-Tac-Toe (Followup) I am unsure if I followed the the suggestions on my previous post.
I have only been working on programming for about 3 weeks so any more suggestions or insight would be more than welcomed.

import sys
from textwrap import dedent
import os
import random

os.system('CLS')

# board number setup
board = [0, 1, 2,
         3, 4, 5,
         6, 7, 8]

# Defines the board layout printed to the console
def board_layout():
    print(dedent(f'''
    *************
    * {board[0]} | {board[1]} | {board[2]} *
    *-----------*
    * {board[3]} | {board[4]} | {board[5]} *
    *-----------*
    * {board[6]} | {board[7]} | {board[8]} *
    *************
    '''))

def main():
    players = ('Player','NPC')
    turn = 'Player'
    change_turn = 0
    for moves in range(9):
        if turn == 'Player':
            while True:
                try:
                    board_layout()
                    player_move = int(input('Please select a spot: '))
                    if board[player_move] != 'x' and board[player_move] != 'o':
                        board[player_move] = 'x'
                        check_winner()
                        break
                except IndexError:
                    print('please select valid spot')
        if turn == 'NPC':
             # npc move, chooses a random spot that is not taken
            while True:
                npc = random.randint(0, 8)
                if board[npc] != 'o' and board[npc] != 'x':
                    board[npc] = 'o'
                    print('Computer chooses spot ', npc)
                    check_winner()
                    break
        try:
            change_turn += 1
            turn = players[change_turn]
        except:
            change_turn = 0
            turn = players[change_turn]
    else:
       print('You Tied')
       end()

def end():
        print('Thank you for playing')
        answer = input('Would you like to play again?: Y/N')

        if answer.lower() == 'n':
            quit()
        elif answer.lower() == 'y':
                    clear_board()
                    main()
        else:
            print('Please choose a valid option')
            end()

def clear_board():
    for i in range(9):
        board[i] = i

# checks for a winner when called at end of each turn
def check_winner():

            # list of lists with all the winning combinations for from the tic tac toe board
            winning_list = [[board[0], board[1], board[2]], [board[3], board[4], board[5], ],
                            [board[6], board[7], board[8]], [board[0], board[4], board[8]],
                            [board[2], board[4], board[6]],
                            [board[0], board[3], board[6]], [board[1], board[4], board[7]],
                            [board[2], board[5], board[8]]]

            # iterates over the lists in winning_list
            for i, j, k in winning_list:
                # looks at the lists in winning_list to determine if a list has all x's for a win
                if i == 'x' and j == 'x' and k == 'x':
                    print('X wins')
                    end()
                # looks at the lists in winning_list to determine if a list has all o's for a win
                elif i == 'o' and j == 'o' and k == 'o':
                    print('O wins')
                    end()

if __name__ == "__main__":
    main()

You now have two methods of setting up the board.  The first is direct initialization:

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

and the second is a resetting an already existing board:

def clear_board():
    for i in range(9):
        board[i] = i

I hate that there are two.  It would be easy to make a mistake and change one (for example, changing to a 4x4 grid) but not the other.

board_layout() is an odd name for the function that prints the board.  It is not laying out the board.  I might call it print_board().

I dislike seeing the same thing over and over.  In board_layout(), you have board[ ] appear 9 times in the format string.  If you wanted to change the name of the game board, you'd have to edit the code in 9 places in this one function.  You can eliminate these duplicates using the .format() command, instead of using a f-string.  I know, seems like going backwards; f-strings are supposed to be an improvement!

'''
*************
* {} | {} | {} *
*-----------*
* {} | {} | {} *
*-----------*
* {} | {} | {} *
*************
'''.format(*board)

*board takes the board list, takes the individual elements and "splats" them all as the arguments to the .format() call.  Each argument, in turn, is substituted into the next {} format code.

Jumping ahead.

        winning_list = [[board[0], board[1], board[2]], [board[3], board[4], board[5], ],
                        [board[6], board[7], board[8]], [board[0], board[4], board[8]],
                        [board[2], board[4], board[6]],
                        [board[0], board[3], board[6]], [board[1], board[4], board[7]],
                        [board[2], board[5], board[8]]]

Again, here we have board[ ] repeated 24 times!  There has got to be a better way.  And there is.  First, create as a global constant, a list of list of winning indices.  Since these will never be modified, I've used tuples instead of lists.

WINNING_ROWS = ((0, 1, 2), (3, 4, 5), (6, 7, 8),  # Rows
                (0, 3, 6), (1, 4, 7), (2, 5, 8),  # Columns
                (0, 4, 8), (2, 4, 6))             # Diagonals

Now we just need to use these indices to check for a win condition.  We can even use chained comparisons to make the test more concise:

    for i, j, k in WINNING_ROWS:
        if board[i] == board[j] == board[k] == 'x':
            print('X wins')

That tests board[i] == board[j] AND board[j] == board[k] AND board[k] == 'x', but we haven't repeated any of the terms in the test.

        elif board[i] == board[j] == board[k] == 'o':
            print('O wins')

And now we have.

Whenever you repeat code, you should think "maybe a loop" or "maybe a function".  A loop doesn't seem right here.  Let's use a function:

def has_won(player):
    for i, j, k in WINNING_ROWS:
        if board[i] == board[j] == board[k] == player:
            return True
    return False

Now you can use if has_won('x'): to check in the 'x' player has won after they have made their move, and if has_won('o'): to check if the 'o' player has won after they have made theirs.

We can condense this function.  The all() function will test each of its arguments, and return True only if all of the arguments are true.  We can use list comprehension to extract each index in turn from the row tuples:

def has_won(player):
    for row in WINNING_ROWS:
        if all(board[idx] == player for idx in row):
            return True
    return False

Like the all() function, there is an any() function, which returns True if any of its arguments are true.  Again, we'll use list comprehension to loop over each row in WINNING_ROWS:

def has_won(player):
    return any(all(board[idx] == player for idx in row) for row in WINNING_ROWS)

For any of the winning rows, if all of the board locations contain the player's symbol, True is returned.  Pretty darn concise, if you want to use it.

Checking for a valid spot:

if board[player_move] != 'x' and board[player_move] != 'o':

if board[npc] != 'o' and board[npc] != 'x':

Effectively the same test, repeated twice.  And board[pos] referenced twice in each test.  Don't Repeat Yourself.  DRY.  As opposed to Write Everything Twice, or WET.  You want DRY code, not WET code.  The in operator will test if the item on the left of in is contained in the container on the right.

def is_valid_move(move):
    return board[move] not in ('x', 'o')

Not bad.  But is 12 a valid move?  How about -1?  Note that -1 will not cause an IndexError, it will just return the last element of the list (board[8]).

def is_valid_move(move):
    return move in range(9) and board[move] not in ('x', 'o')

Elephant in the room.

You play the game, win, play again, loose, play again, tie, play again.  What is the stack trace at this point?

main() -> check_winner() -> end() -> main() -> check_winner() -> end() -> main() -> check_winner() -> end() -> main() -> check_winner() -> end() ...

If you make a mistake and enter invalid input in the end() method, you could even have end() -> end() repeats in that stack trace.

Do not use recursion as a substitute for looping!

Here is a possible implementation, which doesn't use recursion.  Note that there are no global variables, other than the constant WINNING_ROWS.  Since board is no longer global, it can be created brand new each time a game is started.

import random

WINNING_ROWS = ((0, 1, 2), (3, 4, 5), (6, 7, 8),
                (0, 3, 6), (1, 4, 7), (2, 5, 8),
                (0, 4, 8), (2, 4, 6))

def print_board(board):
    row  = "  {} | {} | {}\n"
    line = " ---+---+---\n"
    print(((row + line) * 2 + row).format(*board))

def has_won(player, board):
    return any(all(board[idx] == player for idx in row) for row in WINNING_ROWS)

def is_valid_move(move, board):
    return move in range(9) and board[move] not in ('x', 'o')

def player_move(board):
    print_board(board)
    while True:
        try:
            move = int(input('Please select as spot: '))
            if is_valid_move(move, board):
                return move
        except ValueError:
            pass
        print('Invalid input.', end='  ')

def npc_move(board):
    while True:
        move = random.randint(0, 8)
        if is_valid_move(move, board):
            return move

def play_game():

    board = list(range(9))
    player = 'x'

    for _ in range(9):
        if player == 'x':
            move = player_move(board)
        else:
            move = npc_move(board)

        board[move] = player

        if has_won(player, board):
            print_board(board)
            print(f"{player.upper()} wins!")
            return

        player = 'o' if player == 'x' else 'x'

    print("Tie game")

def main():
    answer = 'y'

    while answer == 'y':
        play_game()

        answer = ''
        while answer not in ('y', 'n'):
            answer = input('Play again? (Y/N): ').lower()

if __name__ == '__main__':
    main()


Function to check if received message matches any of the expected messages I have a message coming in and I need to match it against the expected messages. The program will eventually do something as a result of receiving those messages. I am not very experienced at programming, but surely there should be a better way to declare all those messages it can be in like a separate entity and then be able to use it within this HexSearch.cpp file?

I tried to search how to do that but I couldn't find the right words to ask about this using a search engine. There is many more messages than those show here which still need to be declared but this is just a sample, which I don't like to look at already.

#include "HexSearch.h"

void searchFunction(int num, char msg[]) {

    static const char readReq[] = { 0x92 };
    static const char readResp[] = { 0x00, 0x02, 0x12, 0x34, 0xA1 };

    static const char writeReq[] = { 0x0A, 0xE0 };
    static const char writeResp[] = { 0x00, 0x02, 0x11, 0x01, 0x98 };

    static const char resetReq[] = { 0x00, 0xFF };
    static const char resetResp[] = { 0x00, 0x21, 0x23, 0x0E, 0xAE, 0x11, 0x3A };

    static const char verReq[] = {0x00, 0xA2};
    static const char verResp[] = {0x00, 0x03, 0x82, 0xAA, 0x07, 0x88, 0xA9};

    static const char typeReq[] = {0x00, 0x67};
    static const char typeResp[] = {0x00, 0x03, 0x00, 0x00, 0xC4, 0x77};

    static const char askReq[] = {0x00, 0x55};
    static const char askResp[] = {0x00, 0x01, 0xFE, 0xFF};

    if (num == 4) {
        replyMsg(msg, 2, 3,  readReq, readResp, sizeof(readResp) / sizeof(readResp[0]));
    }
    else if (num == 5) {
        replyMsg(msg, 2, 4, writeReq, writeResp, sizeof(writeResp) / sizeof(writeResp[0]));
        replyMsg(msg, 2, 4, resetReq, resetResp, sizeof(resetResp) / sizeof(resetResp[0]));
        replyMsg(msg, 2, 4, verReq, verResp, sizeof(verResp) / sizeof(verResp[0]));
        replyMsg(msg, 2, 4, typeReq, typeResp, sizeof(typeResp) / sizeof(typeResp[0]));
        replyMsg(msg, 2, 4, askReq, askResp, sizeof(askResp) / sizeof(askResp[0]));
    }
}

void replyMsg(char msg[], int startArr, int endArr, const char* receiv, const char* resps, int respL) {
    if (std::equal(msg + startArr, msg + endArr, receiv)) {
        for (int x = 0; x < respL; x++) {
            serialPC.putc(resps[x]);
        }
    }
}

The code works. I am interested in improving it only. num is the total number of bytes of a message. E.g. readReq has one byte of data, but has also got 2 start bytes and 1 end byte so a total of 4. readResp array has the 2 start bytes, 2 data bytes, and one end byte and so it has a total size of 5 bytes. The 2nd byte is the one which specifies the length of a message. msg[] is the message coming in from a serial connection essentially.

As an example, if msg[] = { 0x00, 0x01, 0x92, 0x56 } then num = 4 and replyMsg will compare the 3rd byte to see that it matches readReq and so output readResp...

Unfortunately your code is incomplete and can't be run in this state. Still I want to recommend some improvements to this snippets.

My first impression from this code is that it looks like plain C, not C++  (besides the use of std::equal).

To pass your Message and compare it you are using plain char arrays.
With this approach you have to also pass the size. You shouldn't feel the need for this in C++ any more. Check out containers such as std::array (fixed size) std::vector, std::string or std::string_view.

There's a bug which can make your program truncate the compared values depending on the platform:

static const char readReq[] = { 0x92 };

Consider that 0x92 = 146(int).

Not all platforms have char == unsigned char.  If you are not lucky it can mean char == signed char. See https://stackoverflow.com/questions/2054939/is-char-signed-or-unsigned-by-default

I found this by accident when I switched your plain C Array:

static const char readReq[] = { 0x92 };

To C++ std::vector:

const std::vector<char> readRequest = { 0x92 };

This doesn't event compile. The compiler complains that 0x92 truncates. So I changed it to:

const std::vector<unsigned char> readRequest = { 0x92 };

Then I thought probably it is event better to really declare your values as an array of constants. So I changed to std::array like this:

constexpr std::array<unsigned char, 1> readRequest = { 0x92 };
constexpr std::array<unsigned char, 5> readResponse = { 0x00, 0x02, 0x12, 0x34, 0xA1

Now it is similar to the old macro defines in C but better because it follows the rules of the language.:

#define readRequest 0x92

With std::array I refactored your code like this:

#include <algorithm>
#include <array>
#include <iostream>
#include <vector>

template<typename MessageBegin, typename MessageEnd, typename ReceiveType,
    typename ResponseType>
void replyMessage(
    const MessageBegin& messageBegin,
    const MessageEnd& messageEnd,
    const ReceiveType& receive,
    const ResponseType& response)
{
    if (std::equal(messageBegin, messageEnd, receive.begin())) {
        for (const auto& sign : response) {
            std::cout << sign;
            //serialPC.putc(sign);
        }
    }
}

void searchFunction(int number, const std::vector<unsigned char>& message)
{
    constexpr std::array<unsigned char, 1> readRequest = { 0x92 };
    constexpr std::array<unsigned char, 5> readResponse = { 0x00, 0x02, 0x12, 0x34, 0xA1 };

    constexpr std::array<unsigned char, 2> writeRequest = { 0x0A, 0xE0 };
    constexpr std::array<unsigned char, 5> writeResponse = { 0x00, 0x02, 0x11, 0x01, 0x98 };

    constexpr std::array<unsigned char, 2> resetRequest = { 0x00, 0xFF };
    constexpr std::array<unsigned char, 7> resetResponse = { 0x00, 0x21, 0x23, 0x0E, 0xAE, 0x11, 0x3A };

    constexpr std::array<unsigned char, 2> verReqeust = { 0x00, 0xA2 };
    constexpr std::array<unsigned char, 7> verResponse = { 0x00, 0x03, 0x82, 0xAA, 0x07, 0x88, 0xA9 };

    constexpr std::array<unsigned char, 2> typeRequest = { 0x00, 0x67 };
    constexpr std::array<unsigned char, 6> typeResponse = { 0x00, 0x03, 0x00, 0x00, 0xC4, 0x77 };

    constexpr std::array<unsigned char, 2> askRequest = { 0x00, 0x55 };
    constexpr std::array<unsigned char, 4> askResponse = { 0x00, 0x01, 0xFE, 0xFF };

    if (number == 4) {
        replyMessage(message.begin() + 2, message.begin() + 3, readRequest, readResponse);
    }
    else if (number == 5) {
        replyMessage(message.begin() + 2, message.begin() + 4, writeRequest, writeResponse);
        replyMessage(message.begin() + 2, message.begin() + 4, resetRequest, resetResponse);
        replyMessage(message.begin() + 2, message.begin() + 4, verReqeust, verResponse);
        replyMessage(message.begin() + 2, message.begin() + 4, typeRequest, typeResponse);
        replyMessage(message.begin() + 2, message.begin() + 4, askRequest, askResponse);
    }
}

In this code, other stuff was improved:

Cryptic names like msg, resps, respl or replyMsg were renamed. Sure, you can find out what they mean, but it is more stressful to read the code and get the meaning. Make a experiment. Forget the code for 6 months and come back to it. How long does it take you to get its meaning?
Functions can now accept Containers, which know their size. Also, we can simply iterate over them.

Compare this:

void replyMsg(char msg[], int startArr, int endArr, const char* receiv, const char* resps, int respL) {
    if (std::equal(msg + startArr, msg + endArr, receiv)) {
        for (int x = 0; x < respL; x++) {
            serialPC.putc(resps[x]);
        }
    }
}

with this:

template<typename MessageBegin, typename MessageEnd, typename ReceiveType,
    typename ResponseType>
void replyMessage(
    const MessageBegin& messageBegin,
    const MessageEnd& messageEnd,
    const ReceiveType& receive,
    const ResponseType& response)
{
    if (std::equal(messageBegin, messageEnd, receive.begin())) {
        for (const auto& sign : response) {
            std::cout << sign;
            //serialPC.putc(sign);  // btw what is this???
        }
    }
}

Besides the template, which we had to use because of different array sizes, which is easier to understand?