texts: Simple Effects in Angular 2+ application using Firebase, NGRX and RXJS

texts:
Made an Angular app using Firebase, RXJS and NGRX.
@Effect()
createQuiz$: Observable<Action> = this.actions$.pipe(
    ofType<quizAction.CreateQuiz>(quizAction.CREATE_QUIZ),
    switchMap((action) => {
        return this.quizService.createQuiz(action.payload)
        .pipe(
        map(() => {
            return new quizAction.CreateQuizCompleted()
        }),
        catchError(error => {
            console.log(error);
            return of(new quizAction.CreateQuizCompleted());
        })
        );
    })
);

@Effect()
updateQuiz$: Observable<Action> = this.actions$.pipe(
    ofType<quizAction.UpdateQuiz>(quizAction.UPDATE_QUIZ),
    switchMap((action) => {
        return this.quizService.updateQuiz(action.payload)
        .pipe(
        map(() => {
            return new quizAction.UpdateQuizCompleted()
        }),
        catchError(error => {
            console.log(error);
            return of(new quizAction.UpdateQuizCompleted());
        })
        );
    })
);

@Effect()
deleteQuiz$: Observable<Action> = this.actions$.pipe(
    ofType<quizAction.DeleteQuiz>(quizAction.DELETE_QUIZ),
    switchMap((action) => {
        return this.quizService.deleteQuiz(action.payload)
        .pipe(
        map(() => {
            return new quizAction.DeleteQuizCompleted()
        }),
        catchError(error => {
            console.log(error);
            return of(new quizAction.DeleteQuizCompleted());
        })
        );
    })
);

These are the NGRX effects. They are triggering a reducer function, then call a service function and then trigger another reducer function upon completion.
export class QuizComponent implements OnInit {

  constructor(
    private quizService: QuizService,
    private store:Store<{app: fromApp.State}>,
  ) { }

  ngOnInit(): void {
  }

  trackByIdx = (index: number): number => index;

  onCreate(): void {
    this.store.select(fromApp.selectUserId).pipe(
      take(1)
    ).subscribe(userId => this.handleCreate(userId));
  }

  onDelete(id: string): void {
    this.store.dispatch(new AppAction.DeletePoll(id));
  }

  onEdit(): void {
    let value = this.quizService.createCustomQuiz();
    if (this.quizService.hasPermission(userId) && this.pollService.validateQuiz(value)) {
      this.store.dispatch(new quizAction.UpdatePoll(value));
    }
  }

  handleCreate(userId: string): void {
    let value = this.quizService.createDefaultQuiz();
    if (this.quizService.hasPermission(userId) && this.quizService.validateQuiz(value)) {
      this.store.dispatch(new quizAction.CreateQuiz(value));
    }
  }
}

This is the component that dispatches the actions.
  createQuiz(quiz:Quiz) {
    const id = this.db.createId();
    return from(
      this.db
        .collection('quizzes')
        .doc(id)
        .set({...quiz, id: id})
    );

  }

  updateQuiz(quiz:Quiz) {
    return from(
      this.db
        .collection('quizzes')
        .doc(quiz.id)
        .set(quiz, { merge: false })
    );
  }

  deleteQuiz(id:string) {
    return from(
      this.db
        .collection('quizzes')
        .doc(id)
        .delete()
    );
  }

These are the service methods. I am wondering if there's any improvement and if switchmap and map are correctly used.


texts:
I have inherited a C++ Win32 thread class which roughly works like this. I am looking for ways to improve the design; specifically I am looking for a way to get rid of the spurious Resume() call at the end of initialization. Is there a way this can be automated or omitted?

Base class

class CThread {
public:
    CThread(DWORD dwCreationFlags = 0)
        : m_hThread(Create(ThreadProc,
                           this,
                           dwCreationFlags,
                           NULL,
                           0,
                           &m_dwThreadId))
    {}

    DWORD Resume() { return ::ResumeThread(m_hThread); }

protected:
    HANDLE  m_hThread;
    DWORD   m_dwThreadId;

private:
    static HANDLE Create(LPTHREAD_START_ROUTINE pThreadProc,
                         LPVOID pParam = NULL,
                         DWORD dwCreationFlags = 0,
                         LPSECURITY_ATTRIBUTES pSecurityAttr = NULL,
                         DWORD dwStackSize = 0,
                         DWORD *pdwThreadId = NULL)
    {
        /* start thread using _beginthreadex */
        return hThread;
    }

    static DWORD WINAPI ThreadProc(LPVOID p)
    {
        CThread* pThreadObj = reinterpret_cast<CThread *>(p);
        return pThreadObj->Execute();
    }
};

So now when I make a subclass to start the thread, I need to start it suspended because otherwise it might run without being fully initialized, and then resume it after initialization:

Actual thread implementation class

class CCreateRestorePointThread
        : public CThread
{
    CCreateRestorePointThread(std::wstring const&    name,
                              zRestorePointEventType eventType,
                              zRestorePointType      restorePointType)
/* I think I need to start suspended this so that initialization can take place */
        : CThread(CREATE_SUSPENDED)
        , m_hSrClient(::LoadLibraryW(L"srclient.dll"))
        , m_bRet(FALSE)
        , m_isFinished(false)
    {
        /* Initialize Restore Point System, structures etc. */
        this->Resume(); /* I wanna get rid of this line */
    }

private:
    DWORD Execute()
    {
        /* Create Restore Point using class members */
        return m_stateMgrStatus.nStatus;
    }
};


texts:
I am maintaining an application and have seen something like this

Permission p = new UserModel().GetPermission(userToTestPerrmission, permissionWeCheck);
if(p.CanChange)
   //sometihing
else
   //something else

This approach looks a little "dirty" to me. The part I have problems with is this new UserModel().GetPermission(). Is this a typical way to write something like this or should it be like:

var model = new UserModel();
model.GetPermissions(...);
...


texts:
Here's a messy C# method used to calculate some business logic.

Does anybody have any suggestions on how I can optimise this code? I'm asking in case there are bad practices, improvements or functions within .NET/LINQ which I'm missing.

private static decimal GetRecurringCostEquiv(List<QuotationItemViewModel> items)
{

    var discVal = GetDiscounts(items, (int)RecordEnums.ProductClassification.Service);

    decimal? currentRecurringCosts = GetRecurringCost(items).Value;

    decimal? result = 0.00M;

    decimal highestContractTerm = items.Where(x => x.ProductTypeId == (int)RecordEnums.ProductClassification.Service).Select(y => y.RecurringTerm).Max() ?? 0;

    if ((discVal > 0) && (highestContractTerm > 0))
    {
        var calc = items.Where(x => x.ProductTypeId == (int)RecordEnums.ProductClassification.Service).Select(y => y.RecurringCostCore * y.Quantity);
        decimal total = calc.Sum() ?? 0;
        decimal totalOverTerm = total * highestContractTerm;
        decimal totalOverTermMinusDiscounts = totalOverTerm - discVal;
        result = totalOverTermMinusDiscounts / highestContractTerm;
    }
    else
    {
        result = currentRecurringCosts;
    }

    return result ?? 0.00M;
}


texts: Function to search for weekends left in month

texts:
I have a function that returns true or false depending upon whether there are any weekend days left in the month.  Is there a better/cleaner way that I can write this?

function checkWeekendsLeft(month, year) {
  var iDaysInMonth   = new Date(year, month, 0).getDate();
  var iCurDayInMonth = new Date().getDate();
  var x              = new Date();
  var weekends       = [];

  if (iDaysInMonth >= iCurDayInMonth) {
    for(var i = iDaysInMonth; i >= iCurDayInMonth; i--) {
      var iDayofMonth = i;
      var date = new Date(year, month - 1, iDayofMonth);
      var iDayOfWeek = date.getDay();
      if(iDayOfWeek === 6 || iDayOfWeek === 0) {
        weekends.push(iDayOfWeek);
      }
    }
    if(weekends.length > 0) {
      return true;
    } else {
      return false;
    }
  }
}


texts:
Version 1 - Beginner web scraper for Nagios

Current version changes:

Moved NAGIOS_DATA dictionary to separate file (and added to .gitignore)
Used functions with DOCSTRINGS
Removed the multiple redundant print() statements
Actually read the PEP8 standards, and renamed variables to match the requirements

Again, beginner Python programmer. I appreciate the feedback!

import requests
from scraper import NAGIOS_DATA
from bs4 import BeautifulSoup
from requests.auth import HTTPBasicAuth, HTTPDigestAuth

def get_url_response(url, user, password, auth_type):
    """Get the response from a URL.

    Args:
        url (str): Nagios base URL
        user (str): Nagios username
        password (str): Nagios password
        auth_type (str): Nagios auth_type - Basic or Digest

    Returns: Response object
    """

    if auth_type == "Basic":
        return requests.get(url, auth=HTTPBasicAuth(user, password))
    return requests.get(url, auth=HTTPDigestAuth(user, password))

def main():
    """
    Main entry to the program
    """

    # for nagios_entry in ALL_NAGIOS_INFO:
    for url, auth_data in NAGIOS_DATA.items():
        user, password, auth_type = auth_data["user"], auth_data["password"], \
            auth_data["auth_type"]
        full_url = "{}/cgi-bin/status.cgi?host=all".format(url)
        response = get_url_response(full_url, user, password, auth_type)
        if response.status_code == 200:
            html = BeautifulSoup(response.text, "html.parser")
            for i, items in enumerate(html.select('td')):
                if i == 3:
                    hostsAll = items.text.split('\n')
                    hosts_up = hostsAll[12]
                    hosts_down = hostsAll[13]
                    hosts_unreachable = hostsAll[14]
                    hosts_pending = hostsAll[15]
                    hosts_problems = hostsAll[24]
                    hosts_types = hostsAll[25]
                if i == 12:
                    serviceAll = items.text.split('\n')
                    service_ok = serviceAll[13]
                    service_warning = serviceAll[14]
                    service_unknown = serviceAll[15]
                    service_critical = serviceAll[16]
                    service_problems = serviceAll[26]
                    service_types = serviceAll[27]
                # print(i, items.text) ## To get the index and text
            print_stats(
                user, url, hosts_up, hosts_down, hosts_unreachable,
                hosts_pending, hosts_problems, hosts_types, service_ok,
                service_warning, service_unknown, service_critical,
                service_problems, service_types)

    # print("Request returned:\n\n{}".format(html.text))
    # To get the full request

def print_stats(
        user, url, hosts_up, hosts_down, hosts_unreachable, hosts_pending,
        hosts_problems, hosts_types, service_ok, service_warning,
        service_unknown, service_critical, service_problems, service_types):
    print("""{}@{}:
                Hosts
    Up\tDown\tUnreachable\tPending\tProblems\tTypes
    {}\t{}\t{}\t\t{}\t{}\t\t{}
                Services
    OK\tWarning\tUnknown\tCritical\tProblems\tTypes
    {}\t{}\t{}\t{}\t\t{}\t\t{}""".format(
        user, url, hosts_up, hosts_down, hosts_unreachable, hosts_pending,
        hosts_problems, hosts_types, service_ok, service_warning,
        service_unknown, service_critical, service_problems, service_types))

if __name__ == '__main__':
    main()

scraper.py source:

NAGIOS_DATA = {
    'http://192.168.0.5/nagios': {
        'user': 'nagiosadmin',
        'password': 'PasswordHere1',
        'auth_type': 'Basic'
    },
    'https://www.example.com/nagios': {
        'user': 'exampleuser',
        'password': 'P@ssw0rd2',
        'auth_type': 'Digest'
    },
}


texts: Looping over a map requiring casting and instance checks

texts:
The following method works. I am looking for advice to make it more readable.
To see if I could avoid any unneccesary checks / casting and the instance of check.
Also not a fan of having to recreate the initial String with every loop but not sure if there is a way around it.

  Things to note.
  I am using Java 8 and Spring boot.
  I can't change the productMap. It will remain as a Map < String, Object> .
  Can use external library Apache commons but not Guava.
  It is possible for initialText and productMap to be null / empty.
  In the map, I am only looking for values which are of type String and value contains only numbers.
  If it exists, I want to use it and replace initialText

Example scenario with following data in the parameters being passed in:

String initialText = "This is a sample text with PLACEHOLDER and yet another PLACEHOLDER and more message."
productMap = {
    "Some key" : new SomeObject(), // I won't use this cos value is not String.
    "PLACEHOLDER" : "26000", // I will use this to replace cos the key PLACEHOLDER exists in above text and it contains only numbers.
    "SOME_OTHER" : "SOME_TEXT", // it is a String value but the key doesn't exist in the initial text thus no difference.
}

After executing the following code, I expect the method to return the updated String as follows (notice the comma due to String format):

"This is a sample text with 26,000 and yet another 26,000 and more message."

Method as follows. Appreciate the advices. Thanks.

public String update(String initialText, Map<String, Object> productMap){
    if(StringUtils.isBlank(initialText) || MapUtils.isEmpty(productMap)){
        return initialText;
    }
    for (Map.Entry<String, Object> productData : productMap.entrySet()) {
        String key = productData.getKey();
        Object value = productData.getValue();
        if(value instanceof String && ((String) value).matches("[0-9]+")){
            String offerValue = (String)value;
            initialText = initialText.replaceAll(key, String.format("%,d", Integer.parseInt(offerValue)));
        }
    }
    return initialText;
}


texts: Should this be written with exception handling instead of nested if-thens?

texts:
I have a function that iterates through a list of file updates, and for each file, if updates are needed, download the file from the server, make the updates, and upload the updated version.  Each update gets marked with a string identifying the result of the update operation.

There are several steps in the update process where I would not want updating to continue for that file.  Right now I have a lot of nested if-then statements, so that the iteration won't proceed any further for that file and will just mark the issue and go on to the next file.  Code as follows:

    public void updateAllFiles()
    {
        foreach (string fileName in updateList.fileNameList())
        {
            updatesForFile = updateList.updatesForFile(fileName);
            hyperlinkEntry = hyperlinkList.getHyperlinkEntry(fileName);
            if (hyperlinkEntry == null)
            {
                updatesForFile.markResultAllRows("File not found on server");
            }
            else
            {
                hyperlink = hyperlinkEntry.hyperlink;
                if (updatesForFile.updateNeeded())
                {
                    if (!po.checkout(hyperlink))
                    {
                        updatesForFile.markResultAllRows("checked out to other user");
                    }
                    else
                    {
                        downloadPath = downloadFolder + fileName;
                        downloadResult = dl.download(hyperlink, downloadPath);
                        if (downloadResult == false)
                        {
                            updatesForFile.markResultAllRows("download failed");
                        }
                        else
                        {
                            file = new FileObject(xlApp, downloadPath, updatesForFile);
                            if (file == null)
                            {
                                updatesForFile.markResultAllRows("unable to open");
                            }
                            else
                            {
                                foreach (FeatureUpdate featureUpdate in updatesForFile.getFeatureUpdateList())
                                {
                                    resultValue = featureUpdate.getColumnValue("result");
                                    if (!resultValue.Contains("updated"))
                                    {
                                        file.update(featureUpdate, updateMethods.lowFeatureLength);
                                        updatesForFile.markResult(featureUpdate.getIndex(), "updated");
                                    }
                                }
                                file.close();
                                updateList.save();
                            }
                        }
                    }
                }
            }
        }

    }

Because it's getting harder to read the code, I'm wondering if I should use exception handling here instead, and if so, how it should be implemented here--e.g., should an exception be thrown in getHyperlinkEntry() and caught in updateAllFiles(), or should it be thrown and caught in updateAllFiles() like this?

try
{
    hyperlinkEntry=hyperlinkList.getHyperlinkEntry(fileName);
    if (hyperlinkEntry == null)
    {
        throw new UpdateException("File not found on server");
    }

    ///more function calls and exception throwing here
}
catch (UpdateException ue)
{
    updatesForFile.markResultAllRows(ue.updateMessage);
}

Or are the existing nested if-then clauses more appropriate for this situation?


texts:
I have written a program to find prime numbers up to a given limit using wheel factorization of 2, 3 and 5. I would like it to work above \$10^{10}\$, but its still pretty slow.

What else can I optimize here.
Any way I can parallelize it?
I am pretty sure markNonPrimes's algorithm is less efficient than it should be. Is it?  I feel that I am brute forcing there: it takes ~250ms when limit is \$10^6\$, ~1500ms when limit is \$10^8\$.

#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>

typedef uint64_t u64;

const uint8_t ONE = 1;
const u64 F30[] = {1,7,11,13,17,19,23,29};

void markNonPrimes(const u64 start, const u64 num, const u64 lcm, const u64 limit, std::vector<uint8_t> &primes)
{
   for (u64 k = start; (lcm*k) < limit; k++)
   {
      u64 K = lcm*k;
      if ((primes[k] & (ONE << 0)) && (K+F30[0]) % num == 0)
         primes[k] &= ~(ONE << 0);
      if ((primes[k] & (ONE << 1)) && (K+F30[1]) % num == 0)
         primes[k] &= ~(ONE << 1);
      if ((primes[k] & (ONE << 2)) && (K+F30[2]) % num == 0)
         primes[k] &= ~(ONE << 2);
      if ((primes[k] & (ONE << 3)) && (K+F30[3]) % num == 0)
         primes[k] &= ~(ONE << 3);
      if ((primes[k] & (ONE << 4)) && (K+F30[4]) % num == 0)
         primes[k] &= ~(ONE << 4);
      if ((primes[k] & (ONE << 5)) && (K+F30[5]) % num == 0)
         primes[k] &= ~(ONE << 5);
      if ((primes[k] & (ONE << 6)) && (K+F30[6]) % num == 0)
         primes[k] &= ~(ONE << 6);
      if ((primes[k] & (ONE << 7)) && (K+F30[7]) % num == 0)
         primes[k] &= ~(ONE << 7);
   }
}

void getPrimesUpto(u64 limit)
{
   const u64 lcm = 30;
   std::vector<uint8_t> primes(limit*0.26 + 1,0xff);

   u64 k = 1;
   u64 n = 0;
   u64 count=3-1;

   markNonPrimes(k, F30[1], lcm, limit, primes);
   markNonPrimes(k, F30[2], lcm, limit, primes);
   markNonPrimes(k, F30[3], lcm, limit, primes);
   markNonPrimes(k, F30[4], lcm, limit, primes);
   markNonPrimes(k, F30[5], lcm, limit, primes);
   markNonPrimes(k, F30[6], lcm, limit, primes);
   markNonPrimes(k, F30[7], lcm, limit, primes);

   while(lcm*k*lcm*k<limit)
   {
      const u64 K = lcm*k;
      if(primes[k] & (ONE<<0))
         markNonPrimes(k+1, K+F30[0], lcm, limit, primes);

      if(primes[k] & (ONE<<1))
         markNonPrimes(k+1, K+F30[1], lcm, limit, primes);

      if(primes[k] & (ONE<<2))
         markNonPrimes(k+1, K+F30[2], lcm, limit, primes);

      if(primes[k] & (ONE<<3))
         markNonPrimes(k+1, K+F30[3], lcm, limit, primes);

      if(primes[k] & (ONE<<4))
         markNonPrimes(k+1, K+F30[4], lcm, limit, primes);

      if(primes[k] & (ONE<<5))
         markNonPrimes(k+1, K+F30[5], lcm, limit, primes);

      if(primes[k] & (ONE<<6))
         markNonPrimes(k+1, K+F30[6], lcm, limit, primes);

      if(primes[k] & (ONE<<7))
         markNonPrimes(k+1, K+F30[7], lcm, limit, primes);

      k++;
   }

   for(u64 k=0; lcm*k < limit; k++ )
   {
      for(u64 i =0; i<8; i++)
         if(primes[k] & ONE<< i && lcm*k+F30[i] < limit) {count++;/*std::cout << lcm*k+F30[i] << " ";*/}
   }

   std::cout  << "\n======\n"<< count << "\n";
}

int main()
{
   clock_t start = clock();
   getPrimesUpto(100);
   std::cout << "\nTime: "<< clock() - start << std::endl;
}


texts: Ising model simulation using metropolis algorithm

texts:
I am new to this community; I have tried my best to respect the policy of the community. I have written the Monte Carlo metropolis algorithm for the ising model. I want to optimize the code. I have tried my best. I want to optimize it further. The following is the code:

(I have used tricks like finding exponential only once, careful generation of random number, etc.)

import numpy as np
import time
import random

def monteCarlo(N,state,Energy,Mag,Beta,sweeps):
    if sweeps > 10000:
        print("Warning:Number of sweeps exceeded 10000\n\tsetting number of sweeps to 10000")
        sweeps = 10000
    start_time = time.time()
    expBeta = np.exp(-Beta*np.arange(0,9))
    E = np.zeros(sweeps)
    M = np.zeros(sweeps)
    for t in range(sweeps):
        for tt in range(N*N):
            a = random.randint(0, N-1)
            b = random.randint(0, N-1)
            s = state[a,b]
            delta_E = 2*s*(state[(a+1)%N,b] + state[a,(b+1)%N] + state[(a-1)%N,b] + state[a,(b-1)%N])
            if delta_E < 0:
                s *= -1
                Energy += delta_E
                Mag += 2*s
            elif random.random() < expBeta[delta_E]:
                s *= -1
                Energy += delta_E
                Mag += 2*s
            state[a, b] = s
        E[t] = Energy
        M[t] = Mag
    print("%d monte carlo sweeps completed in %d seconds" %(sweeps,time.time()-start_time))
    return E,M #returning list of Energy and Magnetization set

#####lattice config#####
"""N is lattice size
nt is number of Temperature points
sweeps are number of mc steps per spin"""
print("Starting Ising Model Simulation")
N = int(input("Enter lattice size : "))
startTime = time.time()
nt = 10
N2 = N*N
sweeps = 10000 #mc steps per spin
"""we will plot the following wrt temperature, T"""
T = np.linspace(2, 3, nt) #you can set temperature range
"""preparing lattice with all spins up"""
state = np.ones((N,N),dtype="int")
Energy = -N2
Mag = N2
#temperature loop
#for k in tqdm_gui(range(nt)):
for k in range(nt):
    temp = T[k]
    Beta=1/temp
    print("____________________________________\nTemperature is %0.2f, time is %d" %(temp,time.time()-startTime))
    E, M = monteCarlo(N,state,Energy,Mag,Beta,sweeps) #list of Energy and Magnetization
    Energy = E[-1]
    Mag = M[-1]

#further code is finding magnetization, autocorrelation, specific heat, autocorrelation, etc.
```


texts:
One of the annoying things about OCaml arrays is that every cell has to be initialized when the array is first created.

I'm trying to implement an array in OCaml that distinguishes size (the current number of elements in the array) from capacity (the maximum size that the array can grow to).

At any given point in the array's lifetime, the "inhabited cells" must form a prefix of the array itself. In other words, you can't do something like:

1 2 UNINITIALIZED 3 4 UNINITIALIZED

The array also clears cell immediately once they've been popped so the application doesn't leak memory / hold references to stuff that "used to be in the array" but isn't anymore.

The array uses the last element as the size. The reason for this is three-fold: 1) creating an array only requires one call to Array.make 2) you don't need to do any arithmetic on the indices to access the elements in the underlying array and 3) it only requires chasing one pointer, not two, to get to the elements.

This code uses Obj.magic, but I try to confine it to places where it can be easily audited.

I'm not using Sys.opaque_identity from the Sys Module anywhere because I'm not actually using uninitialized memory anywhere ... I'm just using Obj.magic to subvert the type system and let me store integers in strategic places. I am curious what work is needed to flambda-proof this code though.

Anyway, here's the interface file uninit.mli:

type 'a t

val make : int -> 'a t

val size : 'a t -> int

val cap : 'a t -> int

val get_exn : 'a t -> int -> 'a

val get_opt : 'a t -> int -> 'a option

val set_exn : 'a t -> int -> 'a -> unit

val append_exn : 'a t -> 'a -> unit

val pop_exn : 'a t -> 'a

And the source file uninit.ml:

type 'a t = 'a array

(* set every value to the integer 0, regardless of the
 * type of the array.
 * note that the last zero is special, it is the current size
 * of the array. *)
let make : int -> 'a t =
    fun cap -> Array.make (cap + 1) (Obj.magic 0)

let cap : 'a . 'a t -> int =
    fun arr -> (-1) + Array.length arr

(* get the index of the size. This is the same as the capacity *)
let size_idx : 'a t -> int = cap

let size : 'a . 'a t -> int =
    fun arr -> (Obj.magic arr.(size_idx arr))

(* NOTE: incr_size is not checked and not safe *)
let incr_size : 'a . 'a t -> unit =
    fun arr ->
        let new_size : int = 1 + Obj.magic arr.(size_idx arr) in
        arr.(size_idx arr) <- (Obj.magic new_size)

(* NOTE: decr_size is not checked and not safe *)
let decr_size : 'a . 'a t -> unit =
    fun arr ->
        let new_size : int = -1 + Obj.magic arr.(size_idx arr) in
        arr.(size_idx arr) <- (Obj.magic new_size)

let get_exn : 'a . 'a t -> int -> 'a =
    fun arr idx ->
        if idx < size arr then arr.(idx) else raise (Invalid_argument "out of bounds")

let get_opt : 'a . 'a t -> int -> 'a option =
    fun arr idx ->
        if idx < size arr then Some arr.(idx) else None

let set_exn : 'a . 'a t -> int -> 'a -> unit =
    fun arr idx v ->
        if idx < size arr then arr.(idx) <- v else raise (Invalid_argument "out of bounds")

let append_exn : 'a . 'a t -> 'a -> unit =
    fun arr v ->
        let s = size arr in
        let c = cap arr in
        if s = c then
            failwith "cannot extend array! size = capacity"
        else
            (* put the new item one after the last item, increment
             * the size by 1 *)
            (arr.(s) <- v; incr_size arr)

let pop_exn : 'a . 'a t -> 'a =
    fun arr ->
        let s = size arr in
        if size arr = 0 then
            failwith "cannot pop from empty array"
        else
            let item = arr.(-1 + s) in
            (* shrink the array, re-zero the discarded element *)
            (decr_size arr; arr.(-1 + s) <- (Obj.magic 0); item)


texts: Picking weighed enumerable values at random

texts:
I have a number of enumerables, and I want to randomly pick one value from one of the enumerables so that each value has a certain weight in the randomisation process. This is simplification of my current code:

private enum ActionPlan //Just an example, there can be many different enums
{
    DoNothing,
    Eat,
    StealFoodCovertly,
    AttackAndSteal,
}

private ActionPlan PickPlan()
{
    double[] odds = new double[Enum.GetNames(typeof(ActionPlan)).Length];
    odds[(int)ActionPlan.DoNothing] = 2.5;
    odds[(int)ActionPlan.Eat] = 3;
    odds[(int)ActionPlan.StealFoodCovertly] = 1;
    odds[(int)ActionPlan.AttackAndSteal] = 0.5;

    ActionPlan plan = (ActionPlan)PickOption(odds);
    return plan;
}

private int PickOption(double[] odds)
{
    double totalOdds = 0;
    foreach (double odd in odds)
    {
        totalOdds += odd;
    }
    double pick = rand.NextDouble() * totalOdds;
    for (int i = 0; i < odds.Length; ++i)
    {
        pick -= odds[i];
        if (pick <= 0)
        {
            return i;
        }
    }
    return odds.Length - 1; // In case there are some precision shenanigans
}

I can't help but to think I'm trying to force a square peg into a round hole with all the casting going on. Is there some better way to accomplish this functionality? The idea was that the PickOption method can handle any enumerable and odds I throw at it.

I understand this question is rather open ended, but it doesn't hurt to ask, I suppose.


texts: jQuery grid-system - handing different row widths

texts:
I made a function in jQuery for my home-made grid system. When a row has too many columns in it, it removes the HTML code from that row.

Normally in my grid system it fits 12 columns in 1 row, but with the function this can easily be changed.

One column with the size of 1 (declared as: column size-1) has a width of 1/12 (or 8.3333%).

function validateRowWidth() {
    var _row = $('.row');
    _row.each(function (index, element) {
        var totalWidth = 0,
            _columnSize = $(element).find('[class*="size-"]');
        _columnSize.each(function (index, element) {
            var width = $(element).outerWidth(true),
                inProcent = Math.round((width / $(element).parent().width()) * 100);
            totalWidth += inProcent;
        });
        if (totalWidth > 100) {
            console.log('You have to many columns into your '+(index + 1)+'th row');
            $(element).remove();
        }
    });
}

Is there any way I can improve this?


texts:
I'm trying to make a simple console application game.  The code is a bit messy and I hope anyone can point out anything wrong.

using System;
using System.Collections.Generic;

namespace CalculatePoints
{
class Program
{
    static void Main(string[] args)
    {
        Game game = new Game();
        game.PlayGame();
    }
}

class Game
{
    private List<Player> player = new List<Player>();

    public void AddPlayer(string name)
    {
        Player person = new Player(name);
        player.Add(person);
    }

    public void PlayGame()
    {
        Console.Write("enter amount of player: ");
        int playerAmount = Convert.ToInt32(Console.ReadLine());

        for (int i = 0; i < playerAmount; i++)
        {
            Console.Write("enter player name: ");
            string playerName = Console.ReadLine();
            AddPlayer(playerName);
        }

        Console.WriteLine("game start");
        foreach (Player name in player)
        {
            Console.WriteLine(name + " turn ");

            Console.WriteLine("enter score 1:");
            int score1 = Int32.Parse(Console.ReadLine());

            Console.WriteLine("enter score 2:");
            int score2 = Int32.Parse(Console.ReadLine());

            Console.WriteLine("enter score 3:");
            int score3 = Int32.Parse(Console.ReadLine());

            Throw result = new Throw(score1, score2, score3);
            Console.WriteLine(result.GetScore());
        }
        Console.ReadKey();
    }
}

class Player
{
    public string Name { get; set; }
    public List<Throw> throwList = new List<Throw>();

    public Player(string name = "")
    {
        Name = name;
    }

    public override string ToString()
    {
        return Name;
    }
}

class Throw
{
    private int throwOne;
    private int throwTwo;
    private int throwThree;

    public Throw(int throwOne = 0, int throwTwo = 0, int throwThree = 0)
    {
        this.throwOne = throwOne;
        this.throwTwo = throwTwo;
        this.throwThree = throwThree;
    }

    public int GetScore()
    {
        return throwOne + throwTwo + throwThree;
    }

    public override string ToString()
    {
        return string.Format("Your total score is {0}", GetScore());
    }
}
}


texts:
I've written a short script to print a number to a string. This actually was very difficult for me to do -- I'm not sure if this is actually a tricky task or just because I'm so new to asm I was having a hard time. Here it is:
SYS_EXIT    = 60
SYS_WRITE   = 1
SYS_STDOUT  = 1

.section .rodata
number: .long   774728

.text
.globl _start
_start:

    # set up stack, align on 16 for syscalls
    push %rbp
    mov %rsp, %rbp
    push number
    sub $16, %rsp

    # r12 will store the size of the string to print
    xor %r12d, %r12d

    # on the stack we will store:
    # rbp-16 (properly sorted number to print)
    # rbp-8  (number that remains)
    # rbp-4  (current right-most digit, ie,remainder)

  loop:

    # if the number is zero, jump to print it
    cmpl $0, -8(%rbp)
    je print
    inc %r12d # increment the size of the string to print

    # Divide by ten
    # - %rdx will give us the remainder (right-most digit)
    # - %rax will give us the new number (for our next iteration of the loop
    xor %edx,       %edx
    movl -8(%rbp),  %eax
    mov $10,        %ebx
    div %ebx

    movl %eax,  -8(%rbp)

    # (a) add 48, because ASCII is number + 48, for example ord('7') ==> 55
    addl $48,   %edx
    # (b) move the asci number to rbp-8-len (to print in reverse)
    # store offset (8+len) in %r13
    mov $-8,        %r13
    sub %r12,       %r13
    movb %dl,       (%rbp, %r13)

    jmp loop

  print:
    # print(%edi:stdout(int), %esi:mem_of_string(* void), %edx:len_of_string(int))
    # (b) How to print the digit to asci (probably fixed offset for 0-9)
    # Our output has length %r12 and starts at rbp-8-len
    # Which, conveniently enough, is (%rbp, %r13)!
    mov $SYS_STDOUT,    %edi
    lea (%rbp, %r13),   %rsi    # remember, this is an 8-byte MEMORY ADDRESS (pointer), not a number
    mov %r12d,          %edx
    mov $SYS_WRITE,     %eax
    syscall

  exit:
    add $8, %rsp    # <-- can also do an empty pop, such as pop %rcx
    mov             %rbp, %rsp
    pop             %rbp
    mov $0,         %rdi
    mov $SYS_EXIT,  %eax
    syscall

And running it:
13_strings$ as file.s -o file.o && ld file.o -o file && ./file
# 774728

Thank you for taking the time to review. Any feedback would be greatly appreciated!


texts: Building SQL from multiple combinations of query parameters

texts:
I have a node.js/express.js based REST application. In one GET service I am querying data based on different set of request parameters. I am looking for a better way to implement it.

function handleGet(connection,req,res) {

var sql = 'SELECT id, name, age, rent, marks FROM student WHERE class = 10';

if (req.param('minAge') && req.param('maxAge')) {
    sql = sql + ' AND age BETWEEN ' + connection.escape(req.param('minAge')) + ' AND ' + connection.escape(req.param('maxAge'));
}

if (req.param('minRent') && req.param('maxRent')) {
    sql =sql + ' AND rent BETWEEN ' + connection.escape(req.param('minRent'))
        + ' AND ' + connection.escape(req.param('maxRent'));
};

if (req.param('marks')) {
    sql = sql + ' AND marks >= ' + connection.escape(req.param('marks'));
};

};

var limit = ('undefined' === typeof req.params.limit) ? 20: req.params.limit;

connection.query(sql + ' ORDER BY id DESC LIMIT ' + limit, function handleSql(err, rows){
        if (err){ logAndRespond(err,res); return; }
        if (rows.length === 0){ res.send(204); return; }
        res.json(200, {'students':rows});
        connection.release();
});
}

Data can be queried by passing difference combination request parameters. Can anyone please suggest any better (reusable, abstract, robust) way of doing it? I was wondering if I can create a module for building query. Something like setting all param values in the module and let the module validate and construct the query.


texts: PHP DAO classes inherit from a generic DAO classes and only change the table name

texts:
I am building a web app that needs to access various tables in a given MySQL db.  To do that, I have created a generic class, see DAO_DBRecord.php below, and I create children classes for each table I want to access, e.g., DAO_User.php is used to access the users table.  The only difference in the children classes is that I change the value of the variable which contains the name of the table I wish to access.

My questions are:
1 - Should I make the DAO_DBRecord.php class abstract?  I'm not planning to instantiate it, and in fact as it is written I cannot access any table with it.
2 - Should I use constants in the DAO_DBRecord.php class (e.g., const USER_TABLENAME = 'users';  const ARTICLE_TABLENAME = 'articles';) and reference them in the children classes (e.g., private Stable = USER_TABLENAME;)?
3 - Anything else I should do?

Class_DB.php:

<?php
    class DB {
        private $dbHost;
        private $dbName;
        private $dbUser;
        private $dbPassword;

        function __construct($dbHost, $dbName, $dbUser, $dbPassword) {
            $this->dbHost=$dbHost;
            $this->dbName=$dbName;
            $this->dbUser=$dbUser;
            $this->dbPassword=$dbPassword;
        }

        function createConnexion() {
            return new PDO("mysql:host=$this->dbHost;dbname=$this->dbName",
                        $this->dbUser, $this->dbPassword);
        }
    }
?>

DAO_DBRecord.php

<?php
    require_once('Class_DB.php');

    class DAO_DBrecord {
        private $dbh; // This is an instance of Class_DB to be injected in the functions.
        private $table=NULL;

        function __construct($dbh){
            $this->dbh=$dbh;
        }
        function dbConnect(){
            $dbConnection=$this->dbh->createConnexion();
            return $dbConnection;
        }
        function checkRecordExists($recordIdentifier, $tableColName){
            $dbConnection=$this->dbConnect();
            $query=$dbConnection->prepare("SELECT COUNT(*) FROM $table "
                . "WHERE $tableColName = :recordIdentifier");
            $query->bindParam(":recordIdentifier", $recordIdentifier);
            $query->execute();
            $result=$query->fetch(PDO::FETCH_ASSOC);
            if ($result["COUNT(*)"]>0){
                return true;
            } else return false;
        }
    }
?>

DAO_Users.php

<?php
    class DAO_User extends DAO_DBRecord {
        private $table='users';
    }
?>


texts:
I was just messing around with python making wav files; when I came up with this (what I think is) pretty neat script. It takes each character and represents it with a tone.

import wave
import struct
from math import sin
import os

RATE = 44100
maxVol = 2 ** 15 - 1.0  # maximum amplitude

noise_output = wave.open('noise2.wav', 'w')
noise_output.setparams((2, 2, 44100, 0, 'NONE', 'not compressed'))

a = lambda i, f: sin(f * i / RATE)
f = open(os.path.basename(__file__)).read()
values = [[a, (ord(l))] for l in f]
result = []
count = 0

for i, j in values:
    count_end = count + RATE / 8
    while count < count_end:
        packed_value = struct.pack('h', maxVol * i(count, j * 20 + 1000))
        result.append(packed_value)
        result.append(packed_value)
        count += 1

result_str = ''.join(result)
noise_output.writeframes(result_str)

noise_output.close()

I found the original here. The original just makes a constant tone. Runs fine with Python 3. I would love to see a decoder for this; but I don't know enough about calculating frequencies.


texts: Passing variable to BackgroundWorker and use the same value later

texts:
I create multiple BackgroundWorker within a for-loop and each of them needs to know a special value. To simplify, it is just i in this example. When the BackgroundWorker is finished, I need to read that i again. I thought of subclassing BackgroundWorker and creating a class MyBW for that purpose which is able to store the i as value.

My example below works, but I am interested, if this is the best way to do this?

Edit: I have to add, that the variable I need to pass is a simple String, not a large object.

Fully working minimal example

using System;
using System.Text;

namespace MultiThreadTest
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                MyBW bw = new MyBW();
                bw.value = i;
                bw.WorkerReportsProgress = false;
                bw.DoWork += delegate(object sender, System.ComponentModel.DoWorkEventArgs eargs)
                {
                    Console.WriteLine(String.Format("Thread {0} started", bw.value));
                    System.Threading.Thread.Sleep(bw.value * 1000);
                };
                bw.RunWorkerCompleted += delegate(object sender, System.ComponentModel.RunWorkerCompletedEventArgs eargs)
                {
                    Console.WriteLine(String.Format("Thread {0} finished", bw.value));
                };

                bw.RunWorkerAsync();
            }

            // Only as a run loop that I can see the output.
            while (true)
            {
                System.Threading.Thread.Sleep(1000);
                Console.WriteLine("Sleeping...");
            }
        }
    }

    class MyBW : System.ComponentModel.BackgroundWorker
    {
        /// <summary>
        /// Here I store the value.
        /// </summary>
        public int value;
    }
}


texts: Array alive/dead entity "refresh" algorithm

texts:
I have an Entity class that can be either dead or alive.

I store entities contiguously in a resizable array. During an update(), some alive entities can become dead, and some new entities can be added at the end of the array.

The range [0 .. size) contains all non-newly-created entities.

The range [size .. sizeNext) contains all newly-created entities (guaranteed to be alive).

After update(), I call refresh(). This function does:

Swap around entities making sure that all alive entities are stored contiguously at the beginning of the array (and that all dead entities are stored contiguously at the end of the array).
Deinitialize all dead entities.
Update size and sizeNext.

Basically, the algorithm uses two iterators:

iD moves from left to right, looking for dead entities.
iA moves from right to left, looking for alive entities.

When iD and iA find an entity, the entities are swapped and the iterators advance.

Here's a quick drawing of the algorithm:

And here's the current code:

void refresh()
{
    // `sizeNext` is unsigned - copy it as a signed value
    // to store its initial value and compare it to integers.
    const int intSizeNext(sizeNext);

    // `iD` walks from left to right, looking for dead entities.
    // `iA` walks from right to left, looking for alive entities.
    int iD{0}, iA{intSizeNext - 1};

    do
    {
        // Find dead item from left
        for(; true; ++iD)
        {
            // No more dead items
            if(iD > iA) goto finishRefresh;

            if(isDeadAt(iD)) break;
        }

        // Find alive item from right
        for(; true; --iA)
        {
            // No more alive items
            if(iA <= iD) goto finishRefresh;

            if(isAliveAt(iA)) break;
        }

        assert(isDeadAt(iD) && isAliveAt(iA));
        std::swap(items[iD], items[iA]);
        assert(isAliveAt(iD) && isDeadAt(iA));

        // Advance both iterators
        ++iD; --iA;
    }
    while(true);

    finishRefresh:
    for(iA = iA - 1; iA >= 0; --iA)
    {
        assert(isAliveAt(iA));
    }

    msize = sizeNext = iD;

    for(; iD < intSizeNext; ++iD)
    {
        assert(isDeadAt(iD));
        deinitAt(iD);
    }
}

Can the code be improved/optimized?
Can the goto instructions be avoided?
Is there a more efficient algorithm that achieves the same results?

Full code is here.


texts: JavaScript and RxJS Password Strength Indicator

texts:
This is my first time using RxJS (or any observable library). It seems to work okay but I'm not sure about best practices.

The thing that I am most unsure about is subscribing to the observable multiple times. I couldn't decide if it would be better to subscribe to it once with one big function, or to use many smaller subscribers.

CodePen Demo

Markup

  Password

    <input id="password" class="input" type="password" />

  Password Strength
  <progress id="passwordStrength" class="progress is-danger" value="0" max="5" />

Script

const { fromEvent } = rxjs
const { map, filter } = rxjs.operators

document.addEventListener('DOMContentLoaded', () => {
  const passwordInput = document.getElementById('password')
  const passwordHelp = document.getElementById('passwordHelp')
  const passwordStrength = document.getElementById('passwordStrength')

  const passwordChanged$ = fromEvent(passwordInput, 'input')
    .pipe(
      map(x => x.target.value),
      map(zxcvbn)
    )

  passwordChanged$
    .pipe(map(password => password.score > 2 ? 'success' : 'danger'))
    .subscribe(state => {
      passwordInput.className = `input is-${state}`
      passwordStrength.className = `progress is-${state}`
    })

  passwordChanged$
    .subscribe(password => { passwordHelp.innerHTML = password.feedback.warning })

  passwordChanged$
    .subscribe(password => { passwordStrength.setAttribute('value', password.score + 1) })
})


texts:
I wrote a simple program to perform g.c.d and l.c.m., trying to follow the Linux kernel coding style. I know C for about one year, but I'm still a beginner.

Example:

user@compuer:~/projects/tmp$ ./tmp 21 45
G.C.D: 3
l.c.m: 315

Code:

#include <stdlib.h>
#include <stdio.h>

/*
 * It returns the greatest common divisor between two numbers. The numbers
 * must not be negative (undefined behaviour).
 */
int gcd(int a, int b);

/*
 * It returns the least common multiple. The numbers must not be negative
 * (undefined behaviour).
 */
int lcm(int a, int b);

int main(int argc, char *argv[])
{
        int retval = -1, a, b;

        if (argc != 3) {
                fprintf(stderr, "Error: missing or too many arguments\n");
                goto err_exit;
        }

        a = strtol(argv[1], NULL, 0);
        b = strtol(argv[2], NULL, 0);

        if (a < 0 || b < 0) {
                fprintf(stderr, "Error: numbers must be postive\n");
                goto err_exit;
        }

        if (!a || !b)
                printf("Warning: one or both numbers are 0.\n");

        printf("G.C.D: %d\nl.c.m: %d\n", gcd(a, b), lcm(a, b));

        retval = 0;

        err_exit:
                return retval;
}

int gcd(int a, int b)
{
        int retval = b, r = a;

        if (!a)
                goto exit;

        // Euclidean alrgorithm.
        do {
                a = b;
                b = r;

                r = a % b;
        } while (r);

        retval = b;

        exit:
                return retval;
}

int lcm(int a, int b)
{
        int retval = 0;

        if (a && b)
                retval = a / gcd(a, b) * b;

        return retval;
}

Makefile:

.PHONY = clean all

PROGNAME = tmp

SHELL = /bin/sh

CC ?= gcc

CFLAGS = -Wall -Wextra

all : main.o
    $(CC) -o $(PROGNAME) $^

clean :
    $(RM) *.o $(PROGNAME)


texts:
The following code is an async beginner exploration into asynchronous file downloads, to try and improve the download time of files from a specific website.

Tasks:
The tasks are as follows:

Visit https://digital.nhs.uk/data-and-information/publications/statistical/mental-health-services-monthly-statistics

Extract the latest publication link. It is the top link under Latest Statistics and is the first match returned by css selector .cta__button.

N.B. Each month this link updates so the next monthly publication e.g. 8 Apr 2021 the link will update to that associated with Mental Health Services Monthly Statistics Performance January, Provisional February 2021.

Visit the extracted link: https://digital.nhs.uk/data-and-information/publications/statistical/mental-health-services-monthly-statistics/performance-december-2020-provisional-january-2021 and, from there, extract the download links for all the files listed under Resources; currently 17 files.

Finally, download all those files, using the retrieved urls, and save them to the location specified by folder variable.

Set-up:
Python 3.9.0 64-bit Windows 10

Request:
I would appreciate any suggested improvements to this code e.g. should I have re-factored the co-routine fetch_download_links into two co-routines, each with a ClientSession, where one co-routine gets the initial link to where to get the resources, and the second co-routine to retrieve the actual resource links?

mhsmsAsynDownloads.py
import time
import os
from bs4 import BeautifulSoup as bs
import aiohttp
import aiofiles
import asyncio
import urllib

async def fetch_download_links(url:str) -> list:
    async with aiohttp.ClientSession() as session:
        r = await session.get(url, ssl = False)
        html = await r.text()
        soup = bs(html, 'lxml')
        link = 'https://digital.nhs.uk' + soup.select_one('.cta__button')['href']
        r = await session.get(link, ssl = False)
        html = await r.text()
        soup = bs(html, 'lxml')
        files = [i['href'] for i in soup.select('.attachment a')]

        return files

async def place_file(source: str) -> None:
    async with aiohttp.ClientSession() as session:
        file_name = source.split('/')[-1]
        file_name = urllib.parse.unquote(file_name)
        r = await session.get(source, ssl = False)
        content = await r.read()

    async with aiofiles.open(folder + file_name, 'wb') as f:
        await f.write(content)

async def main():
    tasks = []
    urls = await fetch_download_links('https://digital.nhs.uk/data-and-information/publications/statistical/mental-health-services-monthly-statistics')

    for url in urls:

        tasks.append(place_file(url))

    await asyncio.gather(*tasks)

folder = 'C:/Users/<User>/OneDrive/Desktop/testing/'

if __name__ == '__main__':

    t1 = time.perf_counter()
    print("process started...")
    asyncio.get_event_loop().run_until_complete(main())
    os.startfile(folder[:-1])
    t2 = time.perf_counter()
    print(f'Completed in {t2-t1} seconds.')

References/Notes:

I wrote this after watching an async tutorial on YouTube by Andrei Dumitrescu.
The example above is my own
https://docs.aiohttp.org/en/v0.20.0/client.html
https://docs.aiohttp.org/en/stable/client_advanced.html
Data is publicly available


texts:
I have some code that is helping to protect some online surveys. The surveys have an incentive in the form of an Amazon voucher or cash (which is manually/semi-automatically distributed post-survey) so as you can imagine, we get a lot of people attempting to get multiple vouchers, or undesirable respondents mainly from China.

Of course the main way to prevent this, is to send out unique links to a set of pre-recruited people, however this isn't always an option and hence the need for some kind of protection.

Here is the code, I've removed 2 SQL insert queries to reduce the size of this post:

$countryCode = sanitise($_SERVER["HTTP_CF_IPCOUNTRY"]);
$allowedCountries = getAllowedCountries($projectID); // array('GB', 'US', 'SE');

if(in_array($countryCode, $allowedCountries)) {

    // Count records with matching ip for this project, >=1 TRUE, 0 FALSE
    $isBlocked = checkForBlockedIP($projectID, $ip);

    if($isBlocked == TRUE) {

        header("Location: error.php?blocked");

    } else {

        // Count records with matching ip for this project, >=1 TRUE, 0 FALSE
        $isDuplicate = checkForDuplicateResponse($projectID, $ip);

        if ($isDuplicate == TRUE) {

            //<Removed>
            // Store identifying data into dup_attempts table
            // and block ip from further attempts

            header("Location: error.php?duplicate");

        } else {

            // Create redirect link and send user to it

            $redirectLink = $projectLink . $userID;
            header("refresh:3; url=" . $redirectLink . "");

        }

    }

}

I'm posting this here, because I'm not a professional developer and I don't know if I'm taking the right approach here. Perhaps my approach as a whole is wrong.

I'm allowing only certain countries to participate, checking for a duplicate IP (per project) and if one is found, then I'm storing it in a table for duplicate attempts and adding the IP to a blacklist for that project.


texts:
This is a simple Python program I wrote.  I hope some one could help me optimize this program. If you found any bad habits, please tell me.

#!/usr/bin/python

import urllib2

def GetURLs(srcURL=""):

    if srcURL == "":
        return -1

    Content = urllib2.urlopen(srcURL, None, 6)
    oneLine = Content.readline()
    while oneLine:
        print oneLine
        oneLine = Content.readline()
    Content.close()
    return 0

GetURLs("http://www.baidu.com")


texts: Splitting a string basing myself on categories

texts:
I was thinking about splitting a string based on certain categories, for example alphabetic and numerical, lower and upper case, and even the 3 lines of the keyboard. I wrote a generic function for this but it seems unreadable, so I ask you for better modularization and improvements to readability.

import doctest

def split_on_changes(string, cats):
    """
    Given an input list and some categories,
    splits the list whenever the category changes.
    Also splits if the next char is in no categories.

    >>> split_on_changes("010010110", ["0", "1"])
    ['0', '1', '00', '1', '0', '11', '0']
    >>> split_on_changes("this is an alaskian example", ["qwertyuiop", "asdfghjkl", "zxcvbnm "])
    ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', 'n ', 'alask', 'i', 'a', 'n ', 'e', 'x', 'a', 'm', 'p', 'l', 'e']
    >>> split_on_changes("MiXeD CASing ahahah", ["qwertyuiopasdfghjklzxcvbnm", "qwertyuiopasdfghjklzxcvbnm".upper()])
    ['M', 'i', 'X', 'e', 'D', ' ', 'CAS', 'ing', ' ', 'ahahah']
    """
    def same_cat(a,b):
        for cat in cats:
            if a in cat and b in cat: return True
    return ''.join([x + '·' if not same_cat(x,string[i+1]) else x
                            for i,x in enumerate(string[:-1])] + list(string[-1])).split('·')

if __name__ == "__main__":
    doctest.testmod()


texts: Hide / Show panels depending of value of a dropdown

texts:
According to the value of a dropdown menu I have to show/hide two panels.
For option 'derive' and 'reject' I should show the comment panel, and just for the 'derive' panel I should also show a derivation panel. There are other

This works, but how could I refactor the code to make it shorter and more efficient without losing clarity?

 $("#formTabs").on( "change", "select.actions",function(){

        var parentContainer = $(this).closest("fieldset");

        if(this.value == "reject" || this.value == "derive"){
            parentContainer.find(".commentPanel").show();
        }
        // other 3 options where the panel should not show up.
        else {
            parentContainer.find(".commentPanel").hide();
        }

        // Just for the derive option, a derivation panel must be shown.
        if(this.value == "derive"){
            parentContainer.find(".derivationPanel").show();
        } else {
            parentContainer.find(".derivationPanel").hide();
        }
    });


texts: Optimising iteration and substitution over large dataset

texts:
I have the following code:

import pandas as pd
import numpy as np
import itertools
from pprint import pprint

# Importing the data
df=pd.read_csv('./GPr.csv', sep=',',header=None)
data=df.values
res = np.array([[i for i in row if i == i] for row in data.tolist()], dtype=object)

# This function will make the subsets of a list
def subsets(m,n):
    z = []
    for i in m:
        z.append(list(itertools.combinations(i, n)))
    return(z)

# Make the subsets of size 2
l=subsets(res,2)
l=[val for sublist in l for val in sublist]
Pairs=list(dict.fromkeys(l))

# Modify the pairs:
mod=[':'.join(x) for x in Pairs]

# Define new lists
t0=res.tolist()
t0=map(tuple,t0)
t1=Pairs
t2=mod

# Make substitions
result = []
for v1, v2 in zip(t1, t2):
    out = []
    for i in t0:
        common = set(v1).intersection(i)
        if set(v1) == common:
            out.append(tuple(list(set(i) - common) + [v2]))
        else:
            out.append(tuple(i))
    result.append(out)

pprint(result, width=200)

# Delete duplicates
d = {tuple(x): x for x in result}
remain= list(d.values())

What it does is as follows: First, we import the csv file we want to work with in here. You can see that it is a list of elements, for each element we find the subsets of size two. We then write a modification to the subsets and call it mod. What it does is to take say ('a','b') and convert it to 'a:b'. We then, for each pair, go through the original data and where ever we find the pairs we substitute them. Finally we delete all the duplicates as it is given.

The code works fine for small set of data. Yet the problem is that the file I have, has 30082 pairs where for each the list of ~49000 list should be scanned and pairs being replaced. I run this in Jupyter and after some time the Kernel dies. I wonder how one can optimise this?


texts: Detail view, edit field: create input, buttons

texts:
I have a detail view for my object. There is only one field available for editing. When I click on the Edit button I want to hide text for field and show input with the OK and Cancel button.

// create kendo buttons
$('#editGrnz').kendoButton({
    icon: "k-icon k-i-pencil",
});

$('.rt-field-cancel-button').kendoButton({
    icon: "k-icon k-i-cancel",
});

$('.rt-field-ok-button').kendoButton({
    icon: "k-icon k-i-tick",
});

$(document).on('click', '#editGrnz', function(e) {
    var $editButton = $(this),
        $parentContainer = $(this).parent(),
        $confirmEditButton = $parentContainer.find('.rt-field-ok-button'),
        $cancelEditButton = $parentContainer.find('.rt-field-cancel-button'),
        $editInput = $parentContainer.find('.rt-field-edit-input'),
        $textContainer = $parentContainer.parent().find('.rt-detail-field');

    $editButton.hide();
    $textContainer.hide();
    $confirmEditButton.show();
    $cancelEditButton.show();
    $editInput.show();
});

$(document).on('click', '.rt-field-ok-button', function(e) {
    var $confirmEditButton = $(this),
        $parentContainer = $(this).parent(),
        $cancelEditButton = $parentContainer.find('.rt-field-cancel-button'),
        $editButton = $parentContainer.find('.rt-field-edit-button'),
        $editInput = $parentContainer.find('.rt-field-edit-input'),
        $textContainer = $parentContainer.parent().find('.rt-detail-field'),
        id = $('.rt-content > #trafficId').val(),
        newTransportNumber = $editInput.val(),
        fixationDate = $('.rt-content > #fixationDate').val();

    //ajax call to save address

    $editButton.show();
    $textContainer.html(newTransportNumber);
    $textContainer.parent().removeClass('text-muted');
    $textContainer.show();
    $confirmEditButton.hide();
    $cancelEditButton.hide();
    $editInput.hide();

});

$(document).on('click', '.rt-field-cancel-button', function(e) {
    var $cancelEditButton = $(this),
        $parentContainer = $(this).parent(),
        $confirmEditButton = $parentContainer.find('.rt-field-ok-button'),
        $editButton = $parentContainer.find('.rt-field-edit-button'),
        $textContainer = $parentContainer.parent().find('.rt-detail-field'),
        $editInput = $parentContainer.find('.rt-field-edit-input');

    $editButton.show();
    $textContainer.show();
    $confirmEditButton.hide();
    $cancelEditButton.hide();
    $editInput.hide();
});

This code is located in my view file. Now I have another view when will be the same logic. I don't want to copy this code. How to refactor it? I use require.js and may create a module for this functionality.

This is the working demo


texts:
The challenge was to create a function which performs an in order traversal without using recursion. What I came up with was to use a stack and some clever popping and pushing. I was wondering if there was any way to improve the following solution. Specifically a better way to implement my if(s.empty()) break; line.

vector<int> inorderTraversal(TreeNode* root) {
        stack<TreeNode*> s;
        vector<int> ans;
        if(root == nullptr) return ans;
        s.push(root);
        while(!s.empty()){
            TreeNode* x = s.top();
            s.pop();
            if(x != nullptr && (x -> right != nullptr || x -> left != nullptr)){
                s.push(x -> right);
                s.push(x);
                s.push(x -> left);
            }else{ //leaf node
                if(x != nullptr)
                    ans.push_back(x -> val);

                if(s.empty()) break;

                if(s.top() != nullptr)
                    ans.push_back(s.top() -> val);
                s.pop();
            }
        }
        return ans;
    }


texts: Cross domain fetch switching in prod vs dev

texts:
I'm beginning a redesign of the front end of my Flask app which currently generates Jinja2 template-based html pages. I am trying to develop a new front end in React, but I want the current front end to continue to exist. Much like Reddit, I want my current front end to exist at old.anno.wiki and the new front end to exist at anno.wiki, but I would like to continue to use all the same backend code.
There are several ways to achieve this and the idea that I most like is that I move the entire app to old.anno.wiki and write a React app at anno.wiki that queries old.anno.wiki's to-be-developed api. This runs into problems with CORS, and, more importantly, with issues of development vs production fetching.
(note: right now I'm temporarily using new.anno.wiki for the new react front end while I continue to use anno.wiki for the old one as I develop the new).
As I develop, while in dev I'd like to query the Flask api running in docker locally, in production I'd like to query the api currently at anno.wiki/api. To do this I set the React proxy to "http://localhost:5000" and wrote a helper function to get the domain to query in my code:
const URL = 'https://anno.wiki';

const getHome = () => {
  const url = process.env.NODE_ENV === 'development' ? '' : URL;
  return url
}

I then, in all my fetches, query this and use it to precede whatever route I query, like so:
  const [currentTime, setCurrentTime] = useState(0);
  const url = getHome();

  useEffect(() => {
    fetch(url + '/api/time').then(res => res.json()).then(data => {
      setCurrentTime(data.time);
    });
  }, [url]);

I am concerned that this might not be the way to do this. Is this secure? I imagine that by concatenating with + it is less efficient than using template literals, but that is not my concern. My concern is that this might have hidden consequences that I am unaware of, either security implications or efficiency problems.
Any advice would be very much appreciated.


texts: C - Improving (really) big number addition

texts:
I was lucky enough to stumble into this task during a job interview.  I was gently guided to use string reversals and a few other things to speed up my process.  I kept thinking that I wouldn't have done it the way I was coached.   It bothered me enough that I went home and coded up my version.

How could I improve this code?

* EDIT * added a size_t for carry.  Reduced the number of calles of strlen().

Rules:

Program must be in C
Can't use atoi, and only basic types
Must be able to add arbitrarily large numbers
Output must be a string

Example usage:

addbig 12345678901234567891234567891234567890123456789123456789  9876543210987654321098765432198765432109876543210987654321

Here's the code I came up with:

#include <stdio.h>   // printf
#include <stdlib.h>  // malloc
#include <string.h>  // strlen

char * addStrings(char* string1, char* string2) {
  char *maxString = string1;
  char *minString = string2;

  // Override our larger if we were wrong.
  if (strlen(string1) < strlen(string2)) {
    maxString = string2;
    minString = string1;
  }

  int maxSize =  strlen(maxString);

  // Allocate enough storage to include our carry and the null char at the end.
  char * myResult = malloc(maxSize + 2);

  // Null terminate the string
  myResult[maxSize + 1] = 0;

  size_t carry = 0;
  int mindex = strlen(minString) - 1;

  char x = 0;

  // One loop.  Avoid -std=c99 flag
  int i = maxSize - 1;
  for (; i >= 0; i--) {
    // Default our char
    x = maxString[i] - '0';
    // We still have something left to add.
    if (mindex >= 0){
      x = x + (minString[mindex] - '0');
      mindex--;
    }

    if (carry) x++;

    if (x >= 10) {
      x -= 10;
      carry = 1;
    } else {
      carry = 0;
    }

    myResult[i + 1] = x + '0';
  }
  // Take care of any leftover carry.
  if (carry) myResult[0] = '1';

  return myResult;
}  // END addStrings()

int main(int argc, char **argv) {
  if (argc < 2) {
    printf("Usage: %s num1 num2\n", argv[0]);
    printf("Utility for big numbers.");
    printf("Adds num1 to num2, for any length of numbers.\n");
    return 1;
  }

  char * result = addStrings(argv[1], argv[2]);

  // Removing the initial space allocated by storage if we didn't overflow
  printf("%s\n", (result[0] == ' ') ? result + 1 : result);

  if (result) {
    free(result);
    return 0;
  }

  // Returned an error state, memory not freed.
  return -1;
}


texts:
For self-study homework I made a Java program that takes user input, creates people as objects, and says "Happy Birthday" to each person.

I am just wondering what mistakes I made here or how it could have been better.

PERSON CLASS

public class PeopleObjects{
    // For practice, make the people objects rather than just a list of names.

    private String name;
    private String birthDay;

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public void setBirthDay(String myBirth){
        birthDay = myBirth;
    }

    public String getBirthDay(){
        return birthDay;
    }

}

MAIN

import java.util.Scanner;
import java.util.ArrayList;

public class PeopleObjectsTestDrive{
    public static void main(String [] args){

        ArrayList<PeopleObjects> listOfPeopleObjects = new ArrayList<PeopleObjects>();
        Scanner input = new Scanner(System.in);

        int userChoice = 0;

        System.out.println("Enter any number other than 1 to start program."+"\n");

            while ((userChoice = input.nextInt()) != 1){

                PeopleObjects people = new PeopleObjects();

                System.out.println("\n###What is the name of the person?###\n");
                input.nextLine();//for some reason we have to use this twice to avoid bug
                people.setName(input.nextLine());

                System.out.println("\n###What is their birthday?###\n");
                people.setBirthDay(input.nextLine());
                listOfPeopleObjects.add(people);

                System.out.println("\nDo you want to quit and see list? Enter 1 for yes and 0 for no\n");
            }

            System.out.println("\n\n\n\n");

            for(int i=0; i < listOfPeopleObjects.size(); i++){

                if(listOfPeopleObjects.get(i).getName().equals("Joe")){
                    System.out.println("Happy Birthday Joe! You are special! Your birthday is on "+listOfPeopleObjects.get(i).getBirthDay()+" \n");
                }else if(i%2 == 0){
                    System.out.println("Happy Birthday to "+listOfPeopleObjects.get(i).getName()+".\n");
                }else{
                    System.out.println("Happy Birthday to "+listOfPeopleObjects.get(i).getName()+" too!!!\n");

                }//end if else
            }//end for
    }
}


texts:
I know that there may be better ways of writing this do you think that this code is written well enough to be used in a real world application?

    var pow = function ( base, power ) {
    var result = 1;
    if ( power < 0 ) {
        return ( 1 / pow( base, -(power)) );
    }
    for ( var i = 1; i <= power; i++ ) {
        result = result * base;
    }
    return result;
};


texts: Methods creating transform functionality on Collections

texts:
I have written a few simple-to-be-used methods in Java 8, and am wondering what could be improved upon those:

public static <E, R, C extends Collection<? extends R>> C transform(final Collection<E> collection, final Function<? super E, ? extends R> mapper) {
    try {
        Objects.requireNonNull(collection);
        Objects.requireNonNull(mapper);
        Class<? extends Collection> clazz = collection.getClass();
        @SuppressWarnings("unchecked") Collection<Object> returnCollection = clazz.newInstance();
        collection.stream().map(mapper).forEach(returnCollection::add);
        @SuppressWarnings("unchecked") C genericReturnCollection = (C)returnCollection;
        return genericReturnCollection;
    } catch (InstantiationException | IllegalAccessException ex) {
        throw new RuntimeException(ex);
    }
}

public static <E, R, C extends Collection<R>> C transform(final Collection<E> collection, final Function<? super E, ? extends R> mapper, final Supplier<C> collectionSupplier) {
    Objects.requireNonNull(collection);
    Objects.requireNonNull(mapper);
    Objects.requireNonNull(collectionSupplier);
    return collection.stream().map(mapper).collect(Collectors.toCollection(collectionSupplier));
}

Their purpose is to provide similar functionality as the List.replaceAll() method, but then allowing that the mapped type differs from the original type. Hence it is something that should be in a static factory class, as it will always need to create a new collection.

Some example code:

LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(5);
linkedList.add(10);
linkedList.add(15);
LinkedList<String> resultList = transform(linkedList, i -> (i + 1) + "-" + i);

and

LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(5);
linkedList.add(10);
linkedList.add(15);
LinkedList<String> resultList = transform(linkedList, i -> (i + 1) + "-" + i, LinkedList::new);

Both have as output:

  6-5
  11-10
  16-15

I am aware that the transform with a Supplier<C> as argument is obviously much nicer, however for convienience the single-argument version with only a function is much better.


texts: Loop months between a time span yyyy-mm and yyyy-mm

texts:
I'm trying to come up with a more elegant solution for a loop in months that I wrote long time ago in C# 1.1

I use a helper class Month but I'd prefer to get rid of it and make the code shorter and more readable.

I receive a start period in format yyyy-mm and end period yyyy-mm and I need to execute something for every month between those 2 periods.

public void LoopMonths(string startM, string endM)
{
        //startM = "2015-02";
        //endM = "2018-11";

        int startYear = int.Parse(startM.Split('-')[0]);
        int startMonth = int.Parse(startM.Split('-')[1]);
        int endYear = int.Parse(endM.Split('-')[0]);
        int endMonth = int.Parse(endM.Split('-')[1]);

        Month month = new Month(startYear, startMonth);
        Month monthEnd = new Month(endYear, endMonth);

        while (month <= monthEnd)
        {
            // do something ...
            month = Month.NextMonth(month);
        }
}

public class Month
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

    public Month(int year, int month)
    {
        StartDate = new DateTime(year, month, 1);
        EndDate = new DateTime(year, month, DateTime.DaysInMonth(year, month));
    }

    public static Month NextMonth(Month month)
    {
        DateTime next = month.StartDate.AddMonths(1);
        return new Month(next.Year, next.Month);
    }

    public static bool operator <=(Month month1, Month month2)
    {
        return month1.StartDate <= month2.StartDate;
    }

    public static bool operator >=(Month month1, Month month2)
    {
        return month1.StartDate >= month2.StartDate;
    }
}


texts: CS50 pset-1 itsa Mario - make a half-pyramid using parameters from user input

texts:
I'm taking Harvard's introduction to computer science (CS50) course online, and I've written a program that satisfies a coding challenge but I don't understand what I did or how I can improve it. I'm a very green programmer.

The challenge is to get an int from the user between 0 and 23 and use that to set the line height of a half-pyramid drawn in the terminal using hashes, ala the ramp at the ends of the levels in Super Mario Bros:

   ##
  ###
 ####
#####

After about 6 hours of banging my head against the wall I came up with the following:

#include <cs50.h>
#include <stdio.h>

int main()
{
    int height;

    printf("How high do you want your half-pyramid?\n");
    height = GetInt();

     //verify that height is an int between 0 and 23

    while (height > 23 || height < 0)

        {
            printf("Invalid entry:\nChoose a number between 0 and 23\n");
            height = GetInt();
        }

    // draw the pyramid

    for (int line = 0; line < height; line++)
      {
         // draw spaces
        for (int space = line + 2; space < height + 1; space++)
         {
         printf(" ");
         }

         // draw hashes
        for (int hash = line + height + 1; height < hash + 1; hash--)
        {
         printf("#");
        }
        printf("\n");
      }

    return 0;
}

I understand the part that I've commented as "verify that height is an int between 0 and 23," but everything in the "draw the pyramid" section was arrived at by brute force. Just making one thing that kind of looked like it worked and then tweaking it over and over again until it did what I needed it to do. Maybe this is how everyone codes, but I hope not.

Can anyone give me some insight in fairly plain language about what the code here is doing, some ideas about how it might be improved, or just some other ways to go about it?


texts: Inner product of random floats written to file

texts:
My goals are to make this code:

faster
more idiomatic C++

What the code does:

take an integer command-line argument N
make a vector of N random floating point values
make a matrix of N*N random floating point values
do inner product of vector * matrix
write the resulting vector to a file

Currently compiled with: g++ myFile.cpp -std=c++11 -O3

#include <vector>
#include <fstream>

const std::string outputName = "output/coutput.txt"; // the name of the file this program makes

std::ostream& operator<< (std::ostream& os, const std::vector<double>& v)
{ // pretty-print a vector of doubles using operator<<
  for (auto& i : v)
    i == *v.begin() ? os << i : os << " " << i;
  return os;
}

double genRand(void)
{
  return rand() / static_cast<double>(RAND_MAX);
}

int main(int argc, char* argv[])
{
  // file i/o
  std::ofstream result;
  result.open(outputName, std::ios::out);

  srand(1);
  long elems = std::atol(argv[1]); // command line param
  std::vector<double> m(elems * elems); // (elems * elems); // actually this is a vector of length (N*N)
  std::vector<double> a(elems);
  std::vector<double> r(elems, 0); // to store the result

  for (auto i = 0; i < elems; i++) // generate random vector
    a[i] = genRand();

  for (auto i = 0; i < elems * elems; i++) // generate random matrix
    m[i] = genRand();

  for (auto i = 0; i < m.size(); i++) {
    auto idx = i / a.size();
    r[idx] += a[idx] * m[i];
  }

  result << r << std::endl; // print results
  result.close();
}


texts:
This query gets data, but for 116819 rows I need to wait 2:19 minutes. Getting the same data from the table takes 2-3 seconds, but I need some rows from the view (that are matching my data from table) in my query. How can I make it faster? The database that I work on is created properly.

select aa.*, b.quantity, b.price, case when b.itemNr is null then 'status' else 'status1' end as Status
    from(
        Select a.*, b.quantity, b.price, b.itemNr
        From table a
        left join view b
        on a.itemNR = b.itemNr and a.itemLine=b.itemLine) aa
    where aa.itemType = 'a type'
    group by ....
    order by ...

If I remove group by and order by, the query takes 2:10 minutes, so I reduce it only by 9 seconds.


texts:
It was a part of my coding challenge and the last one, but I failed because it failed to yield a result in two seconds for some of sample inputs (out of six samples, three passed but three failed for not meeting the time constraint).

Basically, you are supposed to find the maximum deviation from given number of consecutive integers. There are two inputs; the first argument is an array of integers and the second argument is the number of consecutive integers. And you print the maximum deviation. For example, if you have [10, 1, 5, 2, 6, 3] and 3 as arguments, the output should be 9 since [10, 1, 5] would yield the maximum deviation of 9 (10-1).

Can this be refactored to be faster?

def find_deviation(integers, range)
  max = 0
  (0..integers.size-range).each do |n|
    array = integers.slice(n, range)
    diff = array.max - array.min
    max = diff if diff > max
  end
  puts max
end


texts: C++ Template-Based ArrayList Implementation

texts:
As part of my learning C++, I have created an ArrayList class. It shares some of its interface with the Java ArrayList, but it by no means implements anywhere close to the full set of functions an ArrayList or vector supports.

Here is my ArrayList.h:

#ifndef ARRAYLIST_ARRAYLIST_H
#define ARRAYLIST_ARRAYLIST_H

#include <initializer_list>

template<typename T>
class ArrayList{
public:
    //lifecycle
    ArrayList() : m_array(new T[0]) {}
    ArrayList(std::initializer_list<T> it);
    ~ArrayList() { delete [] m_array; }

    //copy control
    ArrayList(const ArrayList<T> &arraylist) { *this = arraylist; }
    ArrayList(const ArrayList<T> &&arraylist) { *this = arraylist; }
    ArrayList& operator=(const ArrayList<T> &arrayList);
    ArrayList& operator=(ArrayList<T> &&arrayList);

    //element access
    T& operator[](unsigned i) { return m_array[i]; }
    void add(const T &t) { resizeIfFull(); m_array[m_frontendLength++] = t; }
    void add(const T &&t) { resizeIfFull(); m_array[m_frontendLength++] = std::move(t); }

    //utilities
    unsigned length() { return m_frontendLength; }

private:
    T *m_array = nullptr;
    unsigned m_backendLength, m_frontendLength;

    void resizeIfFull();
};

#include "ArrayList.tpp"

#endif //ARRAYLIST_ARRAYLIST_H

Here is my ArrayList.tpp:

#ifndef ARRAYLIST_TPP
#define ARRAYLIST_TPP

#include "ArrayList.h"

#include <utility>

template<typename T>
ArrayList<T>::ArrayList(std::initializer_list<T> ls){
    m_array = new T[ls.size()];

    m_backendLength = ls.size();
    m_frontendLength = ls.size();

    unsigned i = 0;
    for(auto it=ls.begin();it!=ls.end();++it){
        m_array[i++] = *it;
    }
}

template<typename T>
ArrayList<T>& ArrayList<T>::operator=(const ArrayList<T> &arrayList){
  m_backendLength = arrayList.m_backendLength;
  m_frontendLength = arrayList.m_frontendLength;

  delete [] m_array;

  m_array = new T[m_backendLength];

  for(unsigned i=0;i<m_frontendLength;++i){
    m_array[i] = arrayList.m_array[i];
  }

  return *this;
}

template<typename T>
ArrayList<T>& ArrayList<T>::operator=(ArrayList<T> &&arrayList){
    m_backendLength = arrayList.m_backendLength;
    m_frontendLength = arrayList.m_frontendLength;
    m_array = arrayList.m_array;
    arrayList.m_array = nullptr;
}

template<typename T>
void ArrayList<T>::resizeIfFull(){
  if(m_backendLength == m_frontendLength){
    m_backendLength *= 2;
    T *newArray = new T[m_backendLength];

    for(unsigned i=0;i<m_frontendLength;++i){
      newArray[i] = std::move(m_array[i]);
    }

    delete [] m_array;
    m_array = newArray;
  }
}

#endif

I am hoping to get some information on things I did badly, and things I did well. I am particularly interested in: compliance with C++ convention, writing good code with regard to organization (ie. OOP, SOLID, etc.), and efficiency. I know Java much better, and I would like to know if I am bringing Java stuff in here that doesn't belong in C++.


texts:
I'm in very early stages of learning some Java coding. I'm asking for this review because, although the code below works, I'd like to know if it's an ugly way of achieving it.
What I want the code to do is take input from Scanner and reprint it, except if the input is empty, ie, just hit the return key, in which case the Scanner should close and the program end.

import java.util.Scanner;

public class Morse {

static boolean truefalse = true;

public static void main(String[] args) {
    // TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
while (truefalse)
{
String line = input.nextLine();
if (line.equals(""))
truefalse = false;
else
System.out.println(line);
}
input.close();
}

}


texts: Given a random section of text delimited by line breaks, get the first paragraph

texts:
Requirements:

  Given a long section of text, where the only indication that a paragraph has ended is a shorter line, make a guess about the first paragraph. The lines are hardwrapped, and the wrapping is consistent for the entire text.

The code below assumes that a paragraph ends with a line that is shorter than the average of all of the other lines. It also checks to see whether the line is shorter merely because of word wrapping by looking at the word in the next line and seeing whether that would have made the line extend beyond the "maximum" width for the paragraph.

def get_first_paragraph(source_text):
    lines = source_text.splitlines()
    lens = [len(line) for line in lines]
    avglen = sum(lens)/len(lens)
    maxlen = max(lens)
    newlines = []
    for line_idx, line in enumerate(lines):
        newlines.append(line)
        try:
            word_in_next_line = lines[line_idx+1].split()[0]
        except IndexError:
            break # we've reached the last line
        if len(line) < avglen and len(line) + 1 + len(word_in_next_line) < maxlen: # 1 is for space between words
            break
    return '\n'.join(newlines)

Sample #1

Input:

This is a sample paragaraph. It goes on and on for several sentences.
Many OF These Remarkable Sentences are Considerable in Length.
It has a variety of words with different lengths, and there is not a
consistent line length, although it appears to hover
supercalifragilisticexpialidociously around the 70 character mark.
Ideally the code should recognize that one line is much shorter than
the rest, and is shorter not because of a much longer word following
it which has wrapped the line, but because we have reached the end of
a paragraph.
This is the next paragraph, and continues onwards for
more and more sentences.

Output:

This is a sample paragaraph. It goes on and on for several sentences.
Many OF These Remarkable Sentences are Considerable in Length.
It has a variety of words with different lengths, and there is not a
consistent line length, although it appears to hover
supercalifragilisticexpialidociously around the 70 character mark.
Ideally the code should recognize that one line is much shorter than
the rest, and is shorter not because of a much longer word following
it which has wrapped the line, but because we have reached the end of
a paragraph.

Using other sample inputs I see there are a few issues, particularly if the text features a short paragraph or if there is more than one paragraph in the source text (leading to the trailing shorter lines reducing the overall average).


texts: Blackjack Insurance Object that implements Null Object Pattern via __new__

texts:
This example of a blackjack insurance object is typical of how I find myself writing classes in Python. I particularly wanted some feedback on my use __new__ to implement the Null Object Pattern and whether this as considered a good approach or not.

# -*- coding: utf-8 -*-
import unittest
from contextlib import redirect_stdout
from io import StringIO

class Insurance:
    class NoInsurance:
        def payout(self, is_dealer_21):
            return 0

    def __new__(cls, player_name, max_bet):
        ans = input("{}, insurance amount? [0-{}] ".format(
                player_name,
                max_bet))
        try:
            bet = min(max_bet, max(0, int(ans)))
        except ValueError:
            bet = 0
        obj = super().__new__(cls) if bet > 0 else cls.NoInsurance()
        obj.bet = bet
        return obj

    def __init__(self, name, max_bet):
        self.name = name
        self.max_bet = max_bet

    def get_payout(self, is_dealer_21):
        return (self.bet*2, "got an insurance payout of") if is_dealer_21 \
          else (-self.bet, "lost insurance amount of")

    def payout(self, is_dealer_21):
        payout, msg = self.get_payout(is_dealer_21)
        return payout

class RedirectStdin:
    def __init__(self, inputs=[]):
        self.inputs = inputs

    def custom_input(self, *args):
        return self.inputs.pop(0)

    def __enter__(self):
        global input
        self.old_input = input
        input = self.custom_input

    def __exit__(self, *args):
        global input
        input = self.old_input

class TestInsurance(unittest.TestCase):
    def test_payouts(self):
        void = StringIO()
        input_list = ["0", "4", "text", "500"]
        results = []
        expected_results = [
                {'False': 0, 'True': 0, 'class': 'NoInsurance'},
                {'False': -4, 'True': 8, 'class': 'Insurance'},
                {'False': 0, 'True': 0, 'class': 'NoInsurance'},
                {'False': -100, 'True': 200, 'class': 'Insurance'}
            ]
        with RedirectStdin(input_list), redirect_stdout(void):
            for _ in range(len(input_list)):
                x = Insurance('', 100)
                results.append({
                        "True": x.payout(True),
                        "False": x.payout(False),
                        "class": x.__class__.__name__
                        })
        for result, expected_result in zip(results, expected_results):
            self.assertEqual(result, expected_result)

def test():
    unittest.main()

def main():
    msg_21 = "Dealer with blackjack    -> your payout is: {}"
    msg_not_21 = "Dealer without blackjack -> your payout is: {}"
    x = Insurance('Player Name', 100)
    print(msg_21.format(x.payout(True)))
    print(msg_not_21.format(x.payout(False)))
    print("The type of the insurance is: {}".format(x.__class__.__name__))

if __name__ == "__main__":
    main()

Sample run:

>>> main()

Player Name, insurance amount? [0-100] 43242
Dealer with blackjack    -> your payout is: 200
Dealer without blackjack -> your payout is: -100
The type of the insurance is: Insurance


texts: Demonstration of ChessBoard Traveling (CoderByte)

texts:
Problem

  Have the function ChessboardTraveling(str) read str which will be a
  string consisting of the location of a space on a standard 8x8 chessboard with no pieces on the board along with another space on the
  chessboard.

  The structure of str will be the following:

  \$(x,y)(a,b)\$ where \$(x, y)\$ represents the position you are
  currently on with \$x\$ and \$y\$ ranging from 1 to 8 and \$(a, b)\$
  represents some other space on the chessboard with \$a\$ and \$b\$
  also ranging from 1 to 8 where \$a > x\$ and \$b > y\$. Your program
  should determine how many ways there are of traveling from \$(x, y)\$
  on the board to \$(a, b)\$ moving only up and to the right.

  Example: if str is \$(1,1)(2, 2)\$ then your program should output 2 because there are only two possible ways to travel from space
  \$(1, 1)\$ on a chessboard to space \$(2, 2)\$ while making only moves
  up and to the right.

Are there any improvements I can make?

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

std::string delete_Punctuation(std::string& str)
{
    std::string noPunctString = "";

    str.insert(str.length()/2," ");

    for (auto character : str)
    {
        if (!ispunct(character))
        {
            noPunctString.push_back(character);
        }
    }

    return str = noPunctString;
}

bool check_If_PointXY_Is_Less_Than_PointAB(std::vector<int> v)
{
     return (v.at(2) > v.at(0) && v.at(3) > v.at(1));
}

long long int find_Factorial(unsigned int n)
{
    if (n == 0)
    {
       return 1;
    }

    return n * find_Factorial(n - 1);
}

int number_Of_Steps(std::string& str)
{
    str = delete_Punctuation( str );

    std::istringstream iss( str );

    std::vector<int> coll((std::istream_iterator<int>( iss )),std::istream_iterator<int>());

    int steps = 0;

    if (check_If_PointXY_Is_Less_Than_PointAB(coll))
    {
        int xDistance = coll.at(2) - coll.at(0);
        int yDistance = coll.at(3) - coll.at(1);

        int totalDistance = xDistance + yDistance;

        //combination formula
        steps = find_Factorial(totalDistance)/(find_Factorial(xDistance) * (find_Factorial(totalDistance - xDistance)));
    }

    return steps;
}


texts:
I'm hoping for suggestions of a concise way to write my list comprehension filter in the first solution.
I would also appreciate insight on the underlying reasons for some performance differences in my solutions for Problem 5 (https://projecteuler.net/problem=5):

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

This first solution takes around 1.5 seconds on my laptop and the other takes 7.5 seconds.
#Project Euler problem 5
import time
start = time.time()
def smallestFactor(start):
#list comprehension filters out numbers not divisible by 11-20
    options = [i for i in range(start, start + 1000000, 20)\
    if i % 20 == 0 and i % 19 == 0 \
    and i % 18 == 0 and i % 17 == 0 \
    and i % 16 == 0 and i % 15 == 0 \
    and i % 14 == 0 and i % 13 == 0 \
    and i % 12 == 0 and i % 11 == 0]
#return if LCM found
    if len(options) > 0:
        print(options[0])
        return options[0]
#recursion with larger numbers if not found
    else:
        smallestFactor(start + 1000000)
smallestFactor(2520)
end = time.time()
print("Speed: " + str(end - start))

My second solution instead uses a function as the list filter. The speed difference may be trivial, but I'm curious about why it takes longer to invoke a function which otherwise performs a similar filtering task as a series of conditionals written directly into the list comprehension.
#Project Euler problem 5
import time
start = time.time()
factors = [i for i in range(20,9,-1)]
def check(num):
#loop 20-11
    for n in factors:
#check modulus, break or return at end of list
        if num % n == 0 and n != factors[len(factors) - 1]:
            continue
        if num % n == 0 and n == factors[len(factors) - 1]:
            return num
        else:
            break
def smallestFactor(start):
#list comprehension filters out numbers not divisible by 11-20
    options = [i for i in range(start, start + 1000000, 20) if check(i) == i]
#return if LCM found
    if len(options) > 0:
        print(options[0])
        return options[0]
#recursion with larger numbers if not found
    else:
        smallestFactor(start + 1000000)
smallestFactor(2520)
end = time.time()
print("Speed: " + str(end - start))


texts:
I'd like to know whether having different variables for the src (source) and dst (destination) of an OpenCV function will have an effect on the processing time.  I have two functions below
that does the same thing.

public static Mat getY(Mat m){
    Mat mMattemp = new Mat();
    Imgproc.cvtColor(m,mMattemp,Imgproc.COLOR_YUV420sp2RGB);
    Imgproc.cvtColor(mMattemp,mMattemp, Imgproc.COLOR_RGB2HSV);
    Core.inRange(mMattemp, new Scalar(20, 100, 100), new Scalar(30, 255, 255), mMattemp);
    return mMattemp;
}

VERSUS

public static Mat getY(Mat m){
    Mat mMattemp_rgb = new Mat();
    Mat mMattemp_hsv = new Mat();
    Mat mMattemp_ir = new Mat();
    Imgproc.cvtColor(m,mMattemp_rgb,Imgproc.COLOR_YUV420sp2RGB);
    Imgproc.cvtColor(mMattemp_rgb,mMattemp_hsv, Imgproc.COLOR_RGB2HSV);
    Core.inRange(mMattemp_hsv, new Scalar(20, 100, 100), new Scalar(30, 255, 255), mMattemp_ir);
    return mMattemp_ir;
}

Which of the two is considered best-practice? What is the advantage of one over the other?


texts: Convert an integer to its Roman numeral equivalent

texts:
I got sent a challenge from a friend;

  You are given a file that contains numbers, one number per line. Convert the numbers from the file into roman numerals.

Test input:
45
65
23
98
123
7754

Expected Output:
XLV
LXV
XXIII
XCVIII
CXXIII
MMMMMMMDCCLIV

I think I've succeeded in doing this successfully, and would like some critque on what I've done so far:

import sys

ROMAN_NUMERAL_TABLE = [
    ("M", 1000), ("CM", 900), ("D", 500),
    ("CD", 400), ("C", 100),  ("XC", 90),
    ("L", 50),   ("XL", 40),  ("X", 10),
    ("IX", 9),   ("V", 5),    ("IV", 4),
    ("I", 1)
]

def convert_to_roman(number):
    """ Convert an integer to Roman
    >>> print(convert_to_roman(45))
    XLV """
    roman_numerals = []
    for numeral, value in ROMAN_NUMERAL_TABLE:
        while value <= number:
            number -= value
            roman_numerals.append(numeral)

    return ''.join(roman_numerals)

if __name__ == '__main__':
    with open(sys.argv[1]) as data:
        for line in data.readlines():
            print("{} to roman numerals: {}".format(line.rstrip(), convert_to_roman(int(line.rstrip()))))

Key points that I would like to focus on (obviously feel free to critique the entire program)

Using the tuples for the list, is this good practice, or would a dict have worked better?
While converting the integers to the roman numerals is there a easier way to do this, right now my program will take a long time, for an integer that is higher than 12345679990 is there a way to speed up the processing for extremely high integers?


texts: Refactoring while-do into tail recursion with F#

texts:
I have a while-do loop nested inside a while-do loop in my program, due to it needing to iterate in two dimensions through an array of arrays, and originally my loop looked like this:

while ( tHeightIndex < tSearchHeight - 1 ) && tContinue do
    while ( tWidthIndex < tSearchWidth - 1 ) && tContinue do
        let tCurrentValue = tLargeArray.[tHeightIndex].[tWidthIndex]
        if tCurrentValue = tFirstSmallPixel then
            tMatch <- ArrayFunctions.SearchSubset tSmallArray tLargeArray ( tHeightIndex, tWidthIndex )
            if tMatch then tContinue <- false
        if tMatch = false && tContinue = true then
            tWidthIndex <- tWidthIndex + 1
    if tMatch = false && tContinue = true then
        tWidthIndex  <- 0                       // Reset to search next row
        tHeightIndex <- tHeightIndex + 1
tMatch, tWidthIndex, tHeightIndex

However, seeing as I'm doing this project entirely to learn better functional programming practices, I refactored that nested loop into two tail-recursive functions. This code passes my unit tests and appears to work correctly, so I would like advice about the style of the code and whether there's better ways I can make the code read clearly.

The relevant part to the original while-do loop is located after the declaration of firstSmallPixel.

module ImageSearch =
    open ImageFunctions

    let SearchBitmap (smallBitmap:Bitmap) (largeBitmap:Bitmap) =
        let smallArray = Transform2D <| LoadBitmapIntoArray smallBitmap
        let largeArray = Transform2D <| LoadBitmapIntoArray largeBitmap
        let searchWidth = largeBitmap.Width - smallBitmap.Width
        let searchHeight = largeBitmap.Height - smallBitmap.Height
        let firstSmallPixel = smallArray.[0].[0]

        let WidthLoop heightIndex =
            let rec WidthLoopRec heightIndex widthIndex =
                let ContinueLoop () = WidthLoopRec heightIndex (widthIndex + 1)
                let currentLargePixel = largeArray.[heightIndex].[widthIndex]
                match ( widthIndex < searchWidth , currentLargePixel = firstSmallPixel ) with
                | ( true , true  ) ->  let foundImage = ArrayFunctions.SearchSubset smallArray largeArray ( heightIndex, widthIndex )
                                       if foundImage then widthIndex , foundImage
                                       else ContinueLoop ()
                | ( true , false ) -> ContinueLoop ()
                | ( false, _     ) -> widthIndex , false
            WidthLoopRec heightIndex 0

        let HeightLoop () =
            let rec HeightLoopRec heightIndex =
                let widthIndex, foundImage = WidthLoop heightIndex
                match ( foundImage, heightIndex < searchHeight ) with
                | ( false , true  ) -> HeightLoopRec ( heightIndex + 1 )
                | ( _     , _     ) -> foundImage , widthIndex , heightIndex
            HeightLoopRec 0

        HeightLoop ()


texts:
I've written a timer to start when the page loads, and to stop when the user clicks a "finished" button:

<br><button id = "finish" onclick = "stopTimer();">Done</button>

My code works fine, but I was just wondering if there's a simpler/easier/faster way to implement a timer in JavaScript.

//Stop timer function
function stopTimer() {
    clearInterval(time);
}

//Start timer function
var secTime = 0,
      minTime = 0,
      hourTime = 0;

var time =  setInterval(function(){
    var maxSec = 59,
        maxMin = 59,
        maxHour = 59;
if(secTime > maxSec){
      minTime++;
      if(minTime > maxMin){
        hourTime++;
        if(hourTime > maxHour){
          hourTime = 0;
          minTime = 0;
          secTime = 0;
        }
        minTime = 0
      }
      secTime = 0;
    }
        var newSec = (secTime.toString().length == 1) ? '0' + secTime : secTime,
            newMin = (minTime.toString().length == 1) ? '0' + minTime : minTime,
            newHour = (hourTime.toString().length == 1) ? '0' + hourTime : hourTime;

        document.getElementById('timer').innerHTML = newHour + ':' + newMin + ':' + newSec;

    secTime++;
}, 1000);