texts: Find the nearest coin to be collected in a game

texts:
I am creating a simple bot that collects coins in-game. The code runs under a game-loop so there are 60 ticks p/s

Here is the function that I use to check for the nearest coin (Game object) to be collected:

public GameObject getNearest(ID objectID) {

    LinkedList<GameObject> object = new LinkedList<GameObject>();
    for (int i = 0; i < handler.object.size(); i++) {
        GameObject temp = handler.object.get(i);
        if (temp.getId() == objectID) {
            object.add(temp);
        }
    }

    if (object.size() == 0)
        return null;

    else {
        GameObject nearest = object.get(0);
        for (int i = 0; i < object.size(); i++) {
            if (getDistance(this, object.get(i)) < getDistance(this, nearest)) {
                nearest = object.get(i);
            }
            object.remove(i);
        }
        return nearest;
    }
}

What this function would do is check for all the game objects, and add all the once that match the parameter in a list. It then will loop through the list and check for the nearest coin to the bot.

Is my function efficient regarding performance, speed, and memory usage? By calling the object.remove after every check, does it help? (If not, please mention why)

Is it okay that it calls the method 60 times p/s or I should limit it to execute once every 20 frames maybe? The thing is that I want it to be collecting the coins safely in the shortest time possible. Is there anything that I should take into consideration or something to improve in my code??


texts: Chaining asynchronous tasks that must run sequentially

texts:
I want to implement an Agent-like object in C#. An Agent wraps some memory location (ideally storing an immutable object) and receives updates to that location. All these updates are performed asynchronously, but sequentially. In other words

  At any point in time, at most one [update submitted to an] Agent is
  being executed.

My current implementation uses the TPL. The Agent keeps a reference to the last update that has been or must be performed, wrapped in a Task. When submitted a new update, you wrap the update in a Task, get a reference to the last Task and replace it, atomically, then invoke ContinueWith on that last Task with this new update Task (everything submitted through a TaskScheduler).

public class Agent<T> where T : class
{
    private T wrappedValue;
    private readonly TaskScheduler scheduler;
    private Task lastTask;

    public Agent (T value, TaskScheduler scheduler)
    {
        this.wrappedValue = value;
        this.scheduler = scheduler;
    }

    public void Send (Action<T> operation)
    {
        Task task = new Task ((action) => ((Action<T>)action) (wrappedValue), operation);
        Task localCurrent;
        do {
            // always append to the end
            localCurrent = lastTask;
        } while(Interlocked.CompareExchange (ref lastTask, task, localCurrent) != localCurrent);

        if (localCurrent == null) {
            task.Start (scheduler);
        } else {
            localCurrent.ContinueWith ((currentTask, scheduler) => {
                task.Start ((TaskScheduler)scheduler);
            }, scheduler, scheduler);
        }
    }
    [...]
}

The first thread to send an action will see null in the field and so needs to Start() the Task directly.

This (seems to) work. Only one submitted action is ever running at a given moment. Additionally, tasks are potentially run on different threads. I don't want a dedicated thread for updates (and I don't want to lock up a TaskScheduler thread).

However, I'm worried about a few things that I think could be improved:

I'd like to be able to ContinueWith the Task task directly, instead of having to start it within a different submitted Action. I feel like I need to create the new Task so that I can atomically exchange the lastTask field's value.
Lambda capturing of local variables, partly alleviated with state objects where possible.
How can I keep a reference to the currently executing Task, so I can short-circuit execution? Or should I use a poison pill to signal termination and not chain any new tasks?
Interlocked for atomicity. Should I use a ConcurrentQueue? How would I manage not having a dedicated thread and only running one Task at a time with a ConcurrentQueue?
Is a Volatile.Read of lastTask necessary for localCurrent = lastTask;?

Doing this now

private void InvokeAndComplete (Action<T> act, TaskCompletionSource<byte> promise)
{
    try {
        act (internalValue);
    } finally {
        // some value we will ignore
        promise.SetResult (1);
    }
}

public Task Alter (Action<T> alterAction)
{
    TaskCompletionSource<byte> promise = new TaskCompletionSource<byte> ();
    Task localLastTask;
    do {
        // Not sure if Volatile.Read is necessary
        localLastTask = Volatile.Read (ref lastTask);
    } while (Interlocked.CompareExchange (ref lastTask, promise.Task, localLastTask) != localLastTask);
    // only this thread has a reference to the object referenced by localLastTask
    return localLastTask.ContinueWith ((currentTask) => {
        InvokeAndComplete (alterAction, promise);
    }, taskScheduler);
}


texts: Displaying user-defined functions and their docstrings

texts:
Let's say I want to create dynamic documentation of functions I wrote, without using the help() function (I don't want the user to care about arguments accepted by my function, nor get cluttered with other stuff like the copyright info, or other stuff that aren't functions).

Here's an attempt:

import inspect

def foo():
    """Return 'foo' string"""
    return "foo"

def user_defined_functions():
    """Return names of user-defined functions"""
    for name in globals():
        if inspect.isfunction(eval(name)):
            docstring = eval(name + ".__doc__")
            print("{}:\n   {}".format(name, docstring))

And here's the pretty result:

>>> import test
>>> test.user_defined_functions()
user_defined_functions:
   Return names of user-defined functions
foo:
   Return 'foo' string

If I had just used the help function I could have gotten extra stuff I don't need (I'm not writing a library, so the user doesn't need all of this):

Help on module test:

NAME
    test

FUNCTIONS
    foo()
        Return 'foo' string

    user_defined_functions()
        Return names of user-defined functions

FILE
    /home/wena/src/utils/test.py


texts: C: Sieve of Eratosthenes and next twin prime

texts:
I am wondering if I can get some feedback for my implementation of "Sieve of Eratosthenes" and twin prime. I followed this pseudocode.
Few notes:

I added MAX(primes.size << 1, (x << 1) + 1) to make I resize the table large enough to find the next twin prime.
Use a struct to keep track of the size of the dynamic array

Things I am concerned about:

Using POW
goto statement

Only playground to test the code: https://www.onlinegdb.com/HydogHGxw
Thank you.
#include "prime.h"
#include <math.h>
#include <stdbool.h>
#include "stdlib.h"
#include "string.h"

#define INITIAL_TABLE_SIZE 9973
#define MAX(x, y) (((x) > (y)) ? (x) : (y))

typedef struct
{
  bool *array;
  unsigned int size
} PRIMES;

PRIMES primes = {NULL, 0};

/**
 * Create a boolean array "prime[0..n]" and initialize
 * all entries it as true. A value in prime[i] will
 * finally be false if i is Not a prime, else true.
 */
void sieve_of_eratosthenes(int n)
{
  if (primes.array != NULL)
  {
    free(primes.array);
  }

  primes.size = n;
  primes.array = malloc(n * sizeof(bool));
  memset(primes.array, true, n * sizeof(bool));

  primes.array[0] = false;
  primes.array[1] = false;

  int i, j;
  for (i = 2; i < (int)sqrt((double)n); i++)
  {
    // If primes[p] is not changed, then it is a prime
    if (primes.array[i] == true)
    {
      // Update all multiples of p
      for (j = (int)pow((int)i, 2); j < n; j += i)
      {
        primes.array[j] = false;
      }
    }
  }
}

/**
 * Return the next prime greater than parameter such that -2 is also a prime
 */
int next_twin_prime(int x)
{
  if (primes.array == NULL)
  {
    sieve_of_eratosthenes(INITIAL_TABLE_SIZE);
  }

resize:

  if (x >= primes.size)
  {
    int new_size = MAX(primes.size << 1, (x << 1) + 1);

    sieve_of_eratosthenes(new_size);
  }

  int i;
  for (i = x; i < primes.size; i++)
  {
    if (primes.array[i] == true && primes.array[i - 2] == true)
    {
      return i;
    }
  }

  goto resize;
}


texts: Rearrange list by modifying the original list, put even-index values at front

texts:
I am relatively new to python and I am still trying to learn the basics of the language. I stumbled upon a question which asks you to rearrange the list by modifying the original. What you are supposed to do is move all the even index values to the front (in reverse order) followed by the odd index values.

Initial:

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

Rearranged:

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

This is how I approached the question:

even = []
odd = []
for i in range(len(l)):
    if i % 2 == 0:
        even.append(i)
    else:
        odd.append(i)
even = even[::-1]
index = even + odd
l2 = []
for i in index:
    l2.append(l[i])
for i in range(len(l)):
    l[i] = l2[i]

Although it works, and does what is being asked, I was wondering if there is a more efficient way to get the result. I feel that creating three empty lists just to rearrange one list is not the best approach.

Any input would be greatly appreciated.


texts: Items derived from one function are getting printed within another for loop in another function

texts:
I have written some code in python to scrape some items from a webpage. There is a link (titling see more) attach to each container. If I click on that link I can reach a certain page where all the information is available. It is quite convenient to track the see more link and parse all documents from there. However, my goal is to parse the first two documents from the first page and going on to the other page (clicking on the see more button) I'll parse the rest. I have tried to do the same as I described just now. It is doing just fine.

At this point, I'm seriously dubious whether the way I'm doing things is the right one or error-prone because I used two items from earlier page to get printed within the newly defined for loop created in the later function. It is giving me the accurate results though. Any suggestion as to what I did here is ideal or any guidance why I should not practice this will be highly appreciated.

This is the site link. This is the full script:

import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

url = 'replace_with_the_above_link'

def glean_items(main_link):
    res = requests.get(main_link)
    soup = BeautifulSoup(res.text,"lxml")
    for item in soup.select('.course-list-item'):
        event = item.select(".lead")[0].text
        date = item.select(".date")[0].text
        link = urljoin(main_link,item.select(".pull-right a")[0]['href'])
        parse_more(event,date,link)

def parse_more(event_name,ev_date,i_link): ## notice the two items (event_name,ev_date)
    res = requests.get(i_link)
    soup = BeautifulSoup(res.text,"lxml")
    for items in soup.select('.e-loc-cost'):
        location = ' '.join([' '.join(item.text.split()) for item in items.select(".event-add")])
        cost = ' '.join([' '.join(item.text.split()) for item in items.select(".costs")])
        print(event_name,ev_date,location,cost) ##again take a look: I used those two items within this newly created for loop.

if __name__ == '__main__':
    glean_items(url)


texts: Outputs all substrings that are palindromes in a given string, in alphabetical order without repitition

texts:
I'm currently trying to find a way to get my program to run more efficiently. If anyone has any ideas on how to optimize my program, i would appreciate it a lot. Also, the output has to display in alphabetic order without any duplicates.

package Palindrome;
import java.io.*;
import java.util.*;
public class Palindrome {

public static void main(String[] args)throws IOException{
    Scanner scan;
    scan = new Scanner(System.in);
    while (scan.hasNext()) {

subPal(scan.next());
        }
    if (scan != null) {
        scan.close();
    }}

private static void subPal(String str) {
    String s1 = "";
    int N = str.length();
    ArrayList<String> palindromeArray = new ArrayList<String>();
    for (int i = 2; i <= N; i++) {
        for (int j = 0; j <= N; j++) {
            int k = i + j - 1;
            if (k >= N)
            continue;
            s1 = str.substring(j, i + j);
            if (s1.equals(new StringBuilder(s1).reverse().toString())&&    !palindromeArray.contains(s1)) {
            palindromeArray.add(s1);
        }
    }

}
Collections.sort(palindromeArray);
for (String s : palindromeArray)
    System.out.println(s );

}

}


texts:
I'm developing a document merger that utilizes an FTP site containing hundreds of documents.

FTP Connection Function

private static function establishFTP() {
    $ftp_conn = ftp_connect(getenv('FTP_HOST'));
    ftp_login($ftp_conn,getenv('FTP_USER'),getenv('FTP_PASS'));
    ftp_pasv($ftp_conn,true);

    return $ftp_conn;
}

I have a function that connects to the FTP site and generates an array of the documents stored inside a designated directory. It will remove the extensions from any files that are of type .docx. Then it will filter out all values containing a .. This removes any extra files that are not a Word document and also removes the FTP root pathings of . and .. from the array.

Form Generation Function

public static function generateForm() {
    $ftp_conn = self::establishFTP();

    $forms = ftp_nlist($ftp_conn,getenv('FTP_DIRECTORY'));
    $forms = str_replace('.docx','',$forms);
    $forms = array_filter($forms,function($value) {
        return strpos($value,'.') === false;
    });

    ftp_close($ftp_conn);

    return view('testDoc')->with(array('forms'=>$forms));
}

My view is very basic right now just to prove functionality. There is lots of design work that needs done to make it more user-friendly and functional.

Blade View

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="_token" content="{{ csrf_token() }}" />
<title>Form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
<body>
{{ Form::open(array('action'=>'DocumentController@mergeDocument')) }}
@foreach($forms as $doc)
    {{ Form::checkbox('documents[]',$doc) }}
    {{ Form::label(null,$doc) }}
@endforeach
{{ Form::submit('Submit',array('id'=>'submitBtn')) }}
{{ Form::close() }}
</body>
</html>

Lastly, I have a function that will accept an array of string values from the GUI. It will then establish a FTP connection and grab all documents requested from the FTP site. It will store these in a temp directory until the documents are merged and downloaded to the browser. Then it will unlink all temp files.

Merge and Download Documents Function

public static function mergeDocument() {
    $ftp_conn = self::establishFTP();

    $forms = Input::get('documents');
    $mergeDocs = array();
    $mergeName = uniqid('temp/files/merge-') . '.docx';
    $documentName = 'policies_' . date('m-d-H-i-s');

    foreach($forms as $doc) {
        ftp_get($ftp_conn,"temp/files/$doc.docx",getenv('FTP_DIRECTORY') . "/$doc.docx",FTP_BINARY);
        $mergeDocs[] = "temp/files/$doc.docx";
    }

    $firstDoc = array_shift($mergeDocs);

    ftp_close($ftp_conn);

    $mergeResult = new \Phpdocx\Utilities\MultiMerge();
    $mergeResult->mergeDocx($firstDoc,$mergeDocs,$mergeName,array('enforceSectionPageBreak'=>true));

    $phpdocx = new \Phpdocx\Create\CreateDocxFromTemplate($mergeName);
    $phpdocx->createDocxAndDownload($documentName);

    foreach($forms as $doc) {
        unlink("temp/files/$doc.docx");
    }
    unlink($mergeName);
    unlink("$documentName.docx");
}

Any suggestions as to the security and design of my app is appreciated.


texts: Performance of ID's checking between Access and Excel

texts:
I want to increase the performance of this code:

Dim...
...
...
...
...

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True

Set wb = objExcel.Workbooks.Open("C:\Dateipfad\Dateiname.xlsx", True)
Set rs = db.OpenRecordset("Select DataPointVID from My_ValidReport", dbOpenSnapshot)

Do Until rs.EOF = True
    For Each ws In wb.Worksheets
        Set ValidMeldeposition = ws.UsedRange.Cells.Find(What:=rs!DataPointVID)
        If Not (ValidMeldeposition Is Nothing) Then ValidMeldeposition.Interior.ColorIndex = 43
    Next ws
    rs.MoveNext
Loop

j = 0
Do While Dir(Dokumentenpfad) <> ""
    j = j + 1
    Dokumentenpfad = CurrentProject.Path & "\Dateiname" & Format(Date, " dd.mm.yyyy") & " (" & j & ")" & ".xlsx"
Loop

NeuerReport = Dokumentenpfad

wb.SaveCopyAs (NeuerReport)
MsgBox "Your file was saved here: " & vbCrLf & "'" & NeuerReport & "'"
objExcel.Visible = True

Set objWorkbook = Nothing
Set objExcel = Nothing

End Sub

The problem is that the Excel file contains over 70 Worksheets and every Sheet includes ID's which are checked by the code and also by the Access-Query which includes the ID's.


texts:
I am slowly learning C and C++, and decided after a few lessons to dive in myself without any help. I developed this prime number generator. It seems fast, but I'm wondering if I'm following the best practices for C++, or if I am missing anything important.

#include "stdafx.h"
#include "stdio.h"
bool checkPrime(int Number);

int _tmain(int argc, _TCHAR* argv[])
{
    int currentNum;
    currentNum = 2;
    do {
        if (checkPrime(currentNum)) {
            printf("%d ", currentNum);
        }
        currentNum++;
    } while (1 == 1);
    return 0;
}

bool checkPrime(int Number){
    for (int a = 2; a < Number; a++){
        if (Number % a == 0) {
            return false;
        }
    }
    return true;
}


texts:
I've written a .NET Core console application to monitor the operation of a sensor network and I'd like a review of the task scheduling performed by the main program loop. There are three tasks that are all declared as public static async Task that perform the following operations:

CheckGateways.CheckAll connects to an external API at one minute intervals and is the most likely to fail or take a long time. Normally it'll take a few seconds but I'd like other tasks to continue meanwhile.

CheckNodes.CheckAll is an internal database check that may take a few seconds but is not time critical and runs once per minute.

CheckAlerts.CheckAll checks for alert conditions on the sensors and is the most time critical so I'm checking that once per second.

While the code seems to be working it hasn't been well stress-tested and a few things I'd like reviewed are:

Are there any potential race conditions with the way I'm checking the status of the first two tasks?

I'm repeating the code to start / check the first two tasks so perhaps there's a cleaner way to do that without introduction too much extra code as there's unlikely to be any more tasks added.

Also any general comments on coding / naming standards would be appreciated.
static async Task Main()
{
    IConfiguration configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .Build();
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        .Enrich.FromLogContext()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
        .CreateLogger();
    Task checkGateways = null;
    DateTime lastGatewayCheck = DateTime.UtcNow;
    Task checkNodes = null;
    DateTime lastNodeCheck = DateTime.UtcNow;
    while (true)
    {
        try
        {
            // Check gateway connectivity loss at one minute intervals
            if (DateTime.UtcNow.Subtract(lastGatewayCheck).TotalMinutes >= 1
                    && (checkGateways == null || checkGateways.IsCompleted))
            {
                lastGatewayCheck = DateTime.UtcNow;
                checkGateways = CheckGateways.CheckAll(configuration);
            }
            if (checkGateways?.Status == TaskStatus.Faulted)
            {
                throw checkGateways.Exception;
            }

            // Check node connectivity loss at one minute intervals
            if (DateTime.UtcNow.Subtract(lastNodeCheck).TotalMinutes >= 1
                    && (checkNodes == null || checkNodes.IsCompleted))
            {
                lastNodeCheck = DateTime.UtcNow;
                checkNodes = CheckNodes.CheckAll(configuration);
            }
            if (checkNodes?.Status == TaskStatus.Faulted)
            {
                throw checkNodes.Exception;
            }

            // Check for pending alerts to send at one second interval
            await CheckAlerts.CheckAll(configuration);
        }
        catch (AggregateException ae)
        {
            foreach (var ex in ae.InnerExceptions)
            {
                LogException(ex);
            }
        }
        catch (Exception ex)
        {
            LogException(ex);
        }
        await Task.Delay(1000);
    }
}

public static void LogException(Exception ex)
{
    ConsoleMessage(ex.ToString());
    Serilog.Log.Error(ex, "Error occured in TelemetryService");
}

public static void ConsoleMessage(string msg)
{
    Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {msg}");
}


texts:
This is something I've done a few times, but I've found it to feel a bit error-prone with so many conditions, and am wondering if anyone can point me in the direction of a cleaner way. This is a PATCH route for editing a user. Super admin and admin users are both able to change other users (with some limitations) while other types of users can only edit themselves.
router.patch('/:userId', async (req, res) => {
  const patcher = (req as AuthRequest).user;
  const otherUser = await database.getUserById(req.params.userId);
  const requestedUpdate = req.body;

  // 404 if user is not found.
  if (!otherUser) {
    return sendCannotFind(res);
  }

  // Basic validation of requestedUpdate
  if (requestedUpdate.userType && !isUserTypeValid(requestedUpdate.userType)) {
    return sendInvalidUserType(res);
  }

  if (patcher.userType === 'superAdmin') {
    // Super admin cannot demote self.
    if (otherUser.id === patcher.id && requestedUpdate.userType) {
      return sendCannotSetUserType(res);
    }

    // Super admin cannot edit other super admins
    if (otherUser.userType === 'superAdmin' && otherUser.id !== patcher.id) {
      return sendCannotEdit(res);
    }
  } else if (patcher.userType === 'admin') {
    // Admin cannot edit super admins
    if (otherUser.userType === 'superAdmin') {
      return sendCannotEdit(res);
    }

    // Admin cannot edit other admins
    if (otherUser.userType === 'admin' && otherUser.id !== patcher.id) {
      return sendCannotEdit(res);
    }

    // Admin cannot promote or demote themselves
    if (otherUser.id === patcher.id && requestedUpdate.userType) {
      return sendCannotSetUserType(res);
    }

    // Admin cannot promote anyone to admin or superAdmin
    if (requestedUpdate.userType === 'admin' || requestedUpdate.userType === 'superAdmin') {
      return sendCannotSetUserType(res);
    }
  } else {
    // Non-admins cannot edit anyone but themselves
    if (otherUser.id !== patcher.id) {
      return sendCannotEdit(res);
    }

    // Non-admins cannot promote or demote themselves
    if (requestedUpdate.userType && requestedUpdate.userType !== otherUser.userType) {
      return sendCannotSetUserType(res);
    }
  }

  await doEdit(otherUser, requestedUpdate);
  return res.json(otherUser);
});
```


texts: Method to count all comments in single external C# file

texts:
I recently had an interview question:

  Write a method that counts all comments in a single external file.

It was a timed question and I wanted to know if this is the best way to accomplish the task. I'm also open to improvements, advice, etc.

(I didn't pass the interview.)

class Program
{
    static void Main(string[] args)
    {
        List<string> FileLines = new List<string>();
        const string Filename = @"file.txt";

        readInFile(Filename, FileLines);

        CountComments(FileLines);
    }

    public static void CountComments(List<string> value)
    {
        int finalCount = 0;
        List<string> something = value;
        bool inQuotes = false;

        for (int x = 0; x < something.Count; x++)
        {
            if (something[x] != @"""")
            {
                inQuotes = !inQuotes;
            }
            for (int y = 0; y < something[x].Length; y++)
            {
                if (something[x][y] == '/' && something[x][y + 1] == '/')
                {
                    finalCount++;
                    break;
                }
                else if (something[x][y] == '/' && something[x][y + 1] == '*')
                {
                    finalCount++;
                    break;
                }
            }
        }
        Console.WriteLine("Total number of comments is " + finalCount);

    }

    public static void readInFile(string Filename, List<string> FileLines)
    {
        using (StreamReader r = new StreamReader(Filename))
        {
            string Line;

            while ((Line = r.ReadLine()) != null)
            {
                FileLines.Add(Line);
            }
        }
    }
}


texts: Similar methods to update today's sales, revenue, and profit

texts:
Please help me to refactor. I have two models, conversion & statistic.
Methods sales_today, revenue_today, profit_today in conversion model only gets specific info from db.

Statistic model

class Statistic < ActiveRecord::Base

class << self

def create_and_update_today(agregate_name, value, network)
  today = find_or_create_by(agregateName: agregate_name, networkName: network)
  today.update(agregateName: agregate_name, date: Date.today,
                value: value, networkName: network)
end

def sales_today(network)
  total = Conversion.sales_today(network)
  create_and_update_today('salesToday', total, network)
end

def revenue_today(network)
  total = Conversion.revenue_today(network)
  create_and_update_today('revenueToday', total, network)
end

def profit_today(network)
  total = Conversion.profit_today(network)
  create_and_update_today('profitToday', total, network)
end

end
end

Conversion model

class Conversion < ActiveRecord::Base

  class << self

def sales_today(network)
  where('DATE(created_at)= ?  AND networkName = ?', Date.today, network).size
end
etc...

end

Is there any way to refactor almost similar pieces of code?


texts: Tying the enablement of one checkbox to another using AngularJS and jQuery

texts:
I'm new to AngularJS, coming from a jQuery background and I have a situation I've solved but only by including jQuery in an AngularJS function.  Something just doesn't feel right doing this and I was hoping someone could tell me if there's a better way. (This is all code I have inherited and have amended to enable new functionality)

I have 2 checkboxes, let's call them 'Notary' and 'Login'. If I enable Notary, then Login must get enabled and also disabled so the user can't uncheck it.

The ASPX looks like:

 Enable INKWRX Login:
 <dw-checkbox class="notarylogin" name="UserHasPassword" ng-model="user.Details.HasPassword" ></dw-checkbox>

Notary:
<dw-checkbox name="notary" id="notary" ng-model="user.ExtraData.userPermissions.notary.allowed" ng-click="amendNotary(user.ExtraData.userPermissions.notary.allowed)"></dw-checkbox>

When the dw-checkbox directive is invoked, it renders a checkbox input element for each dw-checkbox tag like this:

 //this directive adds behaviour for showing ticks and cross images in viewMode and an editable checkbox in editmode
    app.directive("dwCheckbox", function ($rootScope) {
        return {
            restict: 'E',
            require: 'ngModel',
            template: '<input name="name" type="checkbox" ng-model="model" />',
            scope: {
                model: '=ngModel',
                name: '=name'
            },
            link: function (scope, element, attrs, ngModel) {

                //render the field according to the mode and the current value of the model
                function render() { ...does the rendering..}

and my amendNotary function which does the checkbox disabling looks like this (I amended another directive to add an inklogin class to the Login checkbox):

$scope.amendNotary = function(value) {
       if (value === true) {
           $scope.user.Details.HasPassword = true;
           $('.inklogin').attr('disabled', true);
       } else {
           $scope.user.SignatureText = "Signature:";
           $('.inklogin').attr('disabled', false);
       }
    }

Is there an obvious cleaner way of doing this, or is mixing jQuery with Angular generally regarded as okay?


texts: Rewrite two mongo queries to aggregation

texts:
Here is a code block I have:

const _ = require('lodash')
const Box = require('./models/Box')

const boxesToBePicked = await Box.find({ status: 'ready' })
const boxesOriginalIds = _(boxesToBePicked).map('original').compact().uniq().value()
const boxesOriginal = boxesOriginalIds.length ? await Box.find({ _id: { $in: boxesOriginalIds } }) : []

const attributes = ['name']

const boxes = [
  ...boxesOriginal,
  ...boxesToBePicked.filter(box => !box.original)
].map(box => _.pick(box, attributes))

Let's say, we have following data in the "boxes" collection:

[
  { _id: 1, name: 'Original Box #1', status: 'pending' },
  { _id: 2, name: 'Nested box', status: 'ready', original: 1 },
  { _id: 3, name: 'Nested box', status: 'ready', original: 1 },
  { _id: 4, name: 'Nested box', status: 'pending', original: 1 },
  { _id: 5, name: 'Original Box #2', status: 'ready' },
  { _id: 6, name: 'Original Box #3', status: 'pending' },
  { _id: 7, name: 'Nested box', status: 'ready', original: 6 },
  { _id: 8, name: 'Original Box #4', status: 'pending' }
]

Workflow

Find all boxes, which are ready to be picked:

const boxesToBePicked = await Box.find({ status: 'ready' })

// Returns:

[
  { _id: 2, name: 'Nested box', status: 'ready', original: 1 },
  { _id: 3, name: 'Nested box', status: 'ready', original: 1 },
  { _id: 5, name: 'Original Box #2', status: 'ready' },
  { _id: 7, name: 'Nested box', status: 'ready', original: 6 }
]

Get all the IDs of the original (parent) boxes of those:

const boxesOriginalIds = _(boxesToBePicked).map('original').compact().uniq().value()

// Returns:

[1, 6]

Get those boxes by their IDs:

const boxesOriginal = boxesOriginalIds.length ? await Box.find({ _id: { $in: boxesOriginalIds } }) : []

// Returns

[
  { _id: 1, name: 'Original Box #1', status: 'pending' },
  { _id: 6, name: 'Original Box #3', status: 'pending' }
]

Join those boxes with non-nested boxes to be picked:

const boxes = [
  ...boxesOriginal,
  ...boxesToBePicked.filter(box => !box.original)
].map(box => _.pick(box, attributes))

// Returns

[
  { name: 'Original Box #1' },
  { name: 'Original Box #3' },
  { name: 'Original Box #2' }
]

So basically what we are doing here is getting all the original boxes if they have at least one nested box with status "ready", and all non-nested boxes with status "ready".

I think it can be simplified by using aggregation pipeline and projection. But how does one do that?


texts:
I went through a question on SO, and optimized the code according to OP's requirements. I would like a review if it is done properly or not.

Here is the code snippet, there are 2 level buttons, when clicked 1st level button, it toggles second level button group.

Second level button group toggles div, which contains checkbox. Any review and suggestions are appreciated.

$(document).ready(function() {

  var groups = ['a', 'b', 'c']; // here

  $.each(groups, function(k, id) {
    $('#' + id).hide();
    $('#' + id + 'l').hide();
  });

  $(".button").click(function() {

    var button_id = $(this).data('id');

    $('#' + button_id).toggle();

    var hide = $.grep(groups, function(value) {
      return value != button_id;
    });

    $.each(hide, function(k, id) {
      $('#' + id).hide();
    });

  });

  var selector = [];

  $.each(groups, function(k) {
    selector.push('.' + groups[k]);
  });

  selector = selector.join(',');

  $(selector).click(function() {

    var button_id = $(this).data('id');
    var class_id = $(this).attr('class');
    var flag = $('.' + class_id + 'l').filter('[data-id="' + button_id + '"]').is(':visible');

    $.each(groups, function(k, id) {
      $('#' + id + 'l').children().hide();
    });

    $.each(groups, function(k, id) {
      $('#' + id + 'l').hide();
    });

    $('#' + class_id + 'l').show();

    if (flag)
      $('.' + class_id + 'l').filter('[data-id="' + button_id + '"]').hide();
    else
      $('.' + class_id + 'l').filter('[data-id="' + button_id + '"]').show();
  });

});

<button class="button" data-id="a">Toggle a</button>
<button class="button" data-id="b">Toggle b</button>
<button class="button" data-id="c">Toggle c</button>

<button>Toggle a1</button>

<button>Toggle a2</button>

<button>Toggle a3</button>

<button>Toggle b1</button>

<button>Toggle b2</button>

<button>Toggle b3</button>

<button>Toggle c1</button>

<button>Toggle c2</button>

<button>Toggle c3</button>

this is line a1

this is line a2

this is line a3

this is line b1

this is line b2

this is line b3

this is line c1

this is line c2

this is line c3


texts:
I have a navigation bar without a tags:

    $('div.nav ul li').on('click', function() {
        if($(this).is(':first-child')) {
            $("html, body").animate({
                scrollTop: "0"
            }, 'slow');
        } else if($(this).is(':nth-child(2)')) {
            $("html, body").animate({
                scrollTop: "0"
            }, 'slow');
        } else if($(this).is(':nth-child(3)')) {
            var offset = $('div.features').offset().top;
            $("html, body").animate({
                scrollTop: offset+ 'px'
            }, 'slow');
        } else if($(this).is(':nth-child(4)')) {
            var offset = $(document).height();
            $("html, body").animate({
                scrollTop: offset+ 'px'
            }, 'slow');
        }
    });

I wondered if this way is the best way of doing this.  first-child & nth-child(2) goes to the same place, then each child after that - up to 4 has a different position to go to.


texts: Should Golang interface be shared among different packages of an application?

texts:
I'm developing a Go application that has lots of packages.
Many of the packages use the same type from a 3rd party library.
Should an interface be defined for the type in each package, and let the interfaces only contain the methods that are used by the package?
Or, we should define a single interface for the whole application, and let the interface contain the union of all the methods that are used throughout the application?
At official Golang wiki, there's a statement

    Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values.

But does the package means the one that actually uses the type or the root package of the project?
Here's a simplified example:

package subnet
type netOpsClient interface {
    Subnets(ctx context.Context, options map[string]string) ([]string, error)
}

type PrimaryNetFinder struct {
    netOpsClient netOpsClient
}

func (p *PrimaryNetFinder) Find(ctx context.Context) ([]string, error) {
    subnets, err := p.netOpsClient.Subnets(ctx, map[string]string{
        "level": "50",
    })
    //...
}

package loader
type netOpsClient interface {
    Subnets(ctx context.Context, options map[string]string) ([]string, error)
    SubnetGet(ctx context.Context, id string) (netops.Subnet, error)
}
type RulesLoader struct {
    netOpsClient netOpsClient
    policyStore policyStore
}
func (r *RulesLoader) LoadRules(ctx context.Context) error {
    //...
    subnets, err := r.netOpsClient.Subnets(ctx, map[string]string{
        "level": level,
        "site": "ne",
    })
    //...
    subnet, err := r.netOpsClient.SubnetGet(ctx, subnetId)
    //...
    policies, err := policyStore.Policies(subnet.cidr)
    //...
}

You can see both PrimaryNetFinder and RulesLoader store a field of type netOpsClient, which is an interface defined in the package. And a type from a 3-party NetOpsClient implements the interface.
If many packages in the project have a reference to the type, should each package define a similar interface like above? Or, should I define a single interface, and let all the packages share the same interface like below?

package netops
type NetOpsClient interface {
    Subnets(ctx context.Context, options map[string]string) ([]string, error)
    SubnetGet(ctx context.Context, id string) (netops.Subnet, error)
    // ...
}


texts: Creating a bijection between integers and a set of strings

texts:
I have a set of unique strings, I want to create a unique integer identifier for each string.

Usage I want a function to move back and forth, if I give it an integer it returns the corresponding string and vice versa.

Here is how I am doing it

def str_to_int(S):
    integers = list(range(len(S)))
    my_dict = dict(zip(S,integers))
    rev_dict = dict(zip(integers,S))
    return my_dict, rev_dict

If I need to get the integer identifier of an item of S, I need to call the function and then the appropriate returned dictionary.

I want something simpler, given an integer or a string, it knows, somehow automatically if it's an int or str and return the other identifier (i.e. if I give an int it returns the str identifier and vice versa). Is it possible to do it in a single function ? (if possible without being obliged to recreate dictionaries for each call)

Edit: I thought of doing to functions str_to_int(S:set, string:str)->int and int_to_str(S:set ,integer:int)->str but the problem is 1) that's two functions, 2) each time two dictionaries are created.


texts: IEEE 754 square root with Newton-Raphson

texts:
I have an implementation of the sqrt function that uses a combination of IEEE 754, packed bitfields, and the Newton-Raphson algorithm:

decompose.h:

#ifndef DECOMPOSE_H
#define DECOMPOSE_H 1

#ifdef __cplusplus
extern "C" {
#endif

#include <float.h>

#define MANTISSA_SIZE 52
#define EXPONENT_SIZE 11
#define EXPONENT_BIAS 0x3ff
#define TYPE double
#define TYPE_MIN DBL_MIN
#define TYPE_MAX DBL_MAX
#define NAME_SFX(name) name

typedef unsigned long long mantissa;
typedef unsigned short exponent;
typedef unsigned char sign;

#include "decompose_generic.h"

#ifdef __cplusplus
}
#endif

#endif

decompose_generic.h:

#ifndef DECOMPOSE_GENERIC_H
#define DECOMPOSE_GENERIC_H 1

#ifdef __cplusplus
extern "C" {
#endif

#define SIGN_SIZE 1

union decompose {
    TYPE f;
    struct decompose_s {
        mantissa m:MANTISSA_SIZE;
        exponent e:EXPONENT_SIZE;
        sign s:SIGN_SIZE;
    } __attribute__((packed)) o;
};

static inline union decompose decompose(TYPE f)
{
    union decompose result;
    result.f = f;
    return result;
}

#define is_nan(x) NAME_SFX(isnan)(x)

#ifdef __cplusplus
}
#endif

#endif

sqrt.c:

#include <math.h>
#include <errno.h>

#include "decompose.h"

TYPE NAME_SFX(sqrt)(TYPE a)
{
    TYPE result_old2 = 0;
    unsigned short c = 0;
    union decompose r = decompose(a);

    if(a < -(TYPE)0)
    {
        errno = EDOM;
        return NAME_SFX(nan)("");
    }
    if(a == (TYPE)0 || is_nan(a) || a > TYPE_MAX)
    {
        return a;
    }

    /* Divide the exponent by 2 */
    r.o.e -= EXPONENT_BIAS;
    r.o.e = (r.o.e & 1) | (r.o.e >> 1);
    r.o.e += EXPONENT_BIAS;

    /* Newton-Raphson */
    while(result_old2 != r.f)
    {
        if(c % 2 == 0) result_old2 = r.f;
        r.f -= (r.f*r.f-a)/(2*r.f);
        c++;
    }

    return r.f;
}

What I'm looking for:

Are there any efficiency problems?
Are there any accuracy problems?
Are there any other miscellaneous things that I can improve?

As far as I've tested, this is as accurate as possible. It even matches the results from the GNU C library.

One note: This is part of a modular system. There will be a decompose.h for each floating point type (float, double, long double), and they all include decompose_generic.h.

I'm slightly new to this area of C (math, IEEE 754), but not so new that I'd add the beginner tag.


texts: Find max number of repeating heads and tails

texts:
Problem Statement:

Consider the following example: a coin was tossed n=7 times and the results were

"Heads, Tails, Tails, Tails, Heads, Heads, Tails"

Therefore, the longest Heads streak was 2 and the longest Tails streak was 3.

Here is my code:

def getMaxStreaks(toss): #toss=> ["Heads, Tails, Tails, Tails, Heads, Heads, Tails"]
    # Return an array of two integers containing the maximum streak of heads and tails respectively
    scH, scT = 0, 0
    H, T = 0, 0
    for tossResult in range(0, len(toss)):
        if toss[tossResult] == 'Heads':
            H, T = H+1, 0
            if H > scH:
                scH = H

        elif toss[tossResult] == 'Tails':
            H, T = 0, T+1
            if T > scT:
                scT = T
    return [scH, scT] # 2 3

What can I do to improve my code, are there any improvements required? Please let me know if I need to update the question.


texts: Merging hashes, summing values that have the same key

texts:
I'm trying to group by keys in an Array of Hashes in the following form and add their totals. Maybe with #map and #reduce/#inject. I know there is a more compact way to do this.

Given I have

codes_and_totals = [{'1001' => 153, '212' => 153}, {'212' => 1}]

When I run

process_codes_and_totals(codes_and_totals)

Then the return value should be

=> {'1001' => 153, '212' => 154}

Currently #process_codes_and_totals looks like this

def process_codes_and_totals(codes_and_totals)
    totals_across_locations = {}
    codes_and_totals.each do |location|
      location.each do |class_code, total|
        totals_across_locations[class_code] ||= 0
        totals_across_locations[class_code] += total
      end
    end

    totals_across_locations
end


texts: Counting the amount of objects in an array that contain a certain key that doesn't have an empty value

texts:
Here is my source code:

// start at zero
var count = 0;
// loop through the items
for(var i = 0; i < hours.length; i++) {
  // 1. check to see if the current item has a key called "description"
  // 2. check to see if the current item's "description" key isn't empty
  // NOTE: white-space only values aren't valid
  if(hours[i].hasOwnProperty("description") && hours[i].description.replace(/\s/g, "").length > 0) {
    // increment the count (by one)
    count += 1;
  }
}
// return the count
return count;

When we remove the comments the code looks like this:

var count = 0;
for(var i = 0; i < hours.length; i++) {
  if(hours[i].hasOwnProperty("description") && hours[i].description.replace(/\s/g, "").length > 0) {
    count += 1;
  }
}
return count;

This appears to be rather expensive (especially with larger arrays). Is there a better (preferably a more concise) way to count the amount of objects in an array that contain a certain key that doesn't have an empty value?

INFO: I can't use jQuery or LoDash/Underscore, all methods must be natively available in the browser and have good browser support (IE8+).


texts:
For some time now, I've been working on a game which is superficially similar in appearance to this one. A world is filled with particles that move and change state frequently (per frame, often). Drawing is achieved by finding the locations of particles within the camera's viewport, calculating lighting for the grid locations within the viewport, and then tinting a 1x1 white texture with the appropriate color, based on the particle and the lighting present in the particle's grid space:

public void drawParticles(ParticleBoard particle_board) {
    final int cam_min_x = camera.getCameraMinX();
    final int cam_min_y = camera.getCameraMinY();
    final int cam_max_x = camera.getCameraMaxX();
    final int cam_max_y = camera.getCameraMaxY();
    final float[][] light = light_manager.calculateLighting();

    for (int y = cam_min_y; y < cam_max_y; y++) {
        for (int x = cam_min_x; x < cam_max_x; x++) {
            final float l = light[x - cam_min_x][y - cam_min_y];
            if (l <= 0.05f) continue; // don't draw if it's too dark.

            final Particle p = particle_board.getParticle(x, y);

            if (p != null) {
                final Color c = p.getProperty().getColor();
                sprite_batch.setColor(new Color(c.r, c.g, c.b, l));
                sprite_batch.draw(texture, x, y);
            }
        }
    }
}

Light calculations are done within an array of floats the size of the current viewport. The approach is somewhat flood-fill-y, in that initial light values are placed at the 'top' of the array and then spread across the rest of the array, changing based on the presence of blocks:

float[][] calculateLighting() {
    final int cam_min_x = camera.getCameraMinX();
    final int cam_min_y = camera.getCameraMinY();
    final int cam_max_x = camera.getCameraMaxX();
    final int cam_max_y = camera.getCameraMaxY();
    final int light_width = cam_max_x - cam_min_x + 1;
    final int light_height = cam_max_y - cam_min_y + 1;
    final float[][] ambient_light = new float[light_width][light_height];

    for (int y = light_height - 1; y >= 0; y--) {
        for (int x = 0; x < light_width; x++) {
            final float max = getMaxNeighboringLight(ambient_light, x, y, light_width, light_height);

            if (particle_board.getParticle(x + cam_min_x, y + cam_min_y) != null) {
                ambient_light[x][y] = max * 0.75f; // TODO: add constant to particle properties for transparency -- use that here.
            } else {
                ambient_light[x][y] = max;
            }
        }
    }

    return ambient_light;
}

Here's how the max neighboring light level is found:

private float getMaxNeighboringLight(float[][] l, int x, int y, int light_width, int light_height) {
    float left = 0f, right = 0f, top = 0f, bottom = 0f;

    if (x == 0) {
        left = 0f;
    } else if (x == light_width - 1) {
        right = 0f;
    } else {
        left = l[x - 1][y];
        right = l[x + 1][y];
    }

    if (y == 0) {
        bottom = 0f;
    } else if (y == light_height - 1) {
        top = 1f;
    } else {
        bottom = l[x][y - 1];
        top = l[x][y + 1];
    }

    return Math.max(left, right, top, bottom);
}

Here's the result:

It would be very interesting to hear suggestions as to how these approaches to rendering and lighting calculations could be improved. It seems rather inefficient to create a new lighting array each frame, but I'm not sure how I could do much better, since many of the particles shift around frequently. Similarly, it seems that drawing could be improved, but I lack the knowledge to do so. If any clarification would be useful, please let me know. The approach used to draw particles is based in part on the responses that I got from this question.


texts: Find all numbers that are factors of one array and factor into the second array, then print their count

texts:
I'm working on a solution to the Following problem on Hackerrank, and I seem to have found a function that works for the purpose.
However, I feel as though this is a very overdesigned solution to a problem that appears, at first glance, to be simple. This is what I've come up with so far:
This code takes in two arrays, finds every pair of numbers from 1 to 100, multiplies them together, and tests if the product is a factor of all elements in the first array. If so, it appends the product to the fact array. Then, it tests every element in the fact array and checks if the element evenly divides every element in the second array. If so, it loads that element into a new list. Finally, it returns the length of the new list
I've run the code through a few static analyzers but they became unhelpful after a point. I'm looking for ways to cut this code down and reduce its complexity and depth. Any comments or criticisms are welcome!
Apologies if I've made any mistakes in my question-asking etiquette here, feel free to let me know if this needs more context and thanks in advance!
def get_total_x(input_factors: int, test_numbers: int) -> int:
    fact = list()
    output = list()
    for mult1 in range(100):
        for mult2 in range(100):
            # find all multiples of mult1 and mult2 that can be factored
            # into all numbers in a, while ignoring zero.
            if all(v == 0 for v in [(mult1 * mult2) % factor for factor in input_factors]) and (mult1 * mult2 != 0):
                fact.append(mult1 * mult2)
    seen = set()
    seen_add = seen.add
    # remove duplicates, may be able to cut out?
    fact = [x for x in fact if not (x in seen or seen_add(x))]
    for test in fact:
        # check for all numbers from the previous loop that divide b cleanly.
        if all(w == 0 for w in [factor2 % test for factor2 in test_numbers]):
            output.append(test)

    return len(output)

if __name__ == '__main__':

    arr = (2, 4)

    brr = (16, 32, 96)

    total = get_total_x(arr, brr)

    print(total)


texts: Performant functional evaluation for enum value

texts:
I have a Java enum which represents the side of an order (enum Side {ASK, BID}) and I'm constantly writing code with which I'd like to use the ternary operator, e.g.:

BigDecimal orderPrice = order.getSide() == Side.ASK ? calcAskPrice(order) : calcBidPrice(order)

The issue is that I want to future proof the code so that it fails if the provided value is neither ASK nor BID. The obvious solution seems unnecessarily verbose to me, because the pattern needs to be repeates tens (maybe even hundreds?) of times throughout the code. I'd rather not have this everywhere:

BigDecimal orderPrice;
if (order.getSide() == Side.ASK) {
   orderPrice = calcAskPrice(order);
} else if (side == Side.BID) {
   orderPrice = calcBidPrice(order);
} else {
   throw new IllegalArgumentException("The provided order must have a side that is either ASK or BID");
}

Instead I'd prefer a more functional approach, like the ternary operator.

A safer approach works, but is (i) also verbose and (ii) confusing:

BigDecimal orderPrice = order.getSide() == Side.ASK ? calcAskPrice(order) : order.getSide() == Side.BID ? calcBidPrice(order) : null;
assertNotNull(orderPrice);

Thinking about my desired syntax, I decided to add some methods to the enum such that I could write:

BigDecimal orderPrice = order.getSide().ifAsk(calcAskPrice(order)).ifBid(calcBidPrice(order)).elseFail();

This was implemented via an object that would store the value of the enum along with the two result values, and whose elseFail() method would return the appropriate result or fail. I was extremely satisfied with this, until (in pursuit of a separate issue) I noticed that my little evaluator object had a rather large footprint, but in terms of object creation & CPU time.

In retrospect this makes sense, because the code processes large numbers of updates, and is scattered with checks to the order side.

I'm now left with trying to think up a performant/low overhead way to provide similar syntax. The easiest solution that I can think of is to have a method on the enum:

public <T> T ifAskBid(T askResult, T bidResult) {
   // . . .
}

but I'm curious if anybody can think of a nicer solution.


texts:
Cardshifter is an online trading card game, made by a gang of Code Review community members. Cards can have a bunch of different, and sometimes complex effects, and descriptions for these are automatically generated if no custom one is given.

  EIGHT IMMORTALS:
  Choose 1 at random: Summon 1 Life Tool to your Battlefield or Summon 1 Destruction Tool to your Battlefield

The effect description code is quite messy and hard to adapt, which is why I've started a refactoring effort to improve it. The class up for review here is part of this effort.

Design aims

The ability to act as a Strangler Vine and gradually replace what already exists. This is achieved through the text method that simply proxies its input straight to the string builder (which is what was earlier used).
I wanted the class to be very robust and still produce consistent output no matter what is thrown at it. This is largely because of the legacy code, which is inconsistent in some areas.

The code

/**
 * Build sentences using a convenient DSL. Sentences are capitalized and end with a period.
 */
class SentenceBuilder {

    private StringBuilder stringBuilder = new StringBuilder()

    static String build(@DelegatesTo(strategy = Closure.DELEGATE_FIRST, value = SentenceBuilder) Closure closure) {
        def builder = new SentenceBuilder()
        closure.delegate = builder
        closure.resolveStrategy = Closure.DELEGATE_FIRST
        closure.call()

        return builder.toString()
    }

    String toString() {
        String sentence = stringBuilder.toString()

        sentence = sentence.trim()
        if (sentence.length() > 0 && !sentence.endsWith('.')) {
            sentence = sentence + '.'
        }
        sentence = sentence.capitalize()

        return sentence
    }

    /**
     * Add some text.
     */
    void text(String string) {
        stringBuilder.append(string)
    }

    /**
     * Add a separator if not already present and it's not the start of the sentence.
     * @param sep The separator, e.g. ' ' or ', '.
     */
    void separator(String sep) {
        if (stringBuilder.length() > 0 && !stringBuilder.toString().endsWith(sep)) {
            stringBuilder.append(sep)
        }
    }

    /**
     * Add a list like 'egg, bacon and ham'.
     * @param conjunction Conjunction between the last two elements, e.g. 'and'.
     * @param elements A list of the elements, e.g. ['egg', 'bacon', 'ham'].
     */
    void list(String conjunction, List<String> elements) {
        if (elements.size() > 0) {
            stringBuilder.append(elements[0])

            if (elements.size() > 1) {
                for (int i = 1; i < elements.size() - 1; i++) {
                    separator(', ')
                    stringBuilder.append(elements[i])
                }

                separator(' ')
                stringBuilder.append(conjunction)
                separator(' ')
                stringBuilder.append(elements[elements.size() - 1])
            }
        }
    }

}

I don't really like the implementation of list - it doesn't look very groovy at all, but I didn't come up with a better way to handle all cases.

Usage example

def things = ['cats', 'crackers', 'computers']
def feeling = 'like '

SentenceBuilder.build {
    text 'i'
    separator ' '
    text feeling
    separator ' '
    list 'and', things
}

// I like cats, crackers and computers.


texts:
I have myself a little challenge tonight. I've tried to come up with the shortest code for the problem below (the code is pretty self explanatory, except determinGrade there which follows the rule

  A - 90-100%
    B - 80-89%
    C - 70-79%
    D - 60-69%
    F - Below 60%

The code has to be PEP8 complient and no imports (std included) are allowed. Tell me if you can shorten the code further.

isValidScore = lambda n: 0 <= n <= 100
calcAverage = lambda *args: sum(args)/len(args)
determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A'][max(0, (min(s, 99)/10)-5)]

def getValidScore():
    while True:
        try:
            s = int(raw_input('Input score: '))
            if isValidScore(s):
                return s
        except ValueError:
            pass
        print('Score has to be an integer in the range 0 to 100')

if __name__ == "__main__":
    scores = [getValidScore() for _ in range(5)]
    print('The scores are: ' + str(scores))
    print('The average is: ' + str(calcAverage(*scores)))
    print('The grade is: ' + determinGrade(calcAverage(*scores)))


texts: Write into the same CSV file multiple times

texts:
I implemented an OutputWriterService.class to write content in the same file multiple times.

The writeToCsvFile method is called round about 50.000 times and includes a list of descrptions which also needs to iterate and write to the file.

Is it a good way to instantiate a new Filewriter, BufferedWriter and PrintWriter for every call?

public void writeToCsvFile(List<CustomTypeDescription> descriptions){
        try(FileWriter fw = new FileWriter(FILE_NAME, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw))
        {
            for(CustomTypeDescription description : descriptions){
                out.println(description.toString());
            }

            //here the fw.flush()?

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void createOutputFile() throws IOException {
        try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FILE_NAME), "utf-8"))) {
        }
    }

Update:

Is it necessary to flush File-, Buffered- and Printwriter one by one or just the FileWriter. I would do it after the loop?


texts:
Previous review of this project:

Deck of cards program using a card value map

Based on the previous feedback I've received, my program could become more flexible (it formerly created a standard 52-card deck by itself).  Now, the user can add Cards to a Deck, and Card is no longer hidden.  I like this approach better (also easier to work with), but I'm sure it can still be improved.  Regarding its use, I have a few questions:

Although accessors aren't always recommended, would they still be necessary for allowing the driver to know each Card value/rank/suit (unless they're maintained elsewhere)?  For instance, Blackjack requires card numerical values for determining a bust.
Is the exception-handling in deal() effective (when called on an empty Deck), although it'll still need to return a Card?  This is assuming that the user will not always call empty() before calling deal().
Is this particular approach too flexible?  If so, what could be done instead?

Deck.h

#ifndef DECK_H
#define DECK_H

#include <iostream>
#include <cstdint>
#include <vector>

class Card
{
private:
    unsigned value;
    char rank;
    char suit;

public:
    Card(unsigned v, char r, char s) : value(v), rank(r), suit(s) {}
    friend std::ostream& operator<<(std::ostream &out, const Card &card)
        {return out << '[' << card.rank << card.suit << ']';}
};

class Deck
{
private:
    std::vector<Card> cards;
    int topCardPos;

public:
    Deck();
    void addCard(unsigned value, char rank, char suit);
    void shuffle();
    Card deal();
    std::size_t size() const {return topCardPos+1;}
    bool empty() const {return topCardPos == -1;}
    friend std::ostream& operator<<(std::ostream &out, const Deck &deck);
};

#endif

Deck.cpp

#include "Deck.h"
#include <algorithm>
#include <stdexcept>

Deck::Deck() : topCardPos(-1) {}

void Deck::shuffle()
{
    topCardPos = cards.size()-1;
    std::random_shuffle(cards.begin(), cards.end());
}

void Deck::addCard(unsigned value, char rank, char suit)
{
    cards.push_back(Card(value, rank, suit));
    topCardPos++;
}

Card Deck::deal()
{
    try
    {
        topCardPos--;
        return cards.at(topCardPos+1);
    }
    catch (const std::out_of_range &oor)
    {
        std::cerr << "\nDECK DEAL ERROR: " << oor.what() << "\n";
        Card blankCard(0, '*', '*');
        return blankCard;
    }
}

std::ostream& operator<<(std::ostream &out, const Deck &deck)
{
    for (unsigned i = 0; i < deck.size(); ++i)
    {
        out << "\n" << deck.cards[i];
    }

    return out;
}

(Possible driver)

Deck deck;

std::array<char, 13> RANKS = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'};
std::array<char, 4> SUITS = {'H','D','C','S'};

for (unsigned rank = 0; rank < RANKS.size(); ++rank)
{
    unsigned value = (rank < 10) ? rank+1 : 10;

    for (unsigned suit = 0; suit < SUITS.size(); ++suit)
    {
        deck.addCard(value, RANKS[rank], SUITS[suit]);
    }
}


texts:
I need to collect all the data from the stream and resolve it as promise.

I created this stream:

class CollectToPromise extends Writable {
  constructor(options) {
    super();
    this._result = ""

    this.result = new Promise((resolve, reject) => {
      this.on('finish', resolve):w
      this.on('error', reject)
    }).then(() => this._result)

  }

  _write(chunk, encoding, callback) {
    this._result += chunk
    callback()
  }

  _writev(chunks, callback) {
    chunks.forEach(c => {
      this._result += chunk
    })
    callback()
  }

  asPromise() {
    return this.result
  }
}

and I use it like this:

var r = fs.createReadStream('secrets');
const c = new CollectToPromise()
const encrypt = crypto.createCipher(algorithm, password);
r.pipe(encrypt).pipe(c).asPromise().then((res) => console.log(res)

My questions are:

What do you think about the solution, including the naming?
How can I avoid the warning: (node:32386) Warning: Use Cipheriv for counter mode of aes-256-ctr?


texts: Removing spam from a database using NodeJS

texts:
I've written the following in NodeJS as I am trying to learn a bit more about that toolset. It 'works' but is not very robust. I am not concerned with security at this stage and the code will not be accessible to end users. I would like to incorporate some kind of timer which ensures that the call to the Akismet API does not hit a rate limit. Occasionally I see socket hang up and timeout errors.

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '123',
    database : 'mydb',
    //debug: true,
    multipleStatements: true
});

var akismet = require('akismet').client({ blog: 'http://example.com', apiKey: 'xxxxxxx' });

var selectPosts = "SELECT p.topic_id as id, poster_ip, t.subject as message, p.poster FROM topics  t\
                  LEFT JOIN posts p on t.first_post_id = p.id WHERE poster_ip != ''";

akismet.verifyKey(function(err, verified) {
    if(err) throw err;
    if (verified) {

        console.log('API key successfully verified.');
    }

    else {

        console.log('Unable to verify API key.');
    }

});

connection.connect();

connection.query(selectPosts, function(err, rows, fields) {
    if (err) throw err;

    rows.forEach( function(entry) {

    checkSpam(entry)

    });

});

var afterDelete = function (err, result) {

    if (err) throw err;
    console.log('deleted ' + result.affectedRows + ' rows');

}

var afterCheck = function(err, entry) {

    if (err) throw err;

    var deleteQuery = "DELETE t, p FROM topics AS t LEFT JOIN posts AS p ON t.id = p.topic_id WHERE t.id=";
    var deleteUser = "DELETE FROM users WHERE username='"+entry.poster+"';";
        console.log(deleteQuery + entry.id);
        console.log('entry is ' + entry['id']);
        connection.query(deleteQuery + entry.id, function(err,result)
        {
            afterDelete(err,result);
        });

        connection.query(deleteUser, afterDelete);

}

var checkSpam = function(entry) {
    akismet.checkSpam({
        user_ip: entry['poster_ip'],
        comment_author: entry['poster'],
        comment_content: entry['message']

    }, function(err, spam){
        if (err) throw err;
        if (spam) {
            //console.log('spam');
            afterCheck(err, entry);

        } else {

            console.log('Not spam');

        }

    });

}

//connection.end();


texts:
Given a graph and a starting vertex print the value of each vertex in a breadth first order.

Let's code out a general BFS algorithm printing each vertex's value in a BFS order. We are given a graph in the form of an adjacency list, as well as a starting vertex.

To analyze the complexity of a graph, we need to consider the number of vertices (V) and the number of Edges (E) as independent variables. Also, we need to consider the type of edge representation for the graph. We will go over the analysis for adjacency list.

Pseudocode
1. Create a queue to hold neighbor vertices and add the start vertex.
2. Create a set to track visited vertices and add the start vertex.
3. While queue is not empty
    4. Dequeue from the queue and set to current.
    5. Loop through all the vertex's neighbors.
        6. For each neighbor, check if the vertex has been visited.
        7. If not visited, then add it to the queue and add mark it as visited.
    8. Operate on current
9. Once the queue is empty, we have completed the BFS

Here's the code in JavaScript:

function graphBFS(graph, start) {
    let queue = new Queue(); // 1
    let visited = new Set(); // 1
    let current;             // 1
    let neighbors;           // 1

    queue.enqueue(start);    // 1
    visited.add(start);      // 1

  // while loop will run a total of V times
    while (queue.length > 0) {                       // 1 (for break condition)
        current = queue.dequeue();                   // 1
        neighbors = graph.neighbors(current);        // 1 (for adjacency list)
        // the for loop will run based on d (degree) on average is E/V
        for (let i = 0; i < neighbors.length; i++) {    // 1
            if (!visited.has(neighbors[i]) {            // 1
            queue.enqueue(neighbors[i]);                // 1
            visited.add(neighbors[i]);                  // 1
        }
        // <-- operating on the current vertex will add additional time
    }
  }
}


texts: Timeout on Python code to count connected components on HackerRank

texts:
I'm trying to solve the "Roads and Bridges" problem on HackerRank https://www.hackerrank.com/challenges/torque-and-development/problem

I believe the code works, but just needs to be optimized for speed. Any advice as to how to approach this? Is the issue the the list comprehension line? Or perhaps the list(unseen)[0] call?

import sys
from collections import defaultdict

# return connected component containing x
def component(graph, x):
    visited, stack = set(), [x]
    while len(stack):
        x = stack.pop()
        visited.add(x)
        stack.extend([u for u in graph[x] if u not in visited])
    return visited

q = int(raw_input().strip())
for a0 in xrange(q):
    n, m, x, y = raw_input().strip().split(' ')
    n, m, x, y = [int(n), int(m), long(x), long(y)]
    roads = []
    for a1 in xrange(m):
        city_1, city_2 = raw_input().strip().split(' ')
        roads.append((int(city_1), int(city_2)))
    if x <= y:
        print n * x
        continue
    graph = defaultdict(set)
    for (u, v) in roads:
        graph[u].add(v)
        graph[v].add(u)
    unseen = set(range(1, n+1))
    count = 0
    while len(unseen):
        comp = component(graph, list(unseen)[0])
        unseen = unseen - comp
        count += 1
    print count * x + (n - count) * y


texts:
This is my prime number checker in C++.  I know that calculating the square root of a number can be very costly, so I don't do it unless the number is larger than 10k, where we would have to check 2450 extra values \$5k-\sqrt{10k}\over2\$.

void primeChecker(std::vector<int> &primes, int val)
{
    int max = val > 10000 ? sqrt(val) : val / 2;
    for (int i = 0; primes[i] <= max; i++)
    {
        if (val % primes[i] == 0)
        {
            return;
        }
    }
    primes.push_back(val);
    std::cout << val << std::endl;
}

Running it like this, it takes a few seconds to calculate the top 1,000,000 primes:

int main()
{
    std::vector<int> primes;
    primes.push_back(2);

    for (int i = 3; i < 1000000; i+=2)
    {
        primeChecker(primes, i);
    }

    return 0;
}

Am I breaking any coding standards, and are there any ways to improve this?


texts: Chrono-like clock with different epoch (from 1.1. 2000)

texts:
The following will by my simple helper, that should behave just like std::chrono::system_clock but with the epoch being 1.1. 2000, that I can easily cast durations to seconds (or milliseconds or centiseconds) and store them in some records (originated from small devices).

It all started with one constexpr:

/// 1.1.2000 0:00
    static constexpr time_point<system_clock> epoch
      = time_point<system_clock>(seconds(946681200))

Which helped me to get e.g. milliseconds from 1.1.2000 like this:

duration_cast<milliseconds>( system_clock::now() - epoch ).count()

The problem is, that there is no contract / specification what is the epoch, but usually is 1.1. 1970.

(I have once selected 1.1. 2000 because of RTCs in units and designed the firmware to work until 1.1. 2100 when I will probably be dead already or very very old man and won't have to care... record size and amount of data transmitted was more important at the time I have designed the protocol.)

(There are some using std::chrono::system_clock and such inside namespace firda in that header)

#include "basics.hpp"
using namespace firda;

/// Clock with altered epoch
template<class Clock = system_clock
  , typename Clock::rep Epoch = 946681200>
  struct adapted_clock {

    using rep        = typename Clock::rep;
    using period     = typename Clock::period;
    using duration   = typename Clock::duration;
    using time_point = typename firda::time_point<adapted_clock>;

    static constexpr bool is_steady
      = Clock::is_steady;
    static constexpr typename Clock::time_point epoch
      = typename Clock::time_point(seconds(Epoch));

    static time_point now() {
        return time_point(Clock::now() - epoch);
    }

    static time_t to_time_t(const time_point& t) {
        return Clock::to_time_t(epoch + t.time_since_epoch());
    }

    static time_point from_time_t(time_t t) {
        return time_point(Clock::from_time_t(t) - epoch);
    }
};

using y2k_clock = adapted_clock<>;

int main() {
    auto now1 = system_clock::now();
    auto now2 = y2k_clock::now();
    cout << "now1.count: " << duration_cast<seconds>(now1
      .time_since_epoch()).count() << '\n';
    cout << "now2.count: " << duration_cast<seconds>(now2
      .time_since_epoch()).count() << '\n';
    time_t time1 = system_clock::to_time_t(now1);
    time_t time2 = y2k_clock::to_time_t(now2);
    cout << "time1: " << std::ctime(&time1) << '\n';
    cout << "time2: " << std::ctime(&time2) << '\n';
}


texts: Expanding a working query without adding multiple join statements?

texts:
I have the following tables set up:

t_users table:

|----------------------------------|
|uid | name   | email              |
|----------------------------------|
|1   | Maria  | maria@example.com  |
|2   | George | george@example.com |
|----------------------------------|

t_settings table:

|---------------------------------|
|t_sid | name     | default_value |
|---------------------------------|
|1     | uicolour | #f00          |
|2     | language | en            |
|---------------------------------|

t_users_settings table:

|--------------------|
|uid | t_sid | value |
|--------------------|
|2   | 1     | #000  |
|1   | 2     | es    |
|--------------------|

What I want, is for each user, to be able to pull all of their custom settings, and also pull the default settings for anything that they haven't changed. I have the following query that works:

SELECT t_users.*, t_users_settings.*, t_settings.*
FROM t_users
LEFT JOIN t_users_settings ON t_users.uid = t_users_settings.t_uid
LEFT JOIN t_settings ON t_settings.t_sid != t_users_settings.t_sid
WHERE t_users_settings.t_sid IS NOT NULL
AND t_users_settings.t_uid IS NOT NULL
AND t_users.uid = '<input user id here>';

However, it appears that if I add more settings (Such as country), I then have to add another JOIN and AND statement. I think there is something missing something in the setup,
or I'm just not familiar enough with MySQL to format the query correctly.

Little help?


texts: Is it an anti-pattern to let ViewModel fill itself from a domain object?

texts:
Let's say you have a Employees table mapped to a Employee class. Now you want to code a Edit page for general information. You need a ViewModel with all the properties you need to build the page, so you create EditEmployeeViewModel. Then you make your action EditEmployee and your view EditEmployee.

So far so good, but as you add more and more properties, all the code to fill your ViewModel ends up in your controller and as your edit page grows, your controller becomes more and more messy. Specially when your ViewModel starts depending on multiple models and/or lists. You also get the same problem when you get the data back; you have to update all the properties of entities involved in the model.

So my question is: Is it an anti-pattern or a bad practice to let the ViewModel map itself from the domain layer object(s) passed in the constructor or a method? If so, what would be a cleaner approach?

public class EmployeesController : Controller
{
    public ActionResult EditEmployee(int id)
    {
        var employee = repo.GetEmployee(id);
        return View(new EditEmployeeViewModel
        {
            Id = employee.Id,
            FirstName = employee.FirstName,
            LastName = employee.LastName
        });
    }
}

public class Employee
{
    public int Id { get; set; }
    public int FirstName { get; set; }
    public int LastName { get; set; }
    public int EmployeeNumber { get; set; }
}

public class EditEmployeeViewModel
{
    public int Id { get; set; }

    [StringLength(20, MinimumLength = 2)]
    public string FirstName { get; set; }

    [StringLength(20, MinimumLength = 2)]
    public string LastName { get; set; }
}

Example with the mapping in the ViewModel

public class EditEmployeeViewModel
{
    public int Id { get; set; }

    [StringLength(20, MinimumLength = 2)]
    public string FirstName { get; set; }

    [StringLength(20, MinimumLength = 2)]
    public string LastName { get; set; }

    public EditEmployeeViewModel(Employee employee)
    {
        Id = employee.Id;
        FirstName = employee.FirstName;
        LastName = employee.LastName;
    }

    public Employee UpdateModel(Employee employee)
    {
        employee.Id = Id;
        employee.FirstName = FirstName;
        employee.LastName = LastName;
        return employee;
    }
}


texts: Verify a subnet mask for validity in Python

texts:
I've written a small Python function to check whether a string is a valid IPv4 subnet mask.

It works but maybe it's too convoluted and terse? Or maybe it could be improved / optimised / rewritten in a cleverer way than just to check 1's in a string?..

IsIPv4Address is another function of mine (EDIT 1: added it into the question).
I specifically don't want to use any libraries / external functions as this is rather a study in Python :)

def IsIPv4Address(ipAdd):
    """Validate an IPv4 address"""
    octets = ipAdd.split(".")
    if len(octets) != 4:
        return False
    for octet in octets:
        if not IsInteger(octet):
            return False
        if int(octet) > 255 or int(octet) < 0:
            return False

    return True

def IsIPv4Mask(ipMask):
    """Validate an IPv4 subnet mask"""

    # Each mask looks like an IPv4 address and must pass the checks
    if not IsIPv4Address(ipMask):
        return False

    ipMaskBinary = ""
    ipMaskBinary = ipMaskBinary.join([bin(int(oct))[2:] for oct in ipMask.split(".")])

    isBitZero = ipMask[0] == "0"
    for bit in ipMaskBinary[1:]:
        if bit == "1" and isBitZero:
                return False

        if bit == "0":
            isBitZero = True

    return True


texts:
I've made a code that does exactly what https://sapin.herokuapp.com/?n=5 would do.
Here's my code ;
import sys

def firtree(tree_size):
    fir = []
    width = 1
    minus = 2
    foot_width = 1
    for i in range(1,tree_size+1):
        for j in range(1,i+4):
            fir.append("*"*width)
            width = width + 2
        if i % 2 == 0:
            minus += 1
        width -= minus
        if i % 2 == 0:
            foot_width += 2
    fir = [" "*(int((len(fir[-1]))/2)-int(len(i)/2))+i for i in fir]
    for i in fir:
        print(i)
    for i in range(1,tree_size+1):
        print(" "*int((len(fir[-1]))/2-int(foot_width/2))+"|"*foot_width)

size = int(sys.argv[1])
firtree(size)

How can I improve it ?


texts: Getting JSON with jQuery, creating a function that displays the data from two separate feeds

texts:
I have written my first JavaScript program from scratch and am looking for advice to check whether it is efficient and effective or how it could be improved.

        var apiURL = 'https://services.domain.com';

    function dataPlanOutput(countryCode) {
        document.getElementById("dataplan_list").innerHTML = "";
        network_url = apiURL + '/api/v4/countries/' + countryCode ;
        network_new_url = "http://cors.io/?" + network_url;
        $.getJSON(network_new_url, function (networkGroup) {
            $.each(networkGroup.list, function (i, list) {
                var countryName = list.region;
                var networkGroupId = list.networkGroupId;

                function myDataPlan(networkGroupId, countryCode) {
                    data_url = apiURL + '/api/v4/networkGroups/' + networkGroupId + '/plansExt?countryCode=' + countryCode;
                    data_new_url = "http://cors.io/?" + data_url;
                    $.getJSON(data_new_url, function (dataPlan) {
                        $.each(dataPlan.list, function (i, list) {
                            //Price
                            content = '
';
                            var currencyLetter = list.currency;
                            if (currencyLetter == 'USD') {
                                var curencySymbol = currencyLetter.replace("USD", "$");
                            }
                            else if (currencyLetter == 'GBP') {
                                var curencySymbol = currencyLetter.replace("GBP", "£");
                            }
                            else if (currencyLetter == 'JPY') {
                                var curencySymbol = currencyLetter.replace("JPY", "¥");
                            }
                            else if (currencyLetter == 'EUR') {
                                var curencySymbol = currencyLetter.replace("EUR", "€");
                            };
                            content += '' + curencySymbol + list.price + '	';
                            //Data Limits
                            var dataLimit;
                            if (list.dataUnlimited) {
                                dataLimit = 'Unlimited';
                            }
                            else {
                                var dataLimitInKB = list.dataLimitInKB;
                                if ((dataLimitInKB / (1024.0 * 1024.0)) >= 1.0) {
                                    var measure = " GB";
                                    var data = dataLimitInKB / ((1024.0) * (1024.0));
                                }
                                else if (dataLimitInKB / 1024.0 >= 1.0) {
                                    var measure = " MB";
                                    var data = dataLimitInKB / 1024.0;
                                }
                                data = Math.round(data * 100) / 100;
                                dataLimit = data + measure;
                            }
                            content += '' + dataLimit + '	';
                            //Data Length
                            content += '' + list.validityPeriodInDays + '&nbsp;Days	';
                            content += '
';
                            $(content).appendTo("#dataplan_list");
                        });
                    });
                }
                myDataPlan(networkGroupId, countryCode);
                document.getElementById('dataplan_list').innerHTML += '
' + countryName + '
';
            });
        });
    }


texts: Chaining 3 dependent HTTP request subscriptions one, which is polling

texts:
Here is a function that triggers after selecting from a dropdown to choose the floor. As you can see, there are 3 levels of API calls (regular HTTP GET requests with JSON responses) that chain together. The first 2 are regular requests and the 3rd one polls. How can I write this in a better way that utilizes RXJS and observable functions?

onChange(floor)
 {
    this.selectedFloor = floor;
    this.floorService.getRoomsInFloor(floor).subscribe((rooms:IRoom[])=>{
        rooms.forEach((room:IRoom)=>{
            this.floorService.getDeviceInRoom(room.roomId).subscribe((device:IDevice)=>{
                this.floorService.getLatestStatusOfDeviceInRoom(device.deviceId).subscribe((status:IStatus)=>{
                    if(status)
                    {
                    status.occupied == "true"? this.rooms[room.roomId][4] = "red" : this.rooms[room.roomId][4] = "green";

                    }

                    this.renderRooms();
                });
            });
        });
    });
 }

getRoomsInFloor(floorid)
{

    return this.http.get(`example.com/floor/${floorid}/rooms`).map(res => res.json()).catch(this._serverError)
}

getDeviceInRoom(roomid)
{
    return this.http.get(`example.com/devices/${roomid}`).map(res => res.json()).catch(this._serverError)

}

getLatestStatusOfDeviceInRoom(deviceid)
{
    return Observable.timer(0,2000).switchMap(()=> this.http.get(`example.com/roomPresences/${deviceid}/latest`).map(res => res.json()).catch(this._serverError));
}


texts:
I have this ordered list of datetimes that comprises of 30 minute slots:

availability = [
    datetime.datetime(2010, 1, 1, 9, 0),
    datetime.datetime(2010, 1, 1, 9, 30),
    datetime.datetime(2010, 1, 1, 10, 0),
    datetime.datetime(2010, 1, 1, 10, 30),
    datetime.datetime(2010, 1, 1, 13, 0), # gap
    datetime.datetime(2010, 1, 1, 13, 30),
    datetime.datetime(2010, 1, 1, 15, 30), # gap
    datetime.datetime(2010, 1, 1, 16, 0),
    datetime.datetime(2010, 1, 1, 16, 30)
]

And I would to split the ones with time gaps in between into a dictionary with start and end values, like so:

[
    {'start': datetime.datetime(2010, 1, 1, 9, 0), 'end': datetime.datetime(2010, 1, 1, 10, 30)},
    {'start': datetime.datetime(2010, 1, 1, 13, 0), 'end': datetime.datetime(2010, 1, 1, 13, 30)},
    {'start': datetime.datetime(2010, 1, 1, 15, 30), 'end': datetime.datetime(2010, 1, 1, 16, 30)}
]

So I threw this snippet of code together that does exactly that.

result = []
row = {}
for index, date in enumerate(available):
    exists = False
    if not row:
        row['start'] = date
    try:
        if date + timedelta(minutes = 30) != available[index + 1]:
            exists = True
    except IndexError:
        exists = True
    if exists:
        row['end'] = date
        result.append(row)
        row = {}

But needless to say this is super ugly and there just has to be a better, shorter and more elegant way to do this.


texts: Sudoku solution without the use of classes

texts:
A Sudoku puzzle is a 9 × 9 grid with some numbers between 1 and 9 in
  it, that has to be filled in so that

  every row,
  every column, and
  each of the nine 3 × 3 blocks

  contain all the numbers from 1 to 9.

  For example the following matrix is not a valid solution of a Sudoku
  puzzle: the fourth column contains two 7's, block 4 contains also two
  7's, and block 5 contains two 9's (there are more reasons why this
  matrix is not a valid solution but we will not list all them):

1 8 2 | 3 5 9 | 4 7 6
7 5 3 | 2 6 4 | 9 8 1
6 4 9 | 7 1 8 | 2 5 3
------+-------+------
2 6 4 | 9 7 3 | 8 1 5
9 1 7 | 4 8 5 | 9 3 2
8 3 5 | 7 2 1 | 7 4 9
------+-------+------
5 9 6 | 1 4 7 | 3 2 8
4 2 8 | 5 3 6 | 1 9 7
3 7 1 | 8 9 2 | 5 6 4

  Write a program to determine if a given 9 × 9 matrix is the solution
  of a Sudoku puzzle.

  In the example above we have marked the limits of the 9 blocks to make
  the example easier to follow, but the delimiter characters do not
  appear in the input.

Important: the only structures I can use are structs and the defined in the vector library. I cannot use classes (as I have not studied them yet).

#include <iostream>
#include <vector>
//I know I should not include std
//but I am restricted to do so.
using namespace std;

const int sdk_size = 9;
const int sdk_blocks = 3;

typedef vector<int> permutation;
typedef vector<permutation> sdk;

sdk read_sdk()
{
  sdk v(sdk_size, permutation(sdk_size));
  for (int y = 0; y < sdk_size; ++y) {
      for (int x = 0; x < sdk_size; ++x) {
        cin >> v[y][x];
      }
  }
  return v;
}

//Checks if a permutation *is* a permutation, i.e.
//it contains every number in 1..sdk_size once and only once.
bool is_permutation(const permutation& per)
{
  vector<bool> used(sdk_size + 1, false);
  for (int i = 0; i < sdk_size; ++i) {
    if (per[i] < 1 or per[i] > sdk_size or used[per[i]]) {
      return false;
    }
    used[per[i]] = true;
  }
  return true;
}

bool has_valid_rows(const sdk& v)
{
  for (int y = 0; y < sdk_size; ++y) {
    if (not is_permutation(v[y])) return false;
  }
  return true;
}

bool has_valid_cols(const sdk& v)
{
  for (int x = 0; x < sdk_size; ++x) {
    permutation col(sdk_size);
    for (int y = 0; y < sdk_size; ++y) {
      col[y] = v[y][x];
    }
    if (not is_permutation(col)) return false;
  }
  return true;
}

bool has_valid_blocks(const sdk& v)
{
  //A block is a submatrice of v with start point (y0,x0)
  //and height and width of sdk_size.
  for (int y_0 = 0; y_0 < sdk_size; y_0 += sdk_blocks) {
    for (int x_0 = 0; x_0 < sdk_size; x_0 += sdk_blocks) {
      permutation block;
      for (int dy = 0; dy < sdk_blocks; ++dy) {
        for (int dx = 0; dx < sdk_blocks; ++dx) {
          block.push_back(v[y_0+dy][x_0+dx]);
        }
      }
      if (not is_permutation(block)) return false;
    }
  }
  return true;
}

bool is_valid_sdk(const sdk& v)
{
  if (not has_valid_rows(v))   return false;
  if (not has_valid_cols(v))   return false;
  if (not has_valid_blocks(v)) return false;
  return true;
}

int main()
{
  sdk v = read_sdk();
  if (is_valid_sdk(v)) {
    cout << "The sudoku is well-formed" << endl;
  } else {
    cout << "The sudoku is not well-formed" << endl;
  }
}


texts: Longest Substring without Repeating Characters Problem - Kotlin Recursion

texts:
I am practicing coding questions on leetcode. I have been an OOP my whole career, and I am trying to wade into the dark abyss that is functional programming. So I am trying to do things purely functional, e.g. using recursion to try to get to the answer. The problem statement is this: Given a string, find the length of the longest substring without repeating characters.

Sorry for asking literally this leetcode question that everybody else is asking :D

I have coded up this solution -

class Solution {
    fun lengthOfLongestSubstring(str: String): Int {
        return when {
            str.length == 1 -> 1
            str.isEmpty() -> 0
            else -> helper(str, 0, 1, 0)
        }
    }

    private tailrec fun helper(str: String, leftIndex: Int, rightIndex: Int, max: Int): Int {
        return when {
            rightIndex >= str.length+1 -> max
            rightIndex >= str.length && isDistinct(str.substring(leftIndex)) ->
                helper(str, leftIndex, rightIndex + 1, max(rightIndex - leftIndex, max))
            isDistinct(str.substring(leftIndex, rightIndex)) ->
                helper(str, leftIndex, rightIndex + 1, max(rightIndex - leftIndex, max))
            else -> helper(str, leftIndex + 1, leftIndex + max + 1, max)
        }
    }

    private fun isDistinct(substring: String): Boolean {
        return substring.toList().distinct().size == substring.length
    }
}

I have a couple specific questions -
I am using the sliding window approach, is that appropriate in a functional setting? If not, what is a better approach functionally, speaking.

Is there redundancy in my recursion function that I can get rid of?

What things can I do to improve the legibility of the function? Clean code is always best!

What further steps can I take to optimize the solution? Currently this solution is only faster than 10% of other solutions (though those are likely imperative solutions)

Any other tips you can provide outside of the bounds of my question that can help would be awesome. I am also brand new to kotlin programming.

I don't necessarily hate this solution, but I'm sure it can be better. Please advise.


texts:
What would be the "correct" way of transforming an array of objects into an object that contains an array?

Suppose I have this array that contains objects:

const paintings = [
  { painting: "Mona Lisa" },
  { painting: "The Starry Night" },
  { painting: "The Last Supper" },
  { painting: "Girl with a Pearl Earring" },
  { painting: "American Gothic" },
  { painting: "The Night Watch" }
];

And I would like to transform it into this:

const paintings = {
  artworks: [
    "Mona Lisa",
    "The Starry Night",
    "The Last Supper",
    "Girl with a Pearl Earring",
    "American Gothic",
    "The Night Watch"
  ]
};

I know that I can accomplish this with two nested loops like below, but is there a more "elegant" way of doing it? I think that these tasks are nowadays usually solved using map or reduce functions but I find them a bit confusing to use. I would like to learn though!

const paintingsNew = {
  artworks: []
};

for (const painting of paintings) {
  for (const val of Object.values(painting).values()) {
    paintingsNew.artworks.push(val);
  }
}

console.log(paintingsNew);

// { artworks:
//    [ 'Mona Lisa',
//      'The Starry Night',
//      'The Last Supper',
//      'Girl with a Pearl Earring',
//      'American Gothic',
//      'The Night Watch' ] }


texts: Should I add the "fetch_group" method to my user class or should I create a separate class for group

texts:
I have a table of users, where each user has a group (or multiple groups) he/she is part of.

Currently I'm handling the users group via a Users class:

<?php
/**
 *
 *  User (class) Model: Handles users (not system users).
 *
 */
class User{

/*=================================
=            Variables            =
=================================*/

    # Database instance
    private $db;

    # Users ID
    public $user_id;

    # User Realm
    public $realm;

    # User Name
    public $user_name;

    # User display name
    public $display_name;

    # User creation
    public $created;

    # User last seen
    public $last_seen;

    # Is user deleted?
    public $deleted;

    # Is user ignored?
    public $ignored;

    # Is user blacklisted
    public $blacklisted;

    # Is user whitelisted
    public $whitelisted;

    # Is user blocked
    public $blocked;

    # Is user filtered
    public $filtered;

    # User Group
    public $group = array();

/*===============================
=            Methods            =
================================*/

    /**
     *
     *  Constructor
     *  @param      $user_id    Init        User id.
     *  @throws                 Object      User object of a single user.
     *
     */
    public function __construct($user_id) {

        # Get database instance
        $this->db           = Database::getInstance();

        # If user_id isn't passed
        if ( $user_id ) {

            # Get this user by id
            $this->get_user_by_id($user_id);
        }
    }

    /**
     *
     *  Get user by id
     *  @param      $id     Init        User id
     *  @throws             Object      Returns the object with data applied.
     *
     */
    private function get_user_by_id($id)
    {
        if ($id) {

            # Search for the user in the Database 'users' table.
            $data   = $this->db->row("SELECT user_id, realm, user_name, display_name, created, last_seen, deleted, ignored, blacklisted, whitelisted, blocked, filtered FROM users WHERE user_id = :id", array('id' => $id));

            # If there is a result
            if ( $data ) {

                # Get group/s
                // -- Get Group method  --

                # Set data in this user object
                $this->data($data);

                return $this;

            } else { return false; }

        } else {
            return false;
        }
    }

    /**
     *
     *  Insert Data to this object
     *  @param      $data       Array       Gets a result array of user data
     *
     */
    private function data($data)
    {
        # Set data for this user object
        $this->user_id      = $data['user_id'];
        $this->realm        = $data['realm'];
        $this->user_name    = $data['user_name'];
        $this->display_name = $data['display_name'];
        $this->created      = $data['created'];
        $this->last_login   = $data['last_seen'];
        $this->deleted      = $data['deleted'];
        $this->ignored      = $data['ignored'];
        $this->blacklisted  = $data['blacklisted'];
        $this->whitelisted  = $data['whitelisted'];
        $this->blocked      = $data['blocked'];
        $this->filtered     = $data['filtered'];
        // $this->group         = $data['group'];
    }

I have just added the group variable, and not sure if it's "good practice" to add a fetch_group_by_user_id() method (separate table in my DB), or create a new group object, and use it inside my User class.

My user class is pasted ^

Please review my User class code and update me if you think it can be written better, and please tell me what is best to fetch the group.


texts: "Longest Collatz sequence" in C slower than in Python 3

texts:
This tight-looped memoization-less C solution to Project Euler's problem 14 seems efficient, but ran much slower than a similarly trivial Python 3 program. For the desired upper of 1000000, the C version ran practically forever, while Python 3 fairly quickly printed the correct result.

#include <stdio.h>

#define upper 1000000

int main() {
    int max = 1;
    int maxl = 1;

    for (int n = 1; n < upper; ++ n) {
        int c = n; // After v5r's answer: Should be `long c = n;`
        int cl = 1;

        while (c != 1) {
            if (c % 2 == 0) {
                c /= 2;
            }
            else {
                c = 3 * c + 1;
            }
            ++ cl;

            if (cl > maxl) {
                max = n;
                maxl = cl;
            }
        }
    }

    printf("%i\n", max);

    return 0;
}

Python 3:

#! /usr/bin/env python3

max = 1
maxl = 1

for n in range(1, 1000000):
    c = n
    cl = 1

    while c != 1:
        if c % 2 == 0:
            c /= 2
        else:
            c = 3 * c + 1
        cl += 1

        if cl > maxl:
            max = n
            maxl = cl

print(max)


texts: Complex reporting query suggestion needed for different approach as per latest Tsql format

texts:
We have recently migrated from SQL Server 2008 R2 to SQL Server 2017 web edition. I am not a SQL developer but enthuses to learn.
Since many of our scrips are of old SQL format, I am searching for some alternative to leverage new T-SQL formats to help optimize the codes.
Below is one example which I believe can be modified using some different approach. It will be helpful for me if someone suggest me some approaches so that I can learn in detail about them.
Below query is for report it uses UNION ALL, the first part fetches data of ID for which payments are done incorrectly marked as 'recoup' and second part fetched data for the same ID it amount of payment required to be done.
SELECT TOP 200 'Recoup',ERH_DOC_DATE,ERH_DOCNO,ERH_RECV_FROM,ERD_BLH_ID,BLD_CODE,A.ERD_ALLOWED_AMT,A.ERD_PAID_INS_AMT
FROM TRN_ERA_HEAD,TRN_ERA_DET A,TRN_BILLING_DET
WHERE ERH_STATUS = 'P' AND ERH_BOOL_INACTIVE = 0 AND A.ERD_BOOL_RECALLED=1 AND
A.ERD_ALLOWED_AMT <> 0 AND A.ERD_PAID_INS_AMT <> 0 AND
ERH_ID = A.ERD_ERH_ID AND
A.ERD_BLD_ID = BLD_ID AND
NOT EXISTS (SELECT B.ERD_ID FROM TRN_ERA_DET B WHERE A.ERD_ERH_ID = B.ERD_ERH_ID AND A.ERD_ID <> B.ERD_ID AND B.ERD_BLD_ID = A.ERD_BLD_ID AND B.ERD_BOOL_RECALLED = 0 AND A.ERD_ALLOWED_AMT = B.ERD_ALLOWED_AMT AND A.ERD_PAID_INS_AMT = B.ERD_PAID_INS_AMT)
AND ERH_DOC_DATE>='01-01-2021' AND ERH_DOC_DATE<='05-31-2021'
UNION ALL
SELECT TOP 200 'Payment',EH1.ERH_DOC_DATE,EH1.ERH_DOCNO, EH1.ERH_RECV_FROM, ED1.ERD_BLH_ID,BD1.BLD_CODE,ED1.ERD_ALLOWED_AMT, ED1.ERD_PAID_INS_AMT FROM
( SELECT ERD_ERH_ID ERDERH_ID, ERD_BLH_ID erdblh_id, a.erd_bld_id bld, A.ERD_ALLOWED_AMT, A.ERD_PAID_INS_AMT FROM TRN_ERA_HEAD,TRN_ERA_DET A,TRN_BILLING_DET WHERE ERH_STATUS = 'P' AND ERH_BOOL_INACTIVE = 0 AND A.ERD_BOOL_RECALLED=1 AND A.ERD_ALLOWED_AMT <> 0 AND A.ERD_PAID_INS_AMT <> 0 AND ERH_ID = A.ERD_ERH_ID AND A.ERD_BLD_ID = BLD_ID AND NOT EXISTS
(SELECT B.ERD_ID FROM TRN_ERA_DET B WHERE A.ERD_ERH_ID = B.ERD_ERH_ID AND A.ERD_ID <> B.ERD_ID AND B.ERD_BLD_ID = A.ERD_BLD_ID AND B.ERD_BOOL_RECALLED = 0 AND A.ERD_ALLOWED_AMT = B.ERD_ALLOWED_AMT AND A.ERD_PAID_INS_AMT = B.ERD_PAID_INS_AMT) AND ERH_DOC_DATE>='01-01-2021'
AND ERH_DOC_DATE<='05-31-2021') AS RECOUPS,
TRN_ERA_HEAD EH1,TRN_ERA_DET ED1, TRN_BILLING_DET BD1 WHERE RECOUPS.ERDERH_ID < ED1.ERD_ERH_ID AND ED1.ERD_BLD_ID = RECOUPS.BLD AND EH1.ERH_ID=ED1.ERD_ERH_ID AND ED1.ERD_BLD_ID=BD1.BLD_ID AND EH1.ERH_TRNTYPE='IN' AND EH1.ERH_STATUS = 'P' AND EH1.ERH_BOOL_INACTIVE = 0 AND ED1.ERD_BOOL_RECALLED=0 AND ED1.ERD_ALLOWED_AMT <> 0 AND ED1.ERD_PAID_INS_AMT <> 0;

Please suggest me some different approaches. Thank you in advance.