texts: Converting to Roman Numeral with Recursive Algorithm

texts:
Summary

I'm getting ready to dive back into a "more proper" project, so I wanted to take a moment to get my TDD hat on before doing so. I decided to tackle this Roman Numeral Kata for practice. The purpose of the function is simply to take in a Long and output a string containing the equivalent Roman Numeral.

I'm confident that it's accurate out to 3999. Beyond that a standard keyboard doesn't quite have the proper characters, so 4000 comes out as MMMM and 14841 comes out as MMMMMMMMMMMMMMDCCCXLI. Unit Tests can be found in this Gist if you're interested.

I didn't plan on doing this recursively. It just kind of came out naturally after a few refactorings. I did at one point extract a few functions to reduce the redundancy in the code below, but it really felt like it obfuscated the algorithm and hurt the clarity.

Questions

Was the recursive solution a good way to go? I feel like it's clear, but I have this nagging feeling there might be a better algorithm. (One that may involve determining decimal places perhaps?)
Is it dry enough as it is, or should I have extracted a few functions like this.

Private Function UpFrom(ByVal number As Long, ByVal from As Long) As String
    UpFrom = ConvertToRomanNumeral(from) & ConvertToRomanNumeral(number - from)
End Function

Should I have raised an error after reaching 4000, instead of returning "numeral like" strings?
Did I do anything else stupid or dirty? Anything you'd do differently?

Numbers.bas

Public Function ConvertToRomanNumeral(ByVal number As Long) As String
    Dim result As String

    Select Case number
        Case 1
            result = "I"
        Case 2 To 3
            result = ConvertToRomanNumeral(number - 1) & ConvertToRomanNumeral(1)
        Case 4
            result = ConvertToRomanNumeral(1) & ConvertToRomanNumeral(5)
        Case 5
            result = "V"
        Case 6 To 8
            result = ConvertToRomanNumeral(5) & ConvertToRomanNumeral(number - 5)
        Case 9
            result = ConvertToRomanNumeral(1) & ConvertToRomanNumeral(10)
        Case 10
            result = "X"
        Case 11 To 39
            result = ConvertToRomanNumeral(10) & ConvertToRomanNumeral(number - 10)
        Case 40
            result = ConvertToRomanNumeral(10) & ConvertToRomanNumeral(50)
        Case 41 To 49
            result = ConvertToRomanNumeral(40) & ConvertToRomanNumeral(number - 40)
        Case 50
            result = "L"
        Case 51 To 89
            result = ConvertToRomanNumeral(50) & ConvertToRomanNumeral(number - 50)
        Case 90
            result = ConvertToRomanNumeral(10) & ConvertToRomanNumeral(100)
        Case 91 To 99
            result = ConvertToRomanNumeral(90) & ConvertToRomanNumeral(number - 90)
        Case 100
            result = "C"
        Case 101 To 399
            result = ConvertToRomanNumeral(100) & ConvertToRomanNumeral(number - 100)
        Case 400
            result = ConvertToRomanNumeral(100) & ConvertToRomanNumeral(500)
        Case 401 To 499
            result = ConvertToRomanNumeral(400) & ConvertToRomanNumeral(number - 400)
        Case 500
            result = "D"
        Case 501 To 899
            result = ConvertToRomanNumeral(500) & ConvertToRomanNumeral(number - 500)
        Case 900
            result = ConvertToRomanNumeral(100) & ConvertToRomanNumeral(1000)
        Case 901 To 999
            result = ConvertToRomanNumeral(900) & ConvertToRomanNumeral(number - 900)
        Case 1000
            result = "M"
        Case Else
            result = ConvertToRomanNumeral(1000) & ConvertToRomanNumeral(number - 1000)
    End Select

    ConvertToRomanNumeral = result
End Function


texts:
I have a case class that is recursive and looks like this:

case class Config(name: String, isEnabled: Boolean, elems: Map[String, MyCase])

case class MyCase(
  id: String,
  isActive: Boolean,
  elems: Option[Map[String, MyCase]])

Where the Config contains the id of the MyCase entries contained as a Map. I have to iterate over this structure and come up with a Map that contains the parent child relations. Say for example., if I have the Config class represented as below (for simplicity, I have just given the id's):

Config(Map("5" -> myCase1, "6" -> myCase2))

5 - Config
 1
  1
  2
 2
6
 1

where id's 5 and 6 are top level entries which in turn has a recursive structure. I have to now come up with a Map that contains the parent child relationship for the id's. So for the case above, I will expect a Map that looks like:

Map(
 "5" -> Seq("5.1"),
 "5.1" -> Seq("5.1.1", "5.1.2"),
 "5.1.1" -> Seq.empty[String],
 "5.1.2" -> Seq.empty[String],
 "6" -> Seq("6.1"),
 "6.1" -> Seq.empty[String]
)

Notice how I append the parent id to the child.

Given a Seq of such Configs,

val configs = Seq(Config1, Config2)

this is what I have come up with:

def relationsFor(config: Config): Map[String, Seq[String]] = {

    def prepareChildren(parentId: String, acc: Map[String, Seq[String]], subElems: Map[String, MyCase]): Map[String, Seq[String]] = {
      subElems.collect {
        case (id, elem) if elem.isActive =>
          val newAcc = acc ++ Map(parentId -> subElems.keys.map(subElemId => s"$parentId.$subElemId").toSeq)
          if (elem.elems.isDefined) {
            val newParentId = s"$parentId.$id"
            val newAcc1 = newAcc ++ Map(s"$parentId.$id" -> elem.elems.get.keys.map(subElemId => s"$newParentId.$subElemId").toSeq)
            prepareChildren(s"$parentId.$id", newAcc1, elem.elems.get)
          } else {
            acc ++ Map(s"$parentId.$id" -> Seq.empty[String])
          }
      }
    }.flatten.toMap

    configs.collect {
      case config if config.isEnabled =>
        config.elems.collect {
          case (parentId, elemCase) if elemCase.elems.isDefined =>
            prepareChildren(parentId, Map.empty[String, Seq[String]], elemCase.elems.get)
          case (parentId, _) =>
            Map(parentId -> Seq.empty[String])
        }
    }.flatten.flatten.toMap
  }

Could this be simplified ? I have already tested this and it works as expected, but I find it a little bit hard to understand. Can this be made much more elegant? I mean can the relationsFor method be made more elegant ?


texts: Uploading photos: Domain Model and Repository classes

texts:
In the database, I have a table with name photographs with the following columns:

id
filename
type
size
caption

I want to create two classes - one is Domain Model named photo.php and the other one is a Repository class (photorepository.php).

So, I started like this:

photo.php:

class Photo
{
    private $id;
    private $filename;
    private $type;
    private $size;
    private $caption;

    public function __construct($filename, $type, $size, $caption, $id = 0)
    {
        $this->id = $id;
        $this->filename = $filename;
        $this->type = $type;
        $this->size = $size;
        $this->caption = $caption;
    }

   // setters & getters

}

Repository class (photorepository.php):

class PhotographRepository
{
    private $connection;
    private $statements = [];

    public function __construct(PDO $connection)
    {
        $this->connection = $connection;
    }

    public function create($file, $caption) {
        if(!$file || empty($file) || !is_array($file)) {
            return false;
        } elseif($file['error'] != 0) {
            return false;
        } else {
            $temp_path = $file['tmp_name'];
            $filename = basename($file['name']);
            $type = $file['type'];
            $size = $file['size'];
            if(empty($filename) || empty($temp_path)) {
                return false;
            }
            $target_path = __DIR__ . "/../public/images/" . $filename;
            if (file_exists($target_path)) {
                return false;
            }
            if(move_uploaded_file($this->temp_path, $target_path)) {

                $photo = new Photograph($filename, $type, $size, $caption);

                if (!isset($this->statements[__METHOD__])) {
                    $this->statements = $this->connection->prepare("INSERT INTO photographs (filename, type, size, caption) VALUES (:filename, :type, :size, :caption)");
                }
                $stmt = $this->statements[__METHOD__];
                if ($stmt->execute([':filename'=>$photo->getFilename(), ':type'=>$photo->getType(), ':size'=>$photo->getSize()])) {
                    $photo->setId($this->connection->lastInsertId());
                    $stmt->closeCursor();
                    unset($this->temp_path);
                    return true;
                } else {
                    $stmt->closeCursor();
                    return false;
                }
            }
        }
    }

}

$file is $_FILES["input_name"]. Is this the good way of doing it?


texts: Using delegates to communicate between forms and networkcommunicator class

texts:
I have multiple forms, each of which would like to send message through the network, using my NetworkCommunicator class's SendMessage method.

The solution I described here works, however it is ugly, and bludgeons some of the main concepts of OOP paradigm. What I'm looking for (and I'm open to any suggestions) is basically to achieve the same goal but in a more elegant, and OOP conforming solution. (maybe by events?)

I'm using more than these forms, but for the example, these seemed to be enough.

//using statements
namespace examplespace
{
 public delegate void ImprovedSenderDelegate(string message);

 public class LoginForm :Form
  {
   private  NetworkCommunicator ncom = new NetworkCommunicator();
   public Ncom
   {
    get { return ncom; }
   }

   private void Login()
   {
    MainForm mf = new MainForm();
    mf.Owner = this;
    //other things i do etc.
    this.Hide();
    mf.Show();
   }
  }//endofLoginForm

 public class MainForm :Form
 {
  public ImprovedSenderDelegate ISD;

  private void Load ()
  {
   (this.Owner as LoginForm).NCom.SubscribeToSendMessage(this);
  }

  private void I_Want_To_send_A_Message(string message)
  {
   ISD(string);
  }
 }//endofMainForm

 public class NetworkCommunicator
  {
   public void SubscribeToSendMessage(object sender)
    {
     if (sender is MainForm)
     {

         (sender as MainForm).ISD += new ImprovedSenderDelegate(SendMessage);
     }
    }

   private void SendMessage(string message)
    {/*magic*/}
  }/endofNetworkCommunicator
}


texts: Remove vulnerabilities from query on public website

texts:
I think that the following query is preventing against SQL injection, but what other measures do I need to take to ensure my queries are 100% safe from any malicious attacks?

$statement = $db->prepare(
    "INSERT INTO blogs (blogtitle, blogdesc, coverimage, userID, frontpage, tags)
    VALUES (:buildtitle, :builddesc, :buildcover, :userid, :frontpage, :addtags)"
);

if ($statement->execute(array(
    ':buildtitle' => $_POST['addbuildtitle'],
    ':builddesc' => $_POST['addbuilddesc'],
    ':buildcover' => $imagepath,
    ':userid' => $_POST['adduserid'],
    ':frontpage' => $frontpage,
    ':addtags' => $_POST['addtags']))
);


texts: Powershell script to iterate through folder and restore SQL backups

texts:
I am working on a PowerShell script which will loop through a directory containing SQL Server database backup .bak files; move the files to a different location; restore each of those files to the local SQL instance using OSQL.exe; output the SQL output to a log file.

This works OK, but I am willing to improve it.

$sourceBackupDirectory = "C:\FTP"
$sqlDatabaseLocation = "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\"
$backupsLocation = "C:\DatabaseRestore\"

Get-ChildItem $sourceBackupDirectory -Filter "*.bak" -Recurse | Move-Item -Destination $backupsLocation #move files
$backupsLocationFiles = Get-ChildItem $backupsLocation -Filter "*.bak" #load files into array

$todayUK = Get-Date -format yyyyMMdd
$logsFolder = "LogFiles\"
$logFile = $backupsLocation + $logsFolder + $todayUK + ".txt"

foreach ($file in $backupsLocationFiles)
{
    $filePath = $backupsLocation + $file
    $file = [io.path]::GetFileNameWithoutExtension($file)
    #$filePath
    #$file

    RestoreDB $file $filePath
}

function global:RestoreDB ([string] $newDBName, [string] $backupFilePath)
{
    [string] $dbCommand = "RESTORE DATABASE [$newDBName] " +
    "FROM    DISK = N'$backupFilePath' " +
    "WITH    FILE = 1, " +
    "MOVE N'$newDBName' " +
    "TO N'$sqlDatabaseLocation" + "$newDBName.mdf', " +
    "MOVE N'$newDBName" + "_log' " +
    "TO N'$sqlDatabaseLocation" + "$newDBName" + "_log.ldf', " +
    "NOUNLOAD, REPLACE, STATS = 5"
    Write-Host $dbCommand

    OSQL.EXE -E -Q $dbCommand >> $logFile #this ouputs the SQL output into a logfile.
}


texts:
Background

A VSCode extension that uses Chance.JS to generate random data types.

Concerns

My main concern is that there are 4 levels of function references that feels like a hack. From registerCommand → insertFunc* → randomFunc* → processSelection.
If the code is sensible TypeScript/JavaScript

The Code

export function activate(context: vscode.ExtensionContext) {
    context.subscriptions.push(vscode.commands.registerCommand('randomeverything.int', insertRandomInt));
    context.subscriptions.push(vscode.commands.registerCommand('randomeverything.letters', insertRandomLetters));
    context.subscriptions.push(vscode.commands.registerCommand('randomeverything.lettersAndNumbers', insertRandomLettersAndNumbers));
    context.subscriptions.push(vscode.commands.registerCommand('randomeverything.iPv4Address', insertRandomIPv4Address));
    context.subscriptions.push(vscode.commands.registerCommand('randomeverything.iPV6Address', insertRandomIPV6Address));
    /* More commands... */
}

function insertRandomInt(): void {

    var max:number;
    var min:number;

    Window.showInputBox({prompt: "Please enter [MIN-MAX]", value:"1-100"}).then(
        function(txt){
            if(txt){
                var args = txt.split("-");

                min = Number.parseInt(args[0]);
                max = Number.parseInt(args[1]);

                if(args.length != 2 || isNaN(min) || isNaN(max))
                {
                    Window.showErrorMessage("Invalid format.");
                    return;
                }
                processSelection(randomIntString, [min, max]);
            }
    });

}

function insertRandomLetters(): void {
    processSelection(randomLetters, []);
}

function insertRandomLettersAndNumbers(): void {
    processSelection(randomLettersAndNumbers, []);
}

function insertRandomIPv4Address(): void {
    processSelection(randomIP, ['ipv4']);
}

function insertRandomIPV6Address(): void {
    processSelection(randomIP, ['ipv6']);
}
/* More inserters... */

/**
 * Chance.js Wrappers
 */
function randomIntString(min, max): string {
    var chance = require('chance').Chance();
    var randomVar: Number = chance.integer({
      min: min,
      max: max
    });

    return randomVar.toString();
}

function randomIP(option?:string): string{
    var chance = require('chance').Chance();
    var randomVar:string;

    switch (option) {
        default:
        case 'ipv4':
            randomVar = chance.ip();
            break;
        case 'ipv6':
            randomVar = chance.ipv6();
            break;
    }

    return randomVar;
}

/* More wrappers... */

function processSelection(formatCB, argsCB) {

    let e = Window.activeTextEditor;
    let d = e.document;
    let sel = e.selections;

    e.edit(function (edit) {
        // iterate through the selections
        for (var x = 0; x < sel.length; x++) {
            let txt: string = d.getText(new Range(sel[x].start, sel[x].end));

            if (argsCB.length > 0) {
                txt = formatCB.apply(this, argsCB);
            } else {
                txt = formatCB();
            }

            //insert the txt in the start of the current selection
            edit.insert(sel[x].start, txt);
        }
    });
}


texts:
I have developed a test app that works by getting webpages source and processing it. I have up to 100k URLs in queue and want to use a maximum of 25 threads. Please help me check if the code is good or point out any faults you might find.

Public Class frmMain
    Public Delegate Sub AddItemDelegate(ByVal Item As String, ByVal Status As String)
    Private TotalItems As Integer =0

    Public Sub AddItem(ByVal item As String, ByVal status As String)

        If Me.InvokeRequired Then
            Me.Invoke(New AddItemDelegate(AddressOf AddItem), Item, Status)
        Else
            Dim objLock As Object = New Object()
            Dim lvItem As New ListViewItem

            With lvItem
                .Text = Item
                If Status.Length < 200 Then
                    .SubItems.Add(Status)
                Else
                    .SubItems.Add(Status.Length.ToString)
                End If
            End With

            If listView1.Items.Count <TotalItems-1 Then
                listView1.Items.Add(lvItem)
            Else
                tsslstatus.Text ="Done"
                btnStart.Enabled =true
            End If
        End If
    End Sub

    Public Sub DoWork(ByVal objItem As Object)
        static _sem as Semaphore = new Semaphore(5,10)
        Dim objUrl as String = DirectCast(objItem, string)

        Try
            If objUrl Is Nothing Then
                exit sub
            End If

            Dim URL as New Uri(objUrl)
            _sem.waitone()
            AddItem(URL.AbsoluteUri,gethtml(URL))
            _sem.Release()
        Catch ex As Exception
            debug.Print("Error " & ex.StackTrace )
        End Try
    End Sub

    Private Sub btnStart_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnStart.Click
        btnStart.Enabled =False
        dim blnResult as Boolean = ThreadPool.SetMaxThreads(25, 25)
        System.Threading.Thread.Sleep(1000)
        listView1.Items.Clear

        For Each sItem As String In txturls.Lines
            if sItem.Trim <>string.empty
                ' Queue a task
                If sItem.Contains("http://")=False Then
                    sItem="http://" & sItem
                End If

                ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf DoWork), sItem)
                TotalItems+=1
                tsslTotal.Text =String.Format ("Total Tasks: {0}",TotalItems)
            end if
        Next
    End Sub
End Class


texts: Extended Euclidean Algorithm in modern and readable C++

texts:
In Python the Extended Euclidean Algorithm (egcd) could be written as follows:

def egcd(a, b):
  if b == 0:
    return (a, 1, 0)
  else:
    (d, tmp, s) = egcd(b, a%b)
    return (d, s, tmp - (a//b) * s)

I want to write a native and modern C++ version of the egcd. This is what I have so far:

template<typename A, typename B, typename T = std::common_type_t<A, B>>
constexpr std::tuple<T, T, T> egcd(A a, B b) {
  static_assert(std::is_integral<A>::value, "arguments to egcd are integers");
  static_assert(std::is_integral<B>::value, "arguments to egcd are integers");

  if (b == 0) {
    return std::make_tuple(a, 1, 0);
  } else {
    auto triple = egcd(b, a%b);
    return std::make_tuple(std::get<0>(triple), std::get<2>(triple), std::get<1>(triple) - (a/b) * std::get<2>(triple))
  }
}

As you can see using <tuple> makes the code very long and hard (compare with the Python version..) to read.

Any suggestions to make this code more readable?


texts:
My teacher wants me to find all the perfect numbers between 2 and 1000 and must use:

for loops
% operator to determine if a number is a divisor
static final variables for 2 and 1000
A static method to return a boolean value by finding and adding the divisors of the integer parameter and comparing the sum to the parameter

The code works and I just wanted a second opinion on it.

public class Problem_B {
    //Search between 2 and 1000
    public static final int minNum = 2;
    public static final int maxNum = 1000;

    public static void main(String[] args) {
        for (int num=minNum; num <= maxNum; num++)
        if (perfectNum(num)) {
            int i_sumDiv = 0;
            for (int j=1; j <= (num/2); j++) {
                if(num%j == 0)
                    i_sumDiv = i_sumDiv + j;
            }
            if (i_sumDiv == num)
                System.out.println(num + " is a perfect number.");
        }
    }

    public static Boolean perfectNum(int num) {
        // a variable that holds the sum of the factors
        int sum = 0;

        for (int factor = 1; factor < num; factor++) {
            if (num % factor == 0) {
                sum += factor;
            }
        }

        if (sum == num) {
            return true;
        } else {
            return false;
        }
      }
    }


texts: Is this the best way to check sorting (in recursion) without loops?

texts:
Please let me know if there is a shorter way to  do it again without any kind of loops. Recursion only.

static bool isSortedArray (int[] ar, int length)
{
    if (length == 0)
        return true;
    bool temp = isSortedArray(ar, length - 1);
    if (temp && ar[length - 1] <= ar[length])
        return true;
    else
        return false;
}


texts: Summation calculator of integers, squares, and cubes

texts:
Code works exactly how I want it to, but any simplification to the code that could be made would be much appreciated (granted this program uses almost everything within the scope of my C++ knowledge).

 // sum calculator
#include<iostream>
#include<string>

//integer sum: 0 + 1 + 2 + ... + n
int integer_sum(int a, int b){
    int int_sum(0);
    while(a <= b){
    int_sum += a;
    a++;
   }
   return int_sum;
}

//squares sum: 0^2 + 1^2 + 2^2 + ... + n^2
int square_sum(int a, int b){
    int squ_sum(0);
    while(a <= b){
    squ_sum += a*a;
    a++;
  }
  return squ_sum;
}

//cubes sum: 0^3 + 1^3 + 2^3 + ... + n^3
int cube_sum(int a, int b){
    int cub_sum(0);
    while(a <= b){
    cub_sum += a*a*a;
    a++;
   }
  return cub_sum;
}

int main(){

    while(std::cin){

        char choice;
        // user menu
        std::cout << "select an operation: \n"
                  << "(a) sum of integers\n"
                  << "(b) sum of squares\n"
                  << "(c) sum of cubes\n"
                  << "(d) calculator OFF\n";
        std::cin >> choice;

        std::string restraint("First value must be less than the second");
        std::string request_range_1("First Range value: ");
        std::string request_range_2("Second Range value: ");
        int range_1;
        int range_2;

        switch(choice){
        case 'd':
            break;
        case 'a':
            std::cout << restraint << std::endl;
            std::cout << request_range_1;
            std::cin >> range_1;

            std::cout << request_range_2;
            std::cin >> range_2;

            std::cout << std::endl << "The sum of the integers in the range: " << "[" << range_1 << "," << range_2 << "]\nis: ";
            std::cout << integer_sum(range_1, range_2) << std::endl << std::endl;
            break;
        case 'b':
            std::cout << restraint << std::endl;
            std::cout << request_range_1;
            std::cin >> range_1;

            std::cout << request_range_2;
            std::cin >> range_2;

            std::cout << std::endl << "The sum of the squares in the range: " << "[" << range_1 << "," << range_2 << "]\nis: ";
            std::cout << square_sum(range_1, range_2) << std::endl << std::endl;
            break;
        case 'c':
            std::cout << restraint << std::endl;
            std::cout << request_range_1;
            std::cin >> range_1;

            std::cout << request_range_2;
            std::cin >> range_2;

            std::cout << std::endl << "The sum of the cubes in the range: " << "[" << range_1 << "," << range_2 << "]\nis: ";
            std::cout << cube_sum(range_1, range_2) << std::endl << std::endl;
            break;
        default:
            std::cout << "Incorrect operation \n\n";
            break;
        }
        if(choice == 'd')
            break;
    }
    std::cout << "Calculator OFF" << std::endl;
}


texts:
I have created a simple DBLayer class. But I am not sure whether this class have any bug/issue using in production.

public class DBLayer
{
    private static string connectionString = ConfigurationManager.AppSettings["ConnectionString"];

    public static DataTable GetDataTable(string strSQL, CommandType type)
    {
        var objCmd = new SqlCommand(strSQL);
        objCmd.CommandType = type;
        return GetDataTable(objCmd);
    }

    public static DataTable GetDataTable(SqlCommand objCmd)
    {
        SqlConnection objConn = null;
        try
        {
            objConn = new SqlConnection(connectionString);
            objCmd.Connection = objConn;
            var objAdapter = new SqlDataAdapter(objCmd);
            var ds = new DataSet();
            objAdapter.Fill(ds);
            return ds.Tables[0];
        }
        finally
        {
            objConn.Close();
        }
    }

    public static int ExecuteNonQuery(SqlCommand objCmd)
    {
        int r = -1;
        SqlConnection objConn = null;
        try
        {
            objConn = new SqlConnection(connectionString);
            objCmd.Connection = objConn;
            objConn.Open();
            r = objCmd.ExecuteNonQuery();
        }
        finally
        {
            objConn.Close();
        }

        return r;
    }
}

Please review this code?


texts: A method which, given a string, returns a string in which each character is separated by an asterisk

texts:
Use recursion in the solution.

I would really appreciate if you can help me to find a better way to do it.

public class AppendCharacterAfterEachCharacterInString
{
    int index =0;
    StringBuilder outputString = new StringBuilder();

    public string AppendInputCharacterAfterEachCharacterInString(string sInputString, string inputRepeatCharacter)
    {
        if (string.IsNullOrEmpty(sInputString))
        {
            Console.WriteLine("Empty string !");
        }
        else
        {
            BuildNewString(sInputString, inputRepeatCharacter);
        }

        return outputString.ToString();
    }

    private void BuildNewString(string inputString, string repeatCharacter)
    {
        if (index < inputString.Length)
        {
            outputString.Append(inputString[index]);

            if(!(inputString[index].ToString().Trim() == string.Empty) && !(index + 1 == inputString.Length))
              outputString.Append(repeatCharacter);

            index++;
            BuildNewString(inputString, repeatCharacter);
        }

    }


texts:
I have written a class to quantize values to arbitrary bit depths within a specified amplitude.
It is meant to process one value at a time, and has two ways of quantizing values.

I wrote the class so that i could create objects of it as a property for another class, so that the quantization process can easily be included into other, more complex operations. This class I wrote, however, has some things I am quite sure about whether they were solved optimally.

My Header file, Quantizer.h, looks like this:

#pragma once
#include <cmath>
class CQuantizer
{
public:
    ~CQuantizer();

    enum qType {
        lin_midrise,
        lin_midtread,
        numberOfTypes
    };

    CQuantizer(CQuantizer::qType type = CQuantizer::lin_midtread,
        int nBits=4, float amplitude = 1.f);

    float processOneSample(float in);
    void setNBits(int bits);
    void setAmplitude(float amplitude);
    void setType(CQuantizer::qType type);

private:
    int m_nBits;

    float m_amplitude;

    CQuantizer::qType m_type;

    float processOneSampleLinMidtread(float in);
    float processOneSampleLinMidrise(float in);

    float (CQuantizer::*processSampleFunc)(float);
};

The first thing I am wondering about is the enum I used for the types: is it a good idea to include numberOfTypes as last element for later loops through the enum etc.?

Also, I saw somewhere else for a similar class that as some kind of switch, function pointers were used, which I did for the processOneSample-method.
In this scenario, is it appropriate to do so?

Also, below I've included my implementation:

#include "Quantizer.h"

CQuantizer::~CQuantizer()
{
}

CQuantizer::CQuantizer(CQuantizer::qType type, int nBits, float amplitude)
{
    setType(type);
    setNBits(nBits);
    setAmplitude(amplitude);

}

float CQuantizer::processOneSample(float in)
{
    if (m_amplitude == 0.f) {
        // watch out for zero-amplitude
        return 0.f;
    }else{
        // use function specified by type
    return (this->*processSampleFunc)(in);
    }
}

void CQuantizer::setNBits(int bits)
{
    m_nBits = bits;
}

void CQuantizer::setAmplitude(float amplitude)
{
    m_amplitude = amplitude;
}

void CQuantizer::setType(CQuantizer::qType type)
{
    m_type = type;

    switch (m_type) {
    case CQuantizer::lin_midtread:
        processSampleFunc = &CQuantizer::processOneSampleLinMidtread;
        break;
    case CQuantizer::lin_midrise:
        processSampleFunc = &CQuantizer::processOneSampleLinMidrise;
        break;
    }

}

float CQuantizer::processOneSampleLinMidtread(float in)
{
    // upscaling
    float out = std::roundf( (in / m_amplitude) * powf(2.f, m_nBits - 1.f));

    // check for upper boundary
    if (out > powf(2.f, m_nBits - 1.f) - 1.f) {
        out = powf(2.f, m_nBits - 1.f) - 1.f;
    }

    // check for lower boundary
    if (out < -powf(2.f, m_nBits - 1.f)) {
        out = -powf(2.f, m_nBits - 1.f);
    }
    // downscaling
    return m_amplitude * out / powf(2.f, m_nBits - 1.f);
}

float CQuantizer::processOneSampleLinMidrise(float in)
{
    // upscaling
    float out = std::round((in / m_amplitude) * powf(2.f, m_nBits - 1.f) + 0.5f) - 0.5f;

    // check for upper boundary
    if (out > powf(2.f, m_nBits - 1.f) - 0.5f) {
        out = powf(2.f, m_nBits - 1.f) - 0.5f;
    }
    // check for lower boundary
    if (out < -powf(2.f, m_nBits - 1.f) + 0.5f) {
        out = -powf(2.f, m_nBits - 1.f) + 0.5f;
    }
    //downscaling
    return m_amplitude * out / powf(2.f, m_nBits - 1.f);
}

In my processing methods, i feel like there is too much going on: is there a smarter way for me to round these values and ensure they are within a set range?

(The effect I'd like to achieve with this class is that for a given amplitude, there can only be \$2^{\text{nBits}}\$ possible output values within a certain range.)


texts: Imputing values with non-negative matrix factorization

texts:
X is a DataFrame w/ about 90% missing values and around 10% actual values. My goal is to use nmf in a successive imputation loop to predict the actual values I have hidden. The mask, msk, selects a random 80% of the actual values (or 80% of the 10% actual values). I initialize all but these 80% to 0 and begin to impute them. Line 2 looks odd because I couldn't find a way to get a random 80% (train set) of the values who weren't np.nan so if I add an np.nan to a number, the value stays np.nan. Then if I subtract that X.values back off the only values that are effected are the non-null values of the array X_imputed. This allows me to get a random 80% of the non-null values.

import pandas as pd
from pandas import DataFrame
import numpy as np

from sklearn.decomposition import ProjectedGradientNMF

# toy example data, actual data is ~500 by ~ 250
customers = range(20)
features = range(15)

toy_vals = np.random.random(20*15).reshape((20,15))
toy_mask = toy_vals < 0.9
toy_vals[toy_mask] = np.nan

X = DataFrame(toy_vals, index=customers, columns=features)
# end toy example data gen.

# imputation w/ nmf loops
X_imputed = X.copy()
msk = (X.values + np.random.randn(*X.shape) - X.values) < 0.8
X_imputed.values[~msk] = 0
nmf_model = ProjectedGradientNMF(n_components = 5)
W = nmf_model.fit_transform(X_imputed.values)
H = nmf_model.components_

while nmf_model.reconstruction_err_**2 > 10:
   nmf_model.fit_transform(X_imputed.values)
   W = nmf_model.fit_transform(X_imputed.values)
   H = nmf_model.components_
   X_imputed.values[~msk] = W.dot(H)[~msk]

I'm pretty sure this can be written in fewer lines but I'm not sure how to do it.


texts:
This program is a start point to a more comprehensive program that deals with different numerical systems from binary until 35 base. That includes the traditional decimal, octal and hex.

It is until 35 only, because no more digits other than the number 0-9 and the letters A-Z to represent digits for higher base systems.

The program needs a lot of validation code and other stuff. However, I would like to ask if the conversion from/to the decimal is good or you can show me a better approach.

My main focus is the algorithms for the conversion functions and the helper functions.

Notes:

I do not want to use the built-in pow() function; I wrote my own version.
I do not want to use ASCII in character conversions.

#include <iostream>
#include <string>

using namespace std;

string digit = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int power(int base, int exp)
{
    int result = 1;

    for (int i = 0; i < exp; ++i)
        result = result * base;

    return result;
}

int val(char ch)
{
    ch = toupper(ch);

    for (int i = 0; i < 37; ++i)
        if (digit[i] == ch)
            return i;

    return -1;
}

char chr(int d)
{
    return digit[d];
}

string int_to_string(int n)
{
    string result = "";
    int divisor = 10;
    int num = n;
    int r;
    int length = 0;

    while (num > 0)
    {
        num = num / 10;
        ++length;
    }

    num = n;
    divisor = power(10, length) / 10;

    while (num != 0)
    {
        r = num / divisor;
        num = num % divisor;
        result += chr(r);
        divisor /= 10;
    }

    return result;
}

string to_decimal(string str, int base = 10)
{
    if (base == 10) return str;
    if (base < 2 || base > 37) return "Error: base out of range";
    int length = str.length();
    if (length < 1) return "Error: No Number";
    int result = 0;

    for (int i = length - 1; i >= 0; --i)
        result = result + power(base, length - i - 1) * val(str[i]);

    return int_to_string(result);
}

string from_decimal(string str, int base = 10)
{

    if (base == 10) return str;
    if (base < 2 || base > 37) return "Error: base out of range";
    int length = str.length();
    if (length < 1) return "Error: No Number";

    string result = "";
    int divisor = base;
    int num = 0;
    int r;

    for (int i = 0; i < length; ++i)
        num = num + power(10, length - i - 1) * val(str[i]);

    while (num != 0)
    {
        r = num % divisor;
        num = num / divisor;
        result = chr(r) + result;
    }

    return result;
}

bool is_valid(string str, int frombase)
{
    for (char ch : str)
        if (val(ch) >= frombase)
            return false;
    return true;
}

string baseconvert(string str, int frombase,int tobase)
{
    if(is_valid(str, frombase))
        return from_decimal(to_decimal(str,frombase), tobase);
    else
        return "Error: Improper Number used!\n";
}

int main()
{
    cout << baseconvert("FZ", 16,8) << "\n\n\n";
    cout << baseconvert("FE", 16,2) << "\n\n\n";
}


texts: Celery tasks and Flask application factory

texts:
I am implementing a few Celery background tasks (e.g sending an email, subscribing someone to an Audience via Mailchimp API, etc.) and my project relies on a Flask application factory.
Now, I am trying to understand if the way I've used application contexts makes sense at all or if it can be improved (I've quite a few resources lying around presenting very different approaches).
Here's my __init__.py

from flask import Flask
from .config import Config
form celery import Celery

# [...] A bunch of external components
celery = Celery(__name__)

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    celery.conf.update(app.config)

    # Instantiate external components
    # Blueprint registration

    return app

Now, the tasks that get executed in my blueprints are declared in the way presented below (in a ~/app/tasks.py file). As you can see, an application context gets created each time a task gets executed. This is the point where I am struggling: does it make sense to instantiate a Flask app each time a task needs to be executed or should I find a way to create a new 'global' app context?

from flask import current_app
from . import create_app, celery, mailchimp

@celery.task()
def newsletter_subscribe(user):
    """
    Subscribe a new user to a newsletter via Mailchimp API
    """
    app = create_app()  # Create a new Flask app instance

    with app.app_context():
        mailchimp.lists.members.create(
            list_id=current_app.config['MAILCHIMP_LISTS'][user["frequency"]],
            data={
                'email_address': user['email'],
                'status': 'subscribed'
            }
        )

# ... some more tasks following the same structure

Celery gets its worker thanks to the following command in my docker-compose file:

  celery:
    build:
      context: .
      dockerfile: 'Dockerfile.dev'
    command: celery worker -B -A app.tasks -l info
    env_file:
      - '.env'
    volumes:
      - '.:/app'

Everything seems to work just fine but I am wondering if there's any pitfall in the way I am using app contexts or any margin for improvement.


texts:
I'm pushing myself to learn pure JavaScript, so this morning I wrote an equal heights script in jQuery and then converted it to JavaScript. It works, but I'm using two for loops. Is there a better or more efficient way to write this code, maybe by finding a way to remove the second for loop?

I've created a jsfiddle to make is a little easier to test.

var  maxHeight = -1
,    elems = document.getElementsByClassName("features");

for( var i = 0; i < elems.length; i++ )
{
    maxHeight = maxHeight > elems[i].offsetHeight ? maxHeight : elems[i].offsetHeight;
}

for( var i = 0; i < elems.length; i++ )
{
    elems[i].style.height = maxHeight + "px";
}


texts:
I am working with this code to parse through HTML files stored on my computer and extract HTML text by defining a certain tag that should be found:

from bs4 import BeautifulSoup
import glob
import os
import re
import contextlib

@contextlib.contextmanager
def stdout2file(fname):
    import sys
    f = open(fname, 'w')
    sys.stdout = f
    yield
    sys.stdout = sys.__stdout__
    f.close()

def trade_spider():
    os.chdir(r"C:\Users\Independent Auditors Report")
    with stdout2file("auditfeesexpenses.txt"):
        for file in glob.iglob('**/*.html', recursive=True):
            with open(file, encoding="utf8") as f:
                contents = f.read()
                soup = BeautifulSoup(contents, "html.parser")
                for item in soup.findAll("ix:nonfraction"):
                    if re.match(".*AuditFeesExpenses", item['name']):
                        print(file.split(os.path.sep)[-1], end="| ")
                        print(item['name'], end="| ")
                        print(item.get_text())
                        break
trade_spider()

The code works perfectly thanks to the help of the stackflow community! As I am not an expert in python coding, I am wondering whether there are some magic tricks some of you might know, to speed up my code and reduce processing time as it has to parse through ~ 4 Million files.

Perhaps in a nutshell what my code does:
-> open text file -> parse through all html documents in set directory -> if regex is found, print result into open text file -> break, no more than one match and continue to next file...

I am open to any suggestions on improving this code.

Update:

Further Explanation: Basically I want to find a certain name attribute (name=".+AuditFeesExpenses") in each HTML document and IF this attribute is found I want to have the name of the file, the Name Attribute and the correlating HTML text be printed into a separat text file.

An example string that I extracted from a single HTML file is:

<ix:nonFraction name="f:AuditFeesExpenses" contextRef="c201" unitRef="u5" decimals="0" format="ixt:numcommadot">8,930</ix:nonFraction>


texts:
I developed a script to transform a Japanese word in Furigana thanks to the jisho website. But the code is very ugly, especially the extractHiraganaFromHTML and filterBetween functions. What kind of improvements are possible?

module Main
where

import Network.HTTP
import Network.URI
import Text.HTML.TagSoup
import Data.Text (unpack)
import Data.Text.Encoding (decodeUtf8)
import Data.ByteString.Char8 (pack)
import System.Environment (getArgs)

jishoUrlFor :: String -> String
jishoUrlFor word = (escapeURIString isUnescapedInURI) $ "http://jisho.org/word/"++word

getJishoHTML :: String -> IO String
getJishoHTML w  = simpleHTTP (getRequest $ jishoUrlFor w) >>=  getResponseBody

extractHiraganaFromHTML :: String -> String
extractHiraganaFromHTML = unicodeToString . strip . innerText . filter(~== TagText "") . filterBetween . head . partitions  (~== "<span class=\"furigana\">") . parseTags

convertWordToHiragana :: String -> IO String
convertWordToHiragana w = do
    html <- getJishoHTML w
    return $ extractHiraganaFromHTML html

filterBetween :: [Tag String] -> [Tag String]
filterBetween p = fst $ sfoldl step ([],0) $  p
where step (x,a) tag | tag ~== "<span>" = (tag:x,a+1)
      step (x,a) tag | tag ~== TagClose "span" = (tag:x,a-1)
      step (x,a) tag = (tag:x,a)

      sfoldl step (a,1) (TagClose "span":xs) = (reverse (TagClose "span":a),0) -- stop condition
      sfoldl step (a,b) (x:xs) = sfoldl step (step (a,b) x) xs
      sfoldl step (a,b) [] = (a,b)

wchars = " \t\r\n"

strip :: String -> String
strip = lstrip . rstrip

lstrip :: String -> String
lstrip = dropWhile (`elem` wchars)

rstrip :: String -> String
rstrip = reverse . lstrip . reverse

unicodeToString = Data.Text.unpack . Data.Text.Encoding.decodeUtf8 . Data.ByteString.Char8.pack

main = do
    (word:_) <- getArgs
    a <- convertWordToHiragana word
    putStrLn a


texts: Mark rows with identical values in a table

texts:
I have an simple algorithm which marks table rows with identical entries blue.  The problem is that this solution takes a lot of time.

Has anyone an idea how to improve the speed of this?

$(document).ready(function(){
   var tableRows = $("#sortable tbody tr");
   tableRows.each(function(n){
      var id = $(this).attr('id');
      var example = $(this).children('#example').children('#content').html();

      tableRows.each(function(n){
         if($(this).attr('id') != id)
         {
            if ($(this).children('#example').children('#content').html() == example)
            {
               $(this).css('backgroundColor', 'azure');
            }
         }
      });
   });
});

My table looks like this:

         Digitcode

test


texts: T-SQL Hmac (Rfc2104 SHA2_256) Implementation

texts:
I'm trying to implement an Hmac in T-SQL using this question as an guide. Please critique this:

create function dbo.Hmac (
    @key varbinary(8000)
  , @message varbinary(7936)
)
returns table
with schemabinding as
return (
    select HashBytes('SHA2_256', Pads.o + HashBytes('SHA2_256', Pads.i + @message)) as [Hash]
    from (values(
        Cast( -- keys longer than blocksize are shortened and keys shorter than blocksize are zero-padded
            case
                when DataLength(@key) > 64 then HashBytes('SHA2_256', @key)
                else @key
            end
        as binary(64))
      , Cast(0x3636363636363636 as bigint) -- Rfc2104 inner padding constant
      , Cast(0x5C5C5C5C5C5C5C5C as bigint) -- Rfc2104 outer padding constant
    )) as Vars ([key], innerPadding, outerPadding)
    cross apply (values(
      -- unrolled loop to XOR key and iPad
        Cast((Substring(Vars.[key], 1, 8) ^ Vars.innerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 9, 8) ^ Vars.innerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 17, 8) ^ Vars.innerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 25, 8) ^ Vars.innerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 33, 8) ^ Vars.innerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 41, 8) ^ Vars.innerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 49, 8) ^ Vars.innerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 57, 8) ^ Vars.innerPadding) as binary(8))
      -- unrolled loop to XOR key and oPad
      , Cast((Substring(Vars.[key], 1, 8) ^ Vars.outerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 9, 8) ^ Vars.outerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 17, 8) ^ Vars.outerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 25, 8) ^ Vars.outerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 33, 8) ^ Vars.outerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 41, 8) ^ Vars.outerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 49, 8) ^ Vars.outerPadding) as binary(8))
      + Cast((Substring(Vars.[key], 57, 8) ^ Vars.outerPadding) as binary(8))
    )) as Pads (i, o)
);


texts: Write a class with some properties and indexed

texts:
Is there a better way to write it? I need the best way to write it. It is this principle? Please show me a better way

it breaks SRP?

 public class PlacementLocation
{
    public int Row { get; set; }
    public int Column { get; set; }
    public int Location { get; set; }
}

public class PlacementLocations : PlacementLocation
{
    private void SetLocationInList()
    {
        _placementLocations = new List<PlacementLocation>
            {
                new PlacementLocation {Column = 1, Row = 9, Location = 1},
                new PlacementLocation {Column = 2, Row = 9, Location = 2},
                new PlacementLocation {Column = 3, Row = 9, Location = 3},
                new PlacementLocation {Column = 4, Row = 9, Location = 4},
                new PlacementLocation {Column = 5, Row = 9, Location = 5},
            };
    }

    private List<PlacementLocation> _placementLocations;

    public PlacementLocations()
    {
        _placementLocations = new List<PlacementLocation>();
        SetLocationInList();
    }

    public Tuple<int, int> this[int location]
    {
        get { return new Tuple<int, int>(_placementLocations[location].Row, _placementLocations[location].Column); }
    }

    public int this[int row, int column]
    {
        get
        {
            PlacementLocation singleOrDefault =
                _placementLocations.SingleOrDefault(d => d.Column == column && d.Row == row);
            return singleOrDefault != null ? singleOrDefault.Location : 0;
        }
    }
}

Update :

  public class PlacementLocations
{

    #region Variables

    private readonly List<PlacementLocation> _placementLocations;

    #endregion

    #region Constructor

    public PlacementLocations(List<PlacementLocation> placementLocations)
    {
        _placementLocations = placementLocations;
    }

    #endregion

    #region Public Methods

    public Tuple<int, int> FindRowColumn(int location)
    {
        return GetRowColumn(location);
    }

    public int FindLocation(int row, int column)
    {
        return GetLocation(row, column);
    }

    #endregion

    #region Indexes

    public Tuple<int, int> this[int location]
    {
        get { return GetRowColumn(location); }
    }

    public int this[int row, int column]
    {
        get { return GetLocation(row, column); }
    }

    #endregion

    #region Private Methods

    private Tuple<int, int> GetRowColumn(int location)
    {
        return new Tuple<int, int>(_placementLocations[location].Row, _placementLocations[location].Column);
    }

    private int GetLocation(int row, int column)
    {
        PlacementLocation singleOrDefault =
            _placementLocations.SingleOrDefault(d => d.Column == column && d.Row == row);
        return singleOrDefault != null ? singleOrDefault.Location : 0;
    }

    #endregion

}

public class LocationsFactory
{
    public static PlacementLocations GetPredefinedLocations()
    {
        var placementLocationList = new List<PlacementLocation>
            {
                new PlacementLocation {Column = 1, Row = 9, Location = 1},
                new PlacementLocation {Column = 2, Row = 9, Location = 2},
                new PlacementLocation {Column = 3, Row = 9, Location = 3},
                new PlacementLocation {Column = 4, Row = 9, Location = 4},
                new PlacementLocation {Column = 5, Row = 9, Location = 5},
            };

        return new PlacementLocations(placementLocationList);
    }
}


texts:
I made a simple bare bones Tab component, i'm a beginner when it comes to ReactJS so any advice regarding the codes functionality is greatly appreciated.

Tab.js Component

import React from 'react';

class Tabs extends React.Component {

    constructor() {

        super();

        this.state = {
            activeIndex : 0
        }
    }

    handleOnClick(key, event) {

        event.preventDefault();

        this.setState({
            activeIndex : key
        });
    }

    renderNavItem(key) {

        let tab = this.props.children[key];

        return (

                { tab.props.title }

        );
    }

    render() {

        let index = 0;
        let active = this.state.activeIndex;

        let tabs = React.Children.map(this.props.children, function (child) {
            return React.cloneElement(child, {
                active : child.props.active === true ? true : (active == index++)
            });
        });

        return (

                    { Object.keys(this.props.children).map(this.renderNavItem.bind(this)) }

                    { tabs }

        )
    }
}

class Tab extends React.Component {

    render() {

        return (

                { this.props.children }

        )
    }
}

Tab.defaultProps = {
    active : false
};

export default {
  Tabs,
  Tab
};

Usage

import React from 'react';
import {Tabs, Tab} from './Tabs';

class App extends React.Component {

    render() {

        return (
            <Tabs className="tabs-wrapper">
                <Tab active="true" title="Tab One">Tab One content</Tab>
                <Tab title="Tab Two">

Tab Two Content

                </Tab>
            </Tabs>
        );
    }
}

React.render(
    <App/>,
    document.getElementById('react_example')
);

Example

http://jsbin.com/hajokofavu/edit?js,output


texts:
I am very happy because I solved this problem with very little code:

"""

    100 people are standing in a circle with gun in their hands.
    1 kills 2, 3 kills 4, 5 kills 6 and so on till we are
    left with only one person. Who will be the last person alive?
    Write code to implement this ##efficiently.## <-[ Python is not efficient]

"""

persons = list(range(1,101)) # The question asks 1-indexing

while len(persons) > 1:
    for index, person in enumerate(persons):
        del persons[(index + 1) % len(persons)]

print(persons)


texts:
I have started practicing problems in leetcode and I solved the following problem on LeetCode.

The challenge is :

  Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

  The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

  You may assume the integer does not contain any leading zero, except the number 0 itself.

 Example 1:
 Input: [1,2,3]
 Output: [1,2,4]
 Explanation: The array represents the integer 123.

 Example 2:
 Input: [4,3,2,1]
 Output: [4,3,2,2]
 Explanation: The array represents the integer 4321.

I am trying to get better at writing good code for my solutions. Please give me your suggestions

class Solution {
    public int[] plusOne(int[] a) {

        int length = a.length-1;

        while(length>=0)
        {
            a[length]=a[length]+1;
            int carry = a[length]/10;
            if(carry==1)
            {
                a[length]=0;
                length=length-1;
            }
            else
                break;
        }

        if(a[0]==0)
        {
            int [] array = new int[a.length+1];
            array[0]=1;
            for(int i=1;i<array.length-1;i++)
            {
                array[i]=0;
            }
            return array;
        }
        return a;

    }
}


texts: Write a clean convertToNumber function, if value is a number

texts:
I have a function that creates filters for some data. The filters get added to an array and then (later) chained through the reduce function (the chaining part not part of my question).
The data I receive are all strings but can actually be numbers, eg {name:"-45.6"}. If it can be a number, I want the value to be converted to a number.
formFilters = (builder) => {
    const filters = [];
    builder.forEach(b => {
        let {filtername, operator, value} = b;

        if(!value) return;

        if(isNumber(value)){
            value = Number(value);
        }

        switch (operator) {
            case "=":
                filters.push((item) => convertToNumber(item[filtername]) === value);
                break;
            case "<":
                filters.push((item) => convertToNumber(item[filtername]) < value);
                break;
            case ">":
                filters.push((item) => convertToNumber(item[filtername]) > value);

        }
    });
    return filters;
}

function convertToNumber(value){
    const number = Number(value);
    if (!Number.isNaN(number)) return number;
    return value;
}

This works but I'm wondering if there's a cleaner way of converting the value to a number if it is a number?


texts:
I am hoping a Meteor guru can please review my code below and verify if I am properly using return false and event.preventDefault(), especially in the context of form submission.

The reason being, the Meteor docs use this approach:

// Prevent default form submit
return false;

while other tutorials use this approach:

event.preventDefault(); //prevent page reload

So I want to be sure that I am on the correct path before I proceed with the rest of my code.

Basically, my code gets the value of the username input and checks if the value exists in the database:

HTML

<template name="registration">

{{message}}

    <form id="register_form">
        <input type="text" name="username" placeholder="username">
    </form>
</template>

JS

if (Meteor.isClient) {
    // This code only runs on the client

    Meteor.subscribe("users");

    Template.registration.helpers({
        message: function () {
            return Session.get("message");
        },
        message_defined: function () {
            return Session.equals("message", undefined) ? false : true;
        }
    });

    Template.registration.events({
        "submit #register_form": function (event) {
            // This function is called when the registration form is submitted.

            event.preventDefault(); // Correct usage?

            var form_data = {
                username: event.target.username.value,
            };

            if (!Match.test(form_data.username, String)) {
                Session.set("message", "username must be a string");
                return false;  // Correct usage?
            }

            if (form_data.username.length < 6) {
                Session.set("message", "username must be at least 6 characters");
                return false;  // Correct usage?
            }

            Meteor.call("check_username",form_data.username,function(error, result){
                if (error) {
                    Session.set("message", error);
                    return false;  // Correct usage?
                }
                if (result) {
                    Session.set("message", result);
                    return false;  // Correct usage?
                }
            });
        }
    });
}

Meteor.methods({
    check_username: function (username) {
        // If user exists, return error.

        var user = Meteor.users.findOne({username:username});
        if (user) {
            throw new Meteor.Error("username exists", "That username is already in use.");
        }

        return "username not found";
    }
});

if (Meteor.isServer) {
    Meteor.publish("users", function () {
        return Meteor.users.find();  // This publishes everything - be careful!
    });
}


texts: The seasoned Zombie sniper: a query to find unanswered questions with specific tags

texts:
The query (on SEDE)

This query builds upon the previous and includes the suggestions by rofl as well as the now mentioned activity index.

DECLARE @tag_name nvarchar(35) = '##TagName##';
DECLARE @min_score int = ##MinScore:int?0##;
DECLARE @max_score int = ##MaxScore:int?0##;

-- CTE to find the maximum answer score on a question. Originally suggested by
-- rofl on https://codereview.stackexchange.com/a/189966/21002
WITH BestAnswer AS (
  SELECT
    ParentId,
    Max(Score) as Score,
    MAX(LastActivityDate) as LastActivityDate
  FROM Posts
  WHERE PostTypeId = 2
  GROUP BY ParentId
)

SELECT
  q.Id AS [Post Link],
  q.Tags,
  q.LastActivityDate as [Last question activity],
  a.LastActivityDate as [Last answer   activity],
  CAST(a.LastActivityDate - q.LastActivityDate as int) as [Activity Index]
FROM
  Posts q
    INNER JOIN PostTags pt
    ON    q.Id = pt.PostId
    INNER JOIN Tags t
    ON    pt.TagId = t.id
      AND t.TagName = @tag_name
    INNER JOIN BestAnswer a
    ON    q.Id = a.ParentId
      AND a.Score >= @min_score
      AND a.Score <= @max_score
WHERE
      q.PostTypeId = 1
  AND q.ClosedDate IS NULL
  AND q.AnswerCount > 0
  AND q.AcceptedAnswerId IS NULL
ORDER BY
  [Activity Index] DESC,
  q.LastActivityDate ASC

-- TagName: Tag name as you would use in your post
-- MinScore: Highest answer has at least votes:
-- MaxScore: Highest answer has at most votes:

This will probably be the last one in the Zombie series.

Motivation

Zombies! The dread of any barbecue. The grilled brains are sticky, their odour is icky, and they never stop talking about crossdead. But that is not the kind of Zombie we suffer from.

We are looking for easy-to revive question Zombies. Questions, that have at least one 0-score answer but count as /unanswered. A revival just needs a single click in those cases: an upvote. We only need to find those Schroedinger questions and cure them.

The first cure accidentally included closed questions, as did the second. This query remedies this fault and only looks for the Zombies that haven't been thrown into jail. It also includes an activity index (see below).

The goal

The previous questions have shown that the requirements on the query were not really communicated well. This time I'll try to list all requirements for the query:

it must consist of a subset of /unanswered:

it must not contain closed questions
it must not contain questions that have an accepted answer
it must not contain questions that have an answer with a positive (>0) score, unless the MaxScore is greater than 0

it must not contain questions that have answers with a score greater than the MaxScore
it must not contain questions that have answers with a score lesser than the MinScore
it should only return questions that have been tagged with ##Tagname##
it should include the last activity date of the question
it should include the latest activity date the question's answers
it should include an activity index
it should order the results by the activity index descending first and then ascending by date.

The activity index is basically the difference between the last question activity and the latest question's answers' activity, e.g.

$$ \text{activity_index} = \max_{a \text{ answers } q} a_{\text{LastActivityDate}} - q_{\text{LastActivityDate}}. $$

Since any answer activity automatically updates the question's LastActivityDate it is always non-positive. The lower the index, the more likely that a new answer is necessary and the current 0-score answer is insufficient or misses the point.


texts:
Here is the code for the QuickSort class that I created.

public class QuickSort {

        public static void sort(Comparable[] a) {
            quicksort(a, 0, a.length-1);
        }

        private static void quicksort(Comparable[] a, int lo, int hi) {
            if(lo >= hi) return;
            int pi = partition(a, lo, hi);
            quicksort(a, lo, pi-1);
            quicksort(a, pi+1, hi);
        }

        private static int partition(Comparable[] a, int lo, int hi) {
            int i = lo + 1;
            int j = hi;

            while(i <= j) {
                if(a[i].compareTo(a[lo]) <= 0) {
                    i++;
                }
                else if(a[j].compareTo(a[lo]) > 0) {
                    j--;
                }
                else if(j < i) {
                    break;
                }
                else
                    exchange(a, i, j);
            }
            exchange(a, lo, j);
            return j;
        }

        private static void exchange(Object[] a, int i, int j) {
            Object tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }
}

The code passed some simple tests (including duplicate values). I wonder is any bug in my code? Anywhere to improve?


texts: A big ng-repeat to display the progress of builds

texts:
I'm looking to improve the speed my ng-repeat or find an alternative way to do it, because it takes too long to load when it has to manage a lot of data.

{{::build._buildTypeId}}

Running on: {{::build.agent._name}}

Version: {{::build._number}}

Run by: {{::build.user._name}}

 5  ,'progress-bar-warning': build._percentageComplete <= 6}">
                     5" class="sr-only"> {{build._percentageComplete}}% Completed

= 50"> in : {{build.timeInfo}} Minutes


texts: Computation of Prefix Free Codes with many repeated weight values in reduced space

texts:
Does the code below respect Python programming conventions? (and if not, which one does it disrespect?) The objective would be to publish this code as part of a scientific article, as "reproducible research".

In 1998, Moffat and Turpin described in "Efficient Construction of Minimum Redundancy Codes for Large Alphabets" (which I reviewed here) how to compute prefix free codes from sorted weights with many repeated weight values in reduced space and time (once the weights are sorted). I am planning to reproduce and describe their first experiment (compressing some TREC data set) in a fully reproducible way, as an exercize in reproducible research. Their algorithm should be implementable (they did implement it and ran it for their experiment but did not share their code) but I found that I needed to make large modifications when programming it in Python, and I wonder if I am doing it properly (I am more of a mathematician than a programmer).

def assertEqual(x,y):
   assert x==y, str(x)+" should be "+str(y)

# A function to simulate one sorted list from two:
def sourceOfFirstOfTwo(leaves,graphs):
   """Given two lists of 4-uple, returns a pointer to the one with the list with the smallest first element, sorted by first value."""
   assert(len(leaves)>0 or len(graphs)>0)
   if len(leaves)==0:
      return graphs
   elif len(graphs)==0:
      return leaves
   else:
     (firstLeafWeight,firstLeafFrequency,firstLeafLeft,firstLeafRight) = leaves[0]
     (firstGraphWeight,firstGraphFrequency,firstGraphLeft,firstGraphRight) = graphs[0]
     if firstLeafWeight<firstGraphWeight:
        return leaves
     else:
        return graphs
assertEqual(sourceOfFirstOfTwo([(1,1,0,0)],[]),[(1,1,0,0)])
assertEqual(sourceOfFirstOfTwo([],[(2,1,0,0)]),[(2,1,0,0)])
assertEqual(sourceOfFirstOfTwo([(1,1,0,0)],[(2,1,0,0)]),[(1,1,0,0)])
assertEqual(sourceOfFirstOfTwo([(2,1,0,0)],[(1,1,0,0)]),[(1,1,0,0)])

def Meld(leaves):
   assert(len(leaves)>0)
   graphs = []
   source = leaves
   first = (firstWeight,firstFrequency,firstLeft,firstRight) = source[0]
   while firstFrequency>1 or len(leaves)+len(graphs)>1:
      assert(len(graphs)<5)
      if firstFrequency>1:
         if firstFrequency %2 == 1:
            source[0] = (firstWeight, 1, firstLeft, firstRight)
         else:
            source.remove(first)
         graphs.append((2*firstWeight,firstFrequency // 2,first,first))
      else: #firstFrequency == 1 but len(leaves)+len(graphs)>1
         source.remove(first)
         secondSource = sourceOfFirstOfTwo(leaves,graphs)
         second = (secondWeight,secondFrequency,secondLeft,secondRight) = secondSource[0]
         assert(secondFrequency>0)
         if secondFrequency==1:
            secondSource.remove(second)
         else:
            secondSource[0] = (secondWeight,secondFrequency-1,secondLeft,secondRight)
         graphs.append((firstWeight+secondWeight,1,first,(secondWeight,1,secondLeft,secondRight)))
      source = sourceOfFirstOfTwo(leaves,graphs)
      first = (firstWeight,firstFrequency,firstLeft,firstRight) = source[0]
   return(sourceOfFirstOfTwo(leaves,graphs)[0])
assertEqual(Meld([(1,1,0,0)]),(1, 1, 0, 0))
assertEqual(Meld([(1,2,0,0)]),(2,1,(1, 2, 0, 0),(1, 2, 0, 0)))
assertEqual(Meld([(1,4,0,0)]),(4,1,(2,2,(1, 4, 0, 0),(1, 4, 0, 0)),(2,2,(1, 4, 0, 0),(1, 4, 0, 0))))
assertEqual(Meld([(1,2,0,0),(3,1,0,0)]),(5,1,(2,1,(1,2,0,0),(1,2,0,0)),(3,1,0,0)))


texts:
When working with geometric objects I like working with the shapely module (Shapely - PyPI). In here it is easy to create polygons and define union, intersection and differences. Like so:

from shapely.geometry import Polygon

x1 = [3, 3, 6, 6, 3]
y1 = [4, 8, 8, 4, 4]
x2 = [1, 8, 8, 1, 1]
y2 = [1, 1, 6, 6, 1]

rectangle_1 = Polygon([*zip(x1, y1)])
rectangle_2 = Polygon([*zip(x2, y2)])

intersection = rectangle_1.intersection(rectangle_2)
union = rectangle_1.union(rectangle_2)
difference_1_2 = rectangle_1.difference(rectangle_2)
difference_2_1 = rectangle_2.difference(rectangle_1)

However, when plotting this polygons in Matplotlib I could not find a direct method where I can plot the exterior and interior paths that can exist in shapely Polygons. In particular being able to plot 'holes' in a bigger polygon created by differences of smaller polygons fully embedded in the bigger one.

I came up with the following solution whereby the exterior and interior paths of the polygon are drawn using the the mpl Path module and convert this to a patch.

import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from shapely.geometry import Polygon

class PatchPolygon:

    def __init__(self, polygon, **kwargs):
        polygon_path = self.pathify(polygon)
        self._patch = PathPatch(polygon_path, **kwargs)

    @property
    def patch(self):
        return self._patch

    @staticmethod
    def pathify(polygon):
        ''' Convert coordinates to path vertices. Objects produced by Shapely's
            analytic methods have the proper coordinate order, no need to sort.

            The codes will be all "LINETO" commands, except for "MOVETO"s at the
            beginning of each subpath
        '''
        vertices = list(polygon.exterior.coords)
        codes = [Path.MOVETO if i == 0 else Path.LINETO
                 for i in range(len(polygon.exterior.coords))]

        for interior in polygon.interiors:
            vertices += list(interior.coords)
            codes += [Path.MOVETO if i == 0 else Path.LINETO
                      for i in range(len(interior.coords))]

        return Path(vertices, codes)

x1 = [3, 6, 6, 3]
y1 = [2, 2, 4, 4]
x2 = [1, 1, 2, 2]
y2 = [1, 2, 2, 1]
x3 = [0, 9, 9, 0]
y3 = [0, 0, 6, 6]

fig, ax1 = plt.subplots(figsize=(6, 4))

ax1.set_xlim(-1, 10)
ax1.set_ylim(-1, 10)

rectangle_1 = Polygon([*zip(x1, y1)])
rectangle_2 = Polygon([*zip(x2, y2)])
rectangle_3 = Polygon([*zip(x3, y3)])
difference = rectangle_3.difference(rectangle_2).difference(rectangle_1)

ax1.add_patch(PatchPolygon(difference, facecolor='blue', edgecolor='red').patch)

plt.show()

Credit goes to Sean Gillies (painting-punctured-polygons-with-matplotlib) who inspired me to the solution. However we are now almost 10 years further, so wondered if there is a better way!


texts: Custom timer code needs reviewing for thread safety

texts:
I've created a custom timer to satisfy the following requirements:

Millisecond accuracy
I want the tick event handler to only be called once the current tick handler has completed (much like the winforms timer)
I want exceptions on the main UI thread not to be swallowed up by the thread timer so this requires Invoke/Send instead of BeginInvoke/Post

Note: I call timeBeginPeriod(1)/ timeEndPeriod(1) in order to achieve the millisecond accuracy.

I've put in a check if the timer is deleted to make sure that the deletion is complete before the timer can be created again. Does that look ok?

For the IsRunning property, is it possible that racing conditions could occur?

...or is the code a disaster waiting to happen and I should try (again) to get CreateTimerQueueTimer to work?

The code has been tested with a small interval of 1 millisecond and a large interval of 300 milliseconds with frequent start/stops, and I've had no problems so far.

ETA: I've found a problem with it. If the timer is running at an interval of 1 millisecond, and I call, say, Change(300), it locks up @ while (this.DeleteRequest). This
must be because the TimerLoop is in the this.CallbackDelegate.Invoke(null) call.

public class MyTimer : IDisposable
{

    private System.Threading.TimerCallback CallbackDelegate;
    private bool DeleteRequest;

    private System.Threading.Thread MainThread;
    public MyTimer(System.Threading.TimerCallback callBack)
    {
        this.CallbackDelegate = callBack;
    }

    public void Create(int interval)
    {
        while (this.DeleteRequest) {
            System.Threading.Thread.Sleep(0);
        }

        if (this.MainThread != null) {
            throw new Exception("");
        }

        this.MainThread = new System.Threading.Thread(TimerLoop);
        // Make sure the thread is automatically killed when the app is closed.
        this.MainThread.IsBackground = true;
        this.MainThread.Start(interval);

    }

    public void Change(int interval)
    {
        // A lock required here?
        if (!this.IsRunning()) {
            throw new Exception("");
        }
        this.Delete();
        this.Create(interval);
    }

    public void Delete()
    {
        this.DeleteRequest = true;
    }

    public bool IsRunning()
    {
        return (this.MainThread != null) && this.MainThread.IsAlive;
    }

    private void TimerLoop(object args)
    {
        int interval = (int)args;
        Stopwatch sw = new Stopwatch();
        sw.Start();

        do {
            if (this.DeleteRequest) {
                this.MainThread = null;
                this.DeleteRequest = false;
                return;
            }

            long t1 = sw.ElapsedMilliseconds;

            // I want to wait until the operation completes, so I use Invoke.
            this.CallbackDelegate.Invoke(null);

            if (this.DeleteRequest) {
                this.MainThread = null;
                this.DeleteRequest = false;
                return;
            }

            long t2 = sw.ElapsedMilliseconds;

            int temp = Convert.ToInt32(Math.Max(interval - (t2 - t1), 0));
            sw.Reset();
            if (temp > 0) {
                System.Threading.Thread.Sleep(temp);
            }

            sw.Start();
        } while (true);

    }

        // dispose calls this.Delete();

}


texts:
This method find cells that are crossed by line A-B and adds them to one vector.
I have got some duplicates here and some lines of code are very similiar but they differ in one variable. Should this duplicated be fixed or is it fine?

std::vector<Cell> Grid::findCells(int xA,int yA,  int xB,  int yB) {

vector<Cell> setOfCellsToUnmark;
//
int xI, yI, t;

if (xA < xB) {
    for (xI = coordinateToCellIndex(xA) * SIZE_CONST + MOVEMENT;
         xI < xB; xI += SIZE_CONST) {
        t = (xI - xA) / (xB - xA);
        yI = yA + t * (yB - yA);
        //find coordinates that X axis is crossed by line from xA to xB inclusive
        addToVector(xI, yI, setOfCellsToUnmark);
        //find coordinates that X axis is crossed by line from xA to xB exclusive
        addToVector(xI + MOVEMENT, yI, setOfCellsToUnmark);
    }
}
else {
    for (xI = coordinateToCellIndex(xA) * SIZE_CONST - MOVEMENT;
         xI > xB; xI -= SIZE_CONST) {
        t = (xI - xA) / (xB - xA);
        yI = yA + t * (yB - yA);
        addToVector(xI, yI, setOfCellsToUnmark);
        addToVector(xI + MOVEMENT, yI, setOfCellsToUnmark);
    }
}

if (yA < yB) {
    for (yI = coordinateToCellIndex(yA) * SIZE_CONST + MOVEMENT;
         yI < yB; yI += SIZE_CONST) {
        t = (yI - yA) / (yB - yA);
        xI = xA + t * (xB - xA);
        addToVector(xI, yI, setOfCellsToUnmark);
        addToVector(xI, yI + MOVEMENT, setOfCellsToUnmark);
    }
} else {
    for (yI = coordinateToCellIndex(yA) * SIZE_CONST - MOVEMENT;
         yI > yB; yI -= SIZE_CONST) {
        t = (yI - yA) / (yB - yA);
        xI = xA + t * (xB - xA);
        addToVector(xI, yI, setOfCellsToUnmark);
        addToVector(xI, yI + MOVEMENT, setOfCellsToUnmark);
    }
}
return setOfCellsToUnmark;
}

void Grid::addToVector(const int x, const int y, vector<Cell> & setOfCells) const {
    Cell c = coordinateToCellIndex(x, y);
    if (isCellInGrid(c)) {
        setOfCells.push_back(c);
    }
}


texts:
I have been doing some JS lately and I would like to get some constructive criticism.

The project I am working on

var SpotifiedList = [],
youtubeSongs, spotifySongs = 0,
spotifiedSongs = 0,
playNext;

$(document).ready(function () {
  var id = window.location.hash;
  if (id) {
    $("#playlistID").val(id.substring(1));
    startProcess();
  }
});

function resetTimer() {
  console.log("timer reset!")
  clearTimeout(playNext);
}

function startProcess() {
  $("#errorOccured").hide();
  if ($("#playlistID").val().length < 5) { // Checks if there is something entered
    $(".alert-danger").fadeIn().html("Please enter a valid Youtube playlist ID.");
  } else {
    window.location.hash = $("#playlistID").val();
    $("#list").html('This might take some time.');
    $(".alert-info").html("Loading");
    $(".alert-danger").hide();
    retrieveYoutubePlaylist($("#playlistID").val(), 1, [], 1);
  }
}

function retrieveYoutubePlaylist(id, startIndex, list, k) {
  $("#loading").show();
  $.ajax({
    url: 'https://gdata.youtube.com/feeds/api/playlists/' + id + '?v=2&alt=json&start-index=' + startIndex + '&max-results=50',
    dataType: 'json',
    success: function (data) {
      if (typeof data.feed.entry === 'undefined') {} else {
        for (var i = 0; i < data.feed.entry.length; i++) {
          if (k == 1) $("#list").html("");
          var title = data.feed.entry[i].title.$t;
          list.push(title);
          retrieveSpotify(title);
          k++;
        }
        retrieveYoutubePlaylist(id, startIndex + 50, list, k);
        youtubeSongs = list.length;
      }
    },
    error: function (data, a, err) {
      if (err) {
        $(".alert-danger").fadeIn().html("Error Happened: " + err);
      }
    }
  });
}

function retrieveSpotify(title) {
  var url = 'http://ws.spotify.com/search/1/track.json?q=' + parseTitle(title);
  $.getJSON(url, function (data) {
    spotifySongs += 1;
    if (data.tracks.length > 0) {
      spotifiedSongs += 1;
      $("#list").append('
' + data.tracks[0].artists[0].name + ' - ' + data.tracks[0].name + '
');
      var info = {
        'url': data.tracks[0].href,
        'length': Math.round(data.tracks[0].length * 1000),
        'name': data.tracks[0].artists[0].name + ' - ' + data.tracks[0].name
      }
      SpotifiedList.push(info);
    }
    if (youtubeSongs == spotifySongs) {
      $(".alert-info").html('
\
        <button type="button" class="btn btn-default" onClick="play();">\
         Play/Skip\
        </button>\

Converted songs: ' + spotifiedSongs + '/' + youtubeSongs);
    }
  });
}

function parseTitle(title) {

  var newTitle = title
  .replace(/[-!$%^&_+|~=`{}:";'<>?,.\/]/g, '')
  .replace(/  /g, ' ')
  .replace(/\[.*\]/g, '')
  .replace(/lyrics/g, '')
  .replace(/\(.*\)/g, '')
  .replace(/\*.*\*/g, '')
  .replace(/   /g, ' ');

  return newTitle;
}

function play() {
  clearTimeout(playNext);
  var song = SpotifiedList[Math.floor((Math.random() * SpotifiedList.length))];
  window.location = song.url;
  x = (song.length / 1000) >> 0;
  seconds = x % 60
  x = (x / 60) >> 0;
  minutes = x % 60;
  console.log('Playing: ' + song.name + ' (' + minutes + ':' + seconds + ')');
  playNext = setTimeout(play, song.length);
}


texts:
I'm doing some exercises from another good website aimed at a similar problem - exercism.io, and my 1st C++ problem was to pass a certain test suite.

Here is the README for relevant information:

  Bob is a lackadaisical teenager. In conversation, his responses are very limited.

  Bob answers 'Sure.' if you ask him a question.

  He answers 'Whoa, chill out!' if you yell at him.

  He says 'Fine. Be that way!' if you address him without actually saying
  anything.

  He answers 'Whatever.' to anything else.

Here is the test suite:

BOOST_AUTO_TEST_CASE(stating_something)
{
    BOOST_REQUIRE_EQUAL("Whatever.", bob::hey("Tom-ay-to, tom-aaaah-to."));
}

BOOST_AUTO_TEST_CASE(shouting)
{
    BOOST_REQUIRE_EQUAL("Whoa, chill out!", bob::hey("WATCH OUT!"));
}

BOOST_AUTO_TEST_CASE(asking_a_question)
{
    BOOST_REQUIRE_EQUAL("Sure.", bob::hey("Does this cryogenic chamber make me look fat?"));
}

BOOST_AUTO_TEST_CASE(talking_forcefully)
{
    BOOST_REQUIRE_EQUAL("Whatever.", bob::hey("Let's go make out behind the gym!"));
}

BOOST_AUTO_TEST_CASE(using_acronyms_in_regular_speech)
{
    BOOST_REQUIRE_EQUAL("Whatever.", bob::hey("It's OK if you don't want to go to the DMV."));
}

BOOST_AUTO_TEST_CASE(forceful_questions)
{
    BOOST_REQUIRE_EQUAL("Whoa, chill out!", bob::hey("WHAT THE HELL WERE YOU THINKING?"));
}

BOOST_AUTO_TEST_CASE(shouting_numbers)
{
    BOOST_REQUIRE_EQUAL("Whoa, chill out!", bob::hey("1, 2, 3 GO!"));
}

BOOST_AUTO_TEST_CASE(only_numbers)
{
    BOOST_REQUIRE_EQUAL("Whatever.", bob::hey("1, 2, 3"));
}

BOOST_AUTO_TEST_CASE(question_with_only_numbers)
{
    BOOST_REQUIRE_EQUAL("Sure.", bob::hey("4?"));
}

BOOST_AUTO_TEST_CASE(shouting_with_special_characters)
{
    BOOST_REQUIRE_EQUAL("Whoa, chill out!", bob::hey("ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!"));
}

BOOST_AUTO_TEST_CASE(shouting_with_no_exclamation_mark)
{
    BOOST_REQUIRE_EQUAL("Whoa, chill out!", bob::hey("I HATE YOU"));
}

BOOST_AUTO_TEST_CASE(statement_containing_question_mark)
{
    BOOST_REQUIRE_EQUAL("Whatever.", bob::hey("Ending with a ? means a question."));
}

BOOST_AUTO_TEST_CASE(prattling_on)
{
    BOOST_REQUIRE_EQUAL("Sure.", bob::hey("Wait! Hang on.  Are you going to be OK?"));
}

BOOST_AUTO_TEST_CASE(question_with_trailing_whitespace)
{
    BOOST_REQUIRE_EQUAL("Sure.", bob::hey("Are you ok? "));
}

BOOST_AUTO_TEST_CASE(silence)
{
    BOOST_REQUIRE_EQUAL("Fine. Be that way!", bob::hey(""));
}

BOOST_AUTO_TEST_CASE(prolonged_silence)
{
    BOOST_REQUIRE_EQUAL("Fine. Be that way!", bob::hey("   "));
}

Now here is my first-iteration code:

/*
 * #ifndef BOB_H
 * #define BOB_H
 *
 * #include <string>
 *
 * namespace bob {
 *     std::string hey(std::string);
 * }
 * #endif
*/

#include <algorithm>
#include <cctype>
#include "bob.h"

std::string bob::hey(std::string s){

    //remove any whitespaces
    std::string::size_type pos = s.find(' ');
    while(pos != std::string::npos){
        s.erase(s.find(' '), 1);
        pos = s.find(' ' , pos);
    }

    //Oh , he never said anything? Fine. Be that way!
    if(s.empty()) return "Fine. Be that way!";

    bool allUpper = std::all_of(s.begin() , s.end() , [](char ch){ if(std::isupper(ch) || !std::isalpha(ch)) return true; else return false; });
    bool atleastAlpha = std::any_of(s.begin() , s.end() , [](char ch){ if(std::isalpha(ch)) return true; else return false;  });

    //check for ques mark and say sure
    if(s.back() == '?' && (!allUpper || !atleastAlpha)) return "Sure.";

    //check for capital alphabets and yell Whoa, chill out!
    if(allUpper && atleastAlpha && !s.empty()) return "Whoa, chill out!";

    return "Whatever.";
}

In what ways can I improve my code? And is there anything I might be missing that is not according to the standards?


texts: Get _m_s time format from milliseconds value

texts:
I could have any value in milliseconds like:

  1040370

I must alert a specific converted time format : _m_s (ie:17m20s)

Here is how I do it:

function ms(a){
var m = a/1000/60,
s = Math.floor(('0.'+(''+m).split('.')[1])*60);
m = (''+m).split('.')[0];
alert(m+'m'+s+'s');
}

ms(1040370);

What do you think?
Is it satisfactory or is there a better way to accomplish the same?


texts: Binary search tree implementation in golang

texts:
I have started dabbling with golang. I wrote up a binary search tree implementation. I was wondering if there is a cleaner way. Here is my implementation:

type BNode struct {
    left  *BNode
    right *BNode
    data  int64
}

func insert(n **BNode, data int64) {
    if *n == nil {
        (*n) = &BNode{data: data, left: nil, right: nil}
    } else {
        if data <= (*n).data {
            insert(&(*n).left, data)
        } else {
            insert(&(*n).right, data)
        }
    }
}

I don't particularly like &(*n).right, is there syntax better than this? Something like &(n->right)

client code looks like:

var root *BNode = nil
insert(&root, 42)
insert(&root, 2)
insert(&root, -2)
insert(&root, 97)`


texts:
I am using Spring Framework, Hibernate and JUnit.  I am testing persisting of a UserEntity.

The UserEntity has the following associations:

ManyToMany - City
ManyToMany - ActivityCategory
ManyToOne - UserType

@Test
public void testCreateNotExistingEmail() {
    UserTypeEntity userTypeEntity = userTypeDao.find(1L);

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16);
    String password = encoder.encode("123456");

    List<CityEntity> cityEntities = new ArrayList<>();
    cityEntities.add(cityDao.find(1L));
    cityEntities.add(cityDao.find(2L));

    List<ActivityCategoryEntity> activityCategoryEntities = new ArrayList<>();
    activityCategoryEntities.add(activityCategoryDao.find(4L));
    activityCategoryEntities.add(activityCategoryDao.find(5L));

    UserEntity userEntity = new UserEntity();
    userEntity.setEmail("user@domain.com");
    userEntity.setIsActive(true);
    userEntity.setPassword(password);
    userEntity.setUserTypeEntity(userTypeEntity);
    userEntity.setCities(cityEntities);
    userEntity.setActivityCategories(activityCategoryEntities);

    userDao.create(userEntity);

    UserEntity userEntityCreated = userDao.find(userEntity.getId());

    Assert.assertNotNull(userEntityCreated);
    Assert.assertEquals(2, userEntityCreated.getCities().size());
    Assert.assertEquals(2, userEntityCreated.getActivityCategories().size());
}

Is there anything I could do better in the test?


texts: Checking whether one string matches another

texts:
This checks whether one string has all the chars in another string to make up that exact string. Counts matter so for, for example, str1 = 'abcdgbff' str2 ='aaabb' should return false because str1 only has one 'a' and 'b'.

How can I optimize my code further?

function scramble(str1, str2) {
  for (let i of str1) {
    if (str2.indexOf(i) != -1) {
      str2 = str2.slice(0, (str2.indexOf(i))) + str2.slice(str2.indexOf(i) + 1);
    }
  }
  return str2.length === 0;
}

// Example:
console.log(scramble('abcdgbff', 'aaabb')); // false


texts:
I had a simple function.

def graphite_json(target):
    url = 'http://server/render/?format=json&amp;target={}&amp;from=-10days'.format(target)
    r = requests.get(url)
    return r.json()

This contacts  a (Graphite) server, uses the requests library to get JSON string and convert it to a native list. Simple.

Then I wanted to test it and made a complete mess. My thinking was: I'll soon need more Graphite functionality so best to create a class, also have the requests library as an external dependency so that I can test better. What I ended up with is this:

The Business Logic:

import json
import requests

class Graphite(object):

    def __init__(self, server_url = 'http://server', requests_module=requests):
        self.requests = requests_module
        self.server_url = server_url

    def get(self, metric):

        url = '{}/render/?format=json&amp;target={}'.format(
            self.server_url, metric)
        response = self.requests.get(url)
        return response.json()

The Test

import json
import os
import pytest
from api.graphite import Graphite

@pytest.fixture(scope="session")
def sample_response():
    dirpath = os.path.dirname(os.path.realpath(__file__))
    with open('{}/data/graphite_response.json'.format(dirpath), 'r') as content_file:
        content = content_file.read()
    return content

@pytest.fixture(scope="session")
def mock_graphite_requests(sample_response):
    class Requests(object):
        def get(self, url):
            if 'target' not in url:
                raise NotImplementedError('need a target for graphite stats')
            class Response(object):
                def __init__(self, data):
                    self.data = data
                def json(self):
                    return json.loads(self.data)
            return Response(sample_response)
    return Requests()

@pytest.fixture(scope="session")
def graphite(mock_graphite_requests):
    return Graphite(requests_module=mock_graphite_requests)

def test_graphite_metric(graphite, sample_response):
    data = graphite.get('summarize(stats.gauges.items,"12hour","avg")')
    assert data == json.loads(sample_response)

I see this as weak because:

The test is huge! I'll have to maintain it, probably.
What am I actually testing? I think I only test that this class converts the response from JSON.

How can I fix this mess?


texts: Trying to use "this" to refer to a class's instance variable inside a function within the class's method in JavaScript

texts:
Hope that title makes sense.
This is part of an object I have:
The event listener attaches to the correct marker passed in the parameter but inside the function, this points to something else.

function UserGoogleMap($mapElement) {

    this.$mapElement = $mapElement;
    this.map = {};
    this.marker = null;
    this.coords = new google.maps.LatLng(25.2697, 55.3095)

    this.initMap = function () {
       google.maps.event.addListener(this.marker, 'dragend', function() {
         console.log(this.marker); // Undefined
         pos = this.marker.getPosition();
         $('#google-map-info').html("Latitude:" + pos.lat() + " Longitude: " +  pos.lng());
       });
    }

This works with a local variable:

    var marker = this.marker;
    google.maps.event.addListener(marker, 'dragend', function() {
        pos = marker.getPosition();
        $('#google-map-info').html("Latitude:" + pos.lat() + " Longitude: " +  pos.lng());
    });

this.initMap();

}

Is there anyway to rewrite this to use this.marker? or am I stuck with creating a local variable to refer to it? Also is there a way to have this.initMap() execute automatically instead of having to add this.initMap(); at the end of the class?

Any other feedback would be appreciated.


texts: BigDecimal wrapper that ignores zero operands

texts:
I want to perform mathematical operations on a range of values, where zeros should be ignored. This means that multiplication by zero does not result in zero but returns the first operand and likewise (\$5x0=5\$), division by zero does not throw an ArithmeticException but returns the first operand (\$5/0=5\$).

I would like to avoid testing for zero every time I need to make a calculation and would prefer that the calculation logic takes care of it.

My question is about the best way of approaching this problem. I will be using BigDecimal and thought of a simple implementation of the decorator pattern that adds functionality to the multiply and divide methods.

With this in mind, I developed the following code snippet:

public class BigDecimalWrapper extends BigDecimal {

public BigDecimalWrapper multiply(BigDecimal augend){
    if(augend.compareTo(BigDecimal.ZERO) != 0){
        return new BigDecimalWrapper(super.multiply(augend).doubleValue());
    } else {
        return this;
    }
}

public BigDecimalWrapper divide(BigDecimal augend){
    if(augend.compareTo(BigDecimal.ZERO) != 0){
        return new BigDecimalWrapper(super.divide(augend).doubleValue());
    } else {
        return this;
    }
}

public BigDecimalWrapper add(BigDecimal augend){
    return new BigDecimalWrapper(super.add(augend).doubleValue());
}

public BigDecimalWrapper subtract(BigDecimal augend){
    return new BigDecimalWrapper(super.subtract(augend).doubleValue());
}

// Some code omitted for brevity.
}

I expect to use it like this:

@Test
public void shouldMultiply() {
    BigDecimalWrapper v = new BigDecimalWrapper(10).multiply(BigDecimal.ZERO);
    assertThat(v).isEqualTo(new BigDecimal(10));
}

@Test
public void shouldDivide() {
    BigDecimalWrapper v = new BigDecimalWrapper(10).divide(BigDecimal.ZERO);
    assertThat(v).isEqualTo(new BigDecimal(10));
}

One of the problems that this is intended to resolve is in the calculation of quantity where it is not known if it is required to calculate length, area or volume. All that is known at the time of calculation are the dimensions. We may have only length, or length and width or height, width and length, therefor height may be 0 and while width and length are given. I would hope to be able to calculate with just one line of code as follows:

new BigDecimalWrapper(width).multiply(height).multiply(length);

Therefore, if height is zero, it will effectively ignore it and multiply width and length.

There are other similar situations where it will be used in this manner and is therefore worth the effort developing a solution for it.

Is this the best way to approach this problem? What alternative ways should I consider?


texts: Class to parse a file sanitizing each line with a set of methods

texts:
I am parsing a set of lines from a file, after reading the file content with Parser.read_file() I apply a set of methods to solve different issues each line may contain, like removing new lines, comments etc, and set a list of lines in the parser self.lines instance variable.

Filter methods are defined in Parser.filter as a list of names and executed after the file is read with self._sanitize().

import re
import os
import io
from operator import methodcaller

class Parser:

    # List of filters
    filters = ['_filter_comments',
               '_filter_new_lines',
               '_filter_empty_entries']

    def __init__(self, **kwargs):
        self.lines = kwargs.get('lines', [])
        self.file_path = kwargs.get('file_path', "data/data_ts.utf8")
        self.lines_count = kwargs.get('entries_count', None)

    def read_file(self):
        """ Reads file data applying filters from self.filters """
        __location__ = os.path.realpath(
            os.path.join(os.getcwd(), os.path.dirname(__file__)))
        with io.open(os.path.join(__location__, self.file_path), "r",
                     encoding='utf-8') as f:
            self.lines = f.readlines()
            self._sanitize()

    def _sanitize(self):
        for fn in self.filters:
            f = methodcaller(fn)
            f(self)

    def _filter_comments(self):
        """ remove lines starting with # or #! """
        self.lines = [line for line in self.lines
                      if not line.startswith(("#", "#!"))]

    def _filter_new_lines(self):
        self.lines = [line.strip('\n') for line in self.lines]

    def _filter_empty_entries(self):
        self.lines = [line for line in self.lines if line.strip()]

Issues

I think that the pythonic way to write those filters in one line as [line.strip('\n') for line in self.lines if line.strip() and if not line.startswith(("#", "#!")] would make it harder to read and unit test them or it would be better that way?
Should the _sanitize method be called after reading the file or would it make more sense to put it in the setter property of self.lines like:

@lines.setter
def lines(self, lines):
      self.lines = lines
      self._sanitize()

Is there any better option to arrange the above code or a design pattern like putting the sanitize method outside the Parser class and receiving a list of lines and returning the sanitized list instead of working always with self.list?


texts: Attempting to run multiple simulations of the Gillespie algorithm for a set of stochastic chemical reactions in less than 10 minutes

texts:
I have written Python code that generates a plot. In the code below, when I set maxtime = 0.1, the program takes ~50s and when I set maxtime = 1, it takes ~420s. I need to run it for maxtime = 1000.

I am familiar with Python syntax and writing "Matlabic" code, but am lost in writing natively "Pythonic" code. As a result, I need help in optimizing this code for runtime, specifically in the two outer for loops and inner while loop.

How can I make the code suitable for use with Numba or Cython?
If that's not possible, do I need to use functions, or map, or lambda statements?

Unfortunately, my Spyder IDE for Python is freezing up every time I try to profile the code. I would include those details if I could!

import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
import math

maxtime = 1
Qpvec = np.logspace(-2,1,101,10)
lenQp = len(Qpvec)
delta = 1e-3
P0vec = Qpvec/delta
SimNum = 100
PTotStoch = np.zeros((SimNum,lenQp))
k_minus = 1e-3
k_cat = 1-1e-3
k_plus = 1e-3
zeta = 1e-4
D0 = 10000
kappa_M = (k_cat+k_minus)/zeta
QpDeg = np.true_divide(1000*D0*Qpvec*k_cat,1000*Qpvec + kappa_M)

for lenQpInd in range(0,lenQp):
    for SimNumInd in range(0,SimNum):
        Qp = Qpvec[lenQpInd]
        P0 = P0vec[lenQpInd]
        DP0 = 0
        P = math.floor(P0)
        DP = DP0
        D = D0
        time = 0

        while time < maxtime:
            u_time = pl.rand()
            u_event = pl.rand()
            rates=np.array([Qp,zeta*P*D,k_minus*DP,k_cat*DP])
            PTot = P + DP
            kT = np.sum(rates)
            tot = np.cumsum(rates)
            deltaT = -np.log(1-u_time)/kT
            time += deltaT
            if time > maxtime:
                PTotStoch[SimNumInd,lenQpInd] = PTot
                break
            elif u_event*kT < tot[0]:
                P += 1
            elif u_event*kT < tot[1]:
                P -= 1
                DP += 1
                D -= 1
            elif u_event*kT < tot[2]:
                P += 1
                DP -= 1
                D += 1
            elif u_event*kT < tot[3]:
                DP -= 1
                D += 1

PMean = PTotStoch.mean(axis=0)
PStd = PTotStoch.std(axis=0)

plt.figure(0)
plt.plot(Qpvec,PMean,marker=".")
plt.errorbar(Qpvec,PMean,yerr = 2*PStd, xerr = None)
plt.show()


texts:
I've been trying to practice more Python recently so I decided to try and make different simple text-based game programs. I'd hope anybody could help me see how to make the code neater or more efficient in any aspect.

import random

words = []
guessed_letters = []
word_guess = []
joined_word = None

def fill_list():
    f = open('words.txt', 'r')
    for line in f:
        if len(line.strip()) > 3:
            words.append(line.strip())
    f.close()

def reset(secret):
    for letter in secret:
        word_guess.append('_')

def random_word(word_list):
    chosen = random.choice(word_list)
    return chosen

def guess_letter():
    while True:
        letter = input('Guess a letter a-z: ').lower().strip()
        if len(letter) != 1:
            print('Enter a single character only')
        elif not letter.isalpha():
            print('Enter only alphabetical characters')
        elif letter in guessed_letters:
            print('Already guessed {}'.format(letter))
        else:
            return letter

def print_opening():
    print('Welcome to Hangman!\n'
          'Try to guess a random word one letter at a time\n'
          'Good luck and have fun!\n')

def play_again():
    again = input().lower()
    if again.lower().startswith('y'):
        return True
    return False

def play():
    fill_list()
    tries = 5

    while True:
        print_opening()
        secret_word = random_word(words)
        reset(secret_word)

        while tries != 0 and '_' in word_guess:
            print('You have {} tries left'.format(tries))
            joined_word = ''.join(word_guess)
            print(joined_word)

            player_guess = guess_letter()
            for index, letter in enumerate(secret_word):
                if player_guess == letter:
                    word_guess[index] = player_guess

            guessed_letters.append(player_guess)

            if player_guess not in secret_word:
                print('Wrong!')
                tries -= 1

        if '_' not in word_guess:
            print('You win!\n{} was the word!\n'.format(secret_word))
        else:
            print('You lose!\nThe word was {}'.format(secret_word))

        print('Would you like to play another game? y/n')

        if play_again():
            word_guess.clear()
            tries = 5
        else:
            print('Thanks for playing!')
            break

if __name__ == '__main__':
    play()


texts: Transforming a Python dictionary into CSS

texts:
Recently I had the idea to write a module for the transformation of the dictionary into valid CSS code. And I would like to hear your comments on my code.
License MIT, BSD etc.

The code is very simple:

#pss.py

class PSS:
    def __init__(self, obj):
        self.obj = obj
        self.__data = {}
        self.__parse(obj)

    def __repr__(self):
        return self.__build(self.obj)

    def __build(self, obj, string = ''):
        for key, value in sorted(self.__data.items()):
            if self.__data[key]:
                string += key[1:] + ' {\n' + ''.join(value) + '}\n\n'

        return string

    def __parse(self, obj, selector = ''):
        for key, value in obj.items():
            if hasattr(value, 'items'):
                rule = selector + ' ' + key
                self.__data[rule] = []
                self.__parse(value, rule)

            else:
                prop = self.__data[selector]
                prop.append('\t%s: %s;\n' % (key, value))

import module:

#test.py

from pss import *

css = PSS({
    'html': {
        'body': {
            'color': 'red',
            'div': {
                'color': 'green',
                'border': '1px'
            }
        }
    }
})

print(css)

Result:

html body {
        color: red;
}

html body div {
        color: green;
        border: 1px;
}

So I need your advice to improve the quality of the code.
Perhaps there are still places that can be done easier?