texts:
I am learning React and wanted to implement a todo app using function components. Any suggestions and criticism is welcome, especially regarding best practices.

import React, {useState} from 'react';

class Todo {
  constructor(id, description, complete) {
    this.id = id;
    this.description = description;
    this.complete = complete;
  }
}

export default () => {

  const [idCounter, setIdCounter] = useState(1);
  const [todoList, setTodoList] = useState([]);
  const [todoDescription, setTodoDescription] = useState('');

  function addTodo() {
    setTodoList(
      [...todoList, new Todo(idCounter, todoDescription, false)]
    );
    setIdCounter(idCounter + 1);
    setTodoDescription('');
  }

  function markTodoItemComplete(id) {
    const todoListClone = todoList.slice();
    todoListClone[id - 1].complete = true;
    setTodoList(todoListClone);
  }

  return <>
    {todoList.map((todoItem) => {
      return (
        <React.Fragment key={todoItem.id}>
          {todoItem.id} - {todoItem.description} - {todoItem.complete ? 'Completed' : 'Waiting'}
          <button
            onClick={() => markTodoItemComplete(todoItem.id)}
            disabled={todoItem.complete}>
            Mark as complete
          </button>

        </React.Fragment>
      );
    })}

    <input
      onChange={e => setTodoDescription(e.target.value)}
      value={todoDescription}
    />

    <button
      disabled={!todoDescription}
      onClick={addTodo}>Add Todo
    </button>
  </>
}


texts:
I wrote an extension to create a string-representation by an object:

public static string ToString<T>(this T @this, Func<T, string> predicate) where T: class
{
    return predicate(@this);
}

So I can do something like

return handler.GetUserById(id)?.ToString(x => $"{x.LastName}, {x.FirstName}");

which gives me either null if the user is null or otherwise e.g. "Miller, Peter"

My question: is this a good extension? Makes it sense? Anything I didn't consider?
And what about the null-thing? Should I check the null value in the extension? Imho, the thrown NullReferenceException is okay, if s.o. calls this with a null object.


texts:
I am a beginner in Python and have just coded a simple web scraper for a webpage article, output to a text file, using BeautifulSoup and List.

The code is working fine, but I'm wondering if anybody would know a more efficient way to achieve the same.

import requests
page = requests.get('https://www.msn.com/en-sg/money/topstories/10-top-stocks-of-2017/ar-BBGgEyA?li=AA54rX&ocid=spartandhp')

# 2. Parsing the page using BeautifulSoup
import pandas as pd
from bs4 import BeautifulSoup
soup = BeautifulSoup(page.content, 'html.parser')

# 3. Write the context to a text file
all_p_tags = soup.findAll('p') # Put all <p> and their text into a list
number_of_tags = len(all_p_tags) # No of <p>?

x=0
with open('filename.txt', mode='wt', encoding='utf-8') as file:
    title = soup.find('h1').text.strip() # Write the <header>
    file.write(title)
    file.write('\n')
    for x in range(number_of_tags):
        word = all_p_tags[x].get_text() # Write the content by referencing each item in the list
        file.write(word)
        file.write('\n')
    file.close()


texts: Creating website via SQL table and PHP object

texts:
I wanted to try keeping the content of a website (mostly) in a SQL table and have made the basic template for the body.  Set the $pageName and include this template.

class Page {
  public $content = [];
  public $heading;
}

$page = new Page();

$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
/* check connection*/
if ($conn->connect_errno) {
  die("Failed to connect with MySQL: " . $conn->connect_errno);
};

$sql = "SELECT type, heading1, content1, style FROM $table WHERE page = '$pageName' ORDER BY ord";
$result = mysqli_query($conn, $sql);

while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
        switch($row['type']){
          case "content":
            $page->content[] = array("content" => '
' . $row['content1'] . '
', "heading" => "
" . $row['heading1'] . "
", "style" => $row['style']);
            break;
          case "heading":
            $page->heading = "
" . $row['heading1'] . "
";

            if ($row['content1']) {
              $page->heading .= "
" . $row['content1'] . "
";
            }
        }
    }

  mysqli_close($conn);
 ?>

  <?php echo $page->heading; ?>

<?php
for ($i=0; $i < count($page->content); $i++) {
  echo "
content[$i]["style"]."'>";
  echo $page->content[$i]["heading"];
  echo $page->content[$i]["content"];
  echo "
";
}
?>

I'm planning on adding more types than content and heading as needed.  I will also add includes such as HTML head/meta, navbar, and footer.

I just wondered what people thought of this (besides "why?").


texts: Find mobile phone contact according to number typed

texts:
I am using the code below trying to replicate the mobile phone feature that displays one or more contact names according to the numbers typed.

This code is intended to be used on a JavaScript course I am teaching, so I try to keep it as simple as possible in order to walk the students through a possible scenario and the required steps to implement a solution programmatically.

I would like to hear any suggestions for changes or comments before moving this example to class.

Thank you very much!

(You can find the full code, along with some pretty styling at this codepen link)

HTML:

Numbers to try:

  Send SMS
  <input type="text" id="number" name="number" placeholder="Enter telephone number">

JAVASCRIPT:

const contacts = {
  kostas: 6986100100,
  maria: 6986100200,
  george: 6986300300,
  sofia: 6986300400,
  chris: 6987500500,
  marina: 6944600600
}

const input = document.querySelector("#number");
const found = document.querySelector(".found");

input.addEventListener( "keyup", handleKeyUp );

function handleKeyUp( e ){

  found.innerHTML = "";

  Object.entries(contacts).map((contact)=>{

    let [ key, value ] = contact;
    let inputValue = e.target.value;
    value = String( value );
    if ( value.indexOf( inputValue ) === 0 ){
      found.innerHTML += `

          ${key}:
          ${value.replace( inputValue, `<span>${ inputValue }</span>` )}

      `;

    }

  })
}

NOTES: Since this is intended for an audience of beginners, best practices, code organization and probably performance considerations are of great importance here.


texts:
I'm trying to write a Python class that creates a matrix of zeros, then uses a random number generator to pick 'seats' on the matrix. It changes the zero in that seat to a one, until the matrix is all ones. Can someone critique/correct my code? (I also want the 'agent' to check its surroundings on the matrix, and try 3 times to find a seat that is 2 seats away from any ones.)

import random
import numpy as np
#cs is grid size or seats, ns is number of agents
class Seats():
    def __init__(self, cs, ns):
        self.cs = cs
        self.ns = ns
        self.seats = np.zeros([self.cs, self.cs],dtype=int)

    def foundseat(self):
        foundseat = False
        tries = 0
        while foundseat == False and tries <= 3:
            x = random.randint(0, self.cs)
            y = random.randint(0, self.cs)
            if self.seats[x][y] < 1:
                self.seats[x][y] = 1
                foundseat = True
            else:
                tries += 1

   def goodseat(self, x,y):
    empty_neighbors = 0
    for neighbor_x in range(x-1,x+1):
        for neighbor_y in range(y-1,y+1):
            if self.seats[neighbor_x][neighbor_y] == 0:
                empty_neighbors = empty_neighbors + 1


texts:
As an exercise in learning Scala, I implemented a square root function like this:

  def sqrt(x: Double): Double = {
    if (x < 0) throw new IllegalArgumentException("negative numbers not allowed")
    val threshold = if (x < 1) x / 1e15 else 1e-12
    def sqrt(x: Double, p: Double): Double = {
      if (p == x / p) p  // without this condition, non-termination with 1e50
      else if (Math.abs(p * p - x) < threshold) {
        def diff1 = Math.abs(x - p * p)
        def diff2 = Math.abs(x - x / p * x / p)
        if (diff1 < diff2) p else x / p
      }
      else sqrt(x, (p + x / p) / 2)
    }
    sqrt(x, x / 2)
  }

The implementation passes these unit tests:

  test("sqrt 2") {
    assert(sqrt(2) === Math.sqrt(2))
  }

  test("sqrt 1e-3") {
    assert(Math.abs(1e-3 - sqrt(1e-3) * sqrt(1e-3)) ===
      Math.abs(1e-3 - Math.sqrt(1e-3) * Math.sqrt(1e-3)))
  }

  test("sqrt 1e-20") {
    assert(sqrt(1e-20) === Math.sqrt(1e-20))
  }

  test("sqrt 1e-21") {
    assert(sqrt(1e-21) === Math.sqrt(1e-21))
  }

  test("sqrt 1e20") {
    assert(sqrt(1e20) === Math.sqrt(1e20))
  }

  test("sqrt 1e50") {
    assert(sqrt(1e50) === Math.sqrt(1e50))
  }

My questions:

How can I improve this?
Notice the unit test for the case of 1e-3. It's more complex than the others to compensate for the difference between sqrt and Math.sqrt. Although the both sqrt and Math.sqrt are equally incorrect (the square of both have the same discrepancy with x), I wonder if I can change the implementation to match the result of Math.sqrt.
I found the error thresholds for < 1 and >= 1 through trial and error: all unit tests pass with these values and some would fell if I stretched the limits further. I'm wondering if there is a better, proper way of setting suitable thresholds based on x and the numeric limits of the language.


texts:
My implementation works, but it looks very ugly. Curious to see how it's better implemented.

The zipWith function takes a list of lists (List[List[A]]), or a row with columns if you like. It will then transform this into a column with rows and applies a function List[A]=>B to obtain a List[B]. Hopefully the unit test below explains this better.

  test("zipWith"){
    val input = List(List(1,2,3), List(4,5,6), List(7,8,9))
    val expected = List("1::4::7", "2::5::8", "3::6::9")
    assert(zipWith(input)(_.mkString("::")) === expected)
  }

and the implementation is:

  def zipWith[A, B](lists: List[List[A]])(f: List[A] => B): List[B] = {
    @tailrec
    def loop(acc: List[B], input: List[List[A]]): List[B] = {
      val init = (Nil: List[List[A]], Nil: List[A])
      val (left, zipped) = input.foldLeft(init)((z, a) => {
        val (tails, heads) = z
        (a.tail :: tails, a.head :: heads)
      })
      if (left.foldLeft(false)(_ || _.isEmpty))
        f(zipped.reverse) :: acc
      else
        loop(f(zipped.reverse) :: acc, left.reverse)
    }

    loop(Nil, lists).reverse
  }


texts:
I have a need to turn various structures into byte arrays to be sent over serial port to another machine. I created generic extensions to turn any structure into a byte array and from a byte array back into a given structure.

I've not used the Marshal class often, and I'm uncomfortable manipulating memory on this level.

Do I need to explicitly free any memory?
Is this an efficient implementation? I'll be calling this a lot, it's important that it's efficient in both terms of memory and speed.

public static class StructureExtensions
{
    public static byte[] ToByteArray<T>(this T structure) where T : struct
    {
        var bufferSize = Marshal.SizeOf(structure);
        var byteArray = new byte[bufferSize];

        IntPtr handle = Marshal.AllocHGlobal(bufferSize);
        Marshal.StructureToPtr(structure, handle, true);
        Marshal.Copy(handle, byteArray, 0, bufferSize);

        return byteArray;
    }

    public static T ToStructure<T>(this byte[] byteArray) where T : struct
    {
        var packet = new T();
        var bufferSize = Marshal.SizeOf(packet);
        IntPtr handle = Marshal.AllocHGlobal(bufferSize);
        Marshal.Copy(byteArray, 0, handle, bufferSize);

        return Marshal.PtrToStructure<T>(handle);
    }
}

  Example Call:

var point = new Point(10,5);
byte[] serialized = point.ToByteArray();

Point deserialized = serialized.ToStructure<Point>();


texts: SQL Statement with a Select Statement Inside a Where Clause

texts:
Is there a more efficient way to write the following PLSQL statement? It seems inefficient to me to have the SQL statement nested inside the where clause.

SELECT REQ_ID
FROM REQUESTS R
WHERE P_REQ_ID IS NULL AND
      EXISTS (
        SELECT *
        FROM REQUESTS
        WHERE P_REQ_ID = R.REQ_ID
        )


texts: Using the XOR operator to calculate a checksum

texts:
As part of a Google Foobar challenge, I'm trying to answer a rather difficult problem that involves the use of the XOR operator to calculate a checksum. While my solution works, my algorithm works in O(n) time, while the desired solution seems to need to be faster.

You can see the text of the challenge here.

While I know the help presented in that thread is valid, the solution is in Python, and I'm working in Java. Could someone explain why my solution is inefficient, and how it could be improved? I'm a self-taught coder, so some of the arcana of compsci is a mystery to me.

static int answer(int start, int length) {
    int checksum = 0;
    int dividerPos = length;
    int count = start;
    int idx = 0;

    while(true) {
        if(dividerPos == 0)
            return checksum;
        else if (idx == dividerPos) {
            count += (length - dividerPos);
            --dividerPos;
            idx = 0;

            continue;
        }

        checksum ^= count;

        ++idx;
        ++count;
    }
}


texts: Loading the stylesheets and scripts on my website

texts:
I have made a simple website and I have tried to reduce load times as much as possible. All the content that is loaded is necessary.

Is there anything thing I can do to my code, such as structurally, to make it load even faster?

Side Note

I do not want to minify the HTML, as I want it to remain legible and I am not concerned about the content in the body, I am only concerned about the content in the  and the scripts at the bottom of the .

The website is hosted at http://discourse.rf.gd.

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, minimum-scale=1">
        <link rel="manifest" href="./manifest.webmanifest">
        <link rel="stylesheet" href="./src/stylesheet.css">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Muli:400,400i,700,700i,900,900i&display=swap">
        <title>Discourse</title>

        <fieldset>
            <legend>Login</legend>
            Username:
            <input type="text" name="username" id="username">

            Password:
            <input type="password" name="password" id="password">

            <input type="button" value="login" onclick="login()">

        </fieldset>


texts: Static wrapper class for log4net Logging - thread safety

texts:
I'm using log4net in my application and have a static Log class which creates an instance of ILog with a default log type, e.g CMS. The ILog instance is then used by the class to call the log4net logging methods passing in a LogItem type as the log message to enforce a strict logging format.

The user of the class can also change the logger targeted by the logger at runtime by setting a public static property LogType for example: Log.LogType = Enums.LogType.Database.

Here is the class:

/// <summary>
/// Log wrapper around ILog - enforces consistent log format.
/// </summary>
public static class Log
{
    private static ILog Logger = LogManager.GetLogger(LogType.CMS.ToString());

    /// <summary>
    /// Sets the Logger to be used.
    /// </summary>
    public static LogType LogType
    {
        set
        {
            Logger = LogManager.GetLogger(value.ToString());
        }
    }

    /// <summary>
    /// Logs information to the system.
    /// </summary>
    /// <param name="source">Source of the info.</param>
    /// <param name="description">Info description.</param>
    /// <param name="exc">Associated Exception object.</param>
    public static void Info(string source, string description, Exception exc = null)
    {
        Logger.Info(new LogItem() { Source = source, Description = description }, exc);
    }

    /// <summary>
    /// Logs a warning to the system.
    /// </summary>
    /// <param name="source">Source of the info.</param>
    /// <param name="description">Info description.</param>
    /// <param name="exc">Associated Exception object.</param>
    public static void Warn(string source, string description, Exception exc = null)
    {
        Logger.Warn(new LogItem() { Source = source, Description = description }, exc);
    }

    /// <summary>
    /// Logs an error to the system.
    /// </summary>
    /// <param name="source">Source of the info.</param>
    /// <param name="description">Info description.</param>
    /// <param name="exc">Associated Exception object.</param>
    public static void Error(string source, string description, Exception exc)
    {
        Logger.Error(new LogItem() { Source = source, Description = description }, exc);
    }
}

I'm concerned on whether the LogType prop would be thread safe, what would happen if this is changed by another class before the logger does its job?

I've read that log4net itself is thread safe and will block when calling the appenders - would having a single static class that everything logs through eventually cause a bottleneck?


texts: Writing a test to validate that the repo is formatted

texts:
I have a short test to validate that all committed files in the repo are formatted. I'm new to go so not sure what the best wat to do it is.

The error handling, in particular, is rather gruesome as it takes up roughly half of the lines.

package pack

import (
    "os"
    "os/exec"
    "path/filepath"
    "testing"
)

func TestFormatting(t *testing.T) {
    var commandArgs []string
    commandArgs = append(commandArgs, "-l")
    root := "../.."
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if filepath.Ext(path) != ".go" {
            return nil
        }
        absPath, e := filepath.Abs(path)
        if e != nil {
            return e
        }
        commandArgs = append(commandArgs, absPath)
        return nil
    })
    if err != nil {
        t.Logf(err.Error())
        t.Fail()
    }

    out, err := exec.Command("gofmt", commandArgs...).Output()
    if err != nil {
        t.Logf(err.Error())
        t.Fail()
    }
    output := string(out)
    if output != "" {
        t.Logf("Testing Formatting")
        t.Logf(output)
        t.Fail()
    }
}

How can it be improved?


texts: Validating sign up pages using Selenium Python

texts:
I have multiple sign up pages that I am currently testing. Each of the form have seprate fields. However, some share common fields(as you can see from signup page.py).

This is what I have so far(I am using Page Object method), I would like to know how I can improve my code to make it more robust.

Here is the signUp page.py:

class signupPage(Page):

    def __init__(self, driver):
        super(signupPage, self).__init__(driver)

    def SignupPage1139_CompanyOne(self):
        self.driver.get("https://abc.com/s_csignup.jsp?token=XVtQHUUGYFFaRhNaXxJaQVBRZEl2EnBo")
        self.driver.find_element_by_id("cname").clear()
        self.driver.find_element_by_id("cname").send_keys("QA EXTERNAL")
        self.driver.find_element_by_id("cf_2727675").clear()
        self.driver.find_element_by_id("cf_2727675").send_keys("Test")
        self.driver.find_element_by_id("cf_2697953").clear()
        self.driver.find_element_by_id("cf_2697953").send_keys("Test")
        self.driver.find_element_by_id("sbbut").click()
        self.assertEqual("Could not create organization, an organization with the entered criteria already exists.", self.close_alert_and_get_its_text())

    def SignupPage1139_CompanyTwo(self):
        self.driver.get("https://abc.com/s_csignup.jsp?token=XVtQHUUGYFFaRhNaXxJaQVBRZElzGnJt")
        self.driver.find_element_by_id("cname").clear()
        self.driver.find_element_by_id("cname").send_keys("QA EXTERNAL")
        self.driver.find_element_by_id("city").clear()
        self.driver.find_element_by_id("city").send_keys("Toronto")
        Select(self.driver.find_element_by_id("state")).select_by_visible_text("Ontario")
        self.driver.find_element_by_id("sbbut").click()
        self.assertEqual("Cannot update using new scripts as there is already a matching company", self.close_alert_and_get_its_text())

    def SignupPage1139_CompanyThree(self):
        self.driver.get("https://abc.com/s_csignup.jsp?token=XVtQHUUGYFFcRhZdXxJaQVBRZEl9HnRr")
        self.driver.find_element_by_id("cname").clear()
        self.driver.find_element_by_id("cname").send_keys("DO NOT DELETE - Pandora External")
        self.driver.find_element_by_id("cf_2698238").clear()
        self.driver.find_element_by_id("cf_2698238").send_keys("000000124")
        self.driver.find_element_by_id("sbbut").click()

Here is my test.py:

class MatchingContactCompany(BaseTestCase, unittest.TestCase):

    def setUp(self):
        super(MatchingContactCompany, self).setUp()

    def test_MatchingCompany(self):
        # form 1
        signup.obj = signupPage(self.driver)
        signup.obj.SignupPage1139_CompanyOne()
        # form 2
        signup.obj.SignupPage1139_CompanyTwo()
        # form 3 create the account and verify if the account was created
        signup.obj.SignupPage1139_CompanyThree()

   def tearDown(self):
       super(MatchingContactCompany, self).tearDown()

if __name__ == "__main__":
    unittest.main()


texts: React Smart and Dumb Components separation query

texts:
I have been working on React and would like to know best practices for separating smart and dumb components.

This example is a Parent controls state, but I have put the button UI in render. Should these go into child and implemented back to parent via callback or is that overkill?

class Child extends React.Component {
      constructor(props){
      super(props);
      }
      render() {
      return (

I said {this.props.greeting} {this.props.count} times

        );
      }
    }

    class Parent extends React.Component {
      constructor() {
        super();
        this.state = {
          count: 0,
          greeting: "Hello"
        };
      }

      sayHello() {
        this.setState((prevState, props) => {
        return {
          count: prevState.count + 1,
              greeting: "Hello"
               }
        }
      )};
        sayGoodBye() {
        this.setState((prevState, props) => {
        return {
          count: this.count = 1,
          greeting: "Goodbye"
               }
        }
      )};

      render() {
        return (

            <button onClick={() => this.sayHello() }>Say Hello</button>
            <button onClick={() => this.sayGoodBye() }>Say Goodbye</button>
          <Child count={this.state.count} greeting={this.state.greeting} />

        )

      }
    }

    ReactDOM.render(<Parent />, document.getElementById('app'));


texts:
I am trying to write a program to store/display a grid of size N x N with cells containing either a 1 or a 0 in preparation for further computation:

module Board where

import Data.List as List

data CellState = One | Zero deriving (Eq, Ord)

data Cell = Cell {cellPos :: (Int, Int), cellState :: CellState} deriving (Eq, Ord)

type Board = [Cell]

instance Show CellState where
  show One = "1"
  show Zero = "0"

instance Show Cell where
  show (Cell c x) = show (c,x)

genPositions :: Int -> [(Int, Int)]
genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

genCellState :: Int -> CellState
genCellState 0 = Zero
genCellState 1 = One

newBoard :: Int -> [Int] -> Board
newBoard i [x] = [Cell (round $ sqrt(fromIntegral i), round $ sqrt(fromIntegral i)) (genCellState x)]
  where positions = genPositions $ round $ sqrt(fromIntegral i)
newBoard i (x : xs) = [Cell (positions!!(i - 1 - length xs)) (genCellState x)] ++ newBoard i xs
  where positions = genPositions $ round $ sqrt(fromIntegral i)

What improvements can I make to this, both in terms of good practises and performance? I don't like Board being a list of Cells. I posted this on Stack Overflow by accident (have since deleted it) and someone recommended changing type Board = [Cell] to newtype Board = Board { getBoard :: Array (Int,Int) CellState } but I'm not too familiar with arrays in Haskell so not sure how this would work exactly. From what I have read they apply a function to the elements in the range [Int..Int] and return a list of tuples with the input and output.


texts:
I recently learned about Linq's deferred execution and a little clearer understanding of IEnumerable. I came back to some code that I had written and decided to change with Linq extension methods. (The method is a helper function for some custom Excel functions that I use.)

Overall the code kind of feels wrong readability-wise having to tack on values = values.exension like that. When I step through the debugger it seems to be behaving like I expect.

Is there a more readable way to express this function with or without linq extension methods? I fear I'm making things less readable and possibly micro-optimizing.

private static string Concatenate(IEnumerable<string> values
    , string between, string begin, string end
    , bool excludeDuplicates, bool includeBlanks)
{
    if (!includeBlanks)
        values = values.Where(v => v != string.Empty);

    if (excludeDuplicates)
        values = values.Distinct();

    values = values.Select(v => begin + v + end);

    return string.Join(between, values);
}

Here is what I previously used in case it is of interest.

private static string Concatenate(IEnumerable<string> Values, string BetweenString
    , string BeginString, string EndString, bool ExcludeDuplicates, bool IncludeBlanks)
{
    IEnumerable<string> IncludedValues = (
        from Value in Values
        where IncludeBlanks || Value.Length > 0
        select BeginString + Value + EndString
        );

    IEnumerable<string> StringValues;

    if (ExcludeDuplicates)
        StringValues = new HashSet<string>(IncludedValues);
    else
        StringValues = new List<string>(IncludedValues);

    return string.Join(BetweenString, StringValues);
}

EDIT:

To give a little more context for this function (I'll hedge a little here and say that I haven't changed these functions to be more readable yet, so I beg forgiveness now. :) )

The purpose of this function is that it gets used by two other functions RA.VCONCATENATE and RA.HCONCATENATE that will be Excel functions (using ExcelDNA). (I do plan on changing this to be more readable as well and make Values IEnumerable instead of IList). Note: I can't have optional "missing" parameters in Excel or overloading so I made extension methods for string, int, double and bool that convert unspecified parameters to a default.

[ExcelFunction(Category = "Extra Range Functions", Name = "RA.VCONCATENATE",
    Description = "Vertically Concatenates all values in the Range starting from Top to Bottom, then Left to Right.")]
public static string VerticalConcatenate(object[,] Range, object BetweenString, object BeginString, object EndString, object ExcludeDuplicates, object IncludeBlanks)
{

    List<string> Values = RangeValuesToList(Range, RangeEnumerateFirstDirection.Down); //Empty cells replaced with String.Empty
    string sBetweenString = BetweenString.Optional("");
    string sBeginString = BeginString.Optional("");
    string sEndString = EndString.Optional("");
    bool bExcludeDuplicates = ExcludeDuplicates.Optional(false);
    bool bIncludeBlanks = IncludeBlanks.Optional(false);

    return Concatenate(Values, sBetweenString, sBeginString, sEndString, bExcludeDuplicates, bIncludeBlanks);
}

RA.HCONCATENATE is the same except is uses RangeEnumerateFirstDirection.Right. The expected output of =RA.VCONCATENATE(A1:A5, ",", "^", "$", TRUE, FALSE) (if Range [A1:B3] values are { 1, 2, 2 }, {3, EMPTY, EMPTY} ) is: "^1$,^2$,^3$". RA.HCONCATENATE output is: "^1$,^3$,^2$".


texts: Should I use setters with null or no setter when null value?

texts:
I would like to know what are the drawbacks of setting values this way:

class PersonFactory
{
    public function createPerson($firstName = null, $lastName = null, $separator = null)
    {
        $person = new Person();
        $person
            ->setFirstName($firstName)
            ->setLastName($lastName)
            ->setSeparator($separator);

        return $person;
    }
}

And if this way would be more clear, sustainable or efficient

class PersonFactory
{
    public function createPerson($firstName = null, $lastName = null, $separator = null)
    {
        $person = new Person();
        if (!null === $firstName) {
            $person->setFirstName($firstName);
        }

        if (!null === $lastName) {
            $person->setLastName($lastName);
        }

        if (!null === $separator) {
            $person->setSeparator($separator);
        }

        return $person;
    }
}

Example call:

class PersonController extends Controller
{
    public function indexAction()
    {
        // get the PersonFactory instance
        $person = $this->get('person.factory')
            ->createPerson('Bob', 'Whatever', '-');

        return $this->render('some/file.html.twig', [
            'person' => $person
        ]);
    }
}

It feels like they are the same as null is already the value of an undefined variable, at least in PHP (looking at you Javascript).

So, would the only difference would be to call the setters even if it's not useful ?


texts:
I've written this very simple quiz program, I'm trying to get to grips with OOP (Object Orientated Programming), so I've started simple with very basic Classes. The nature of the code would have suited using functions but I wanted to practice with Python Classes.

Any comments or suggestions about my code would be most welcome, my ultimate goal is to be as pythonic as possible in future projects.

I've tried to follow Python PEP8 guidelines.

from colorama import *
import random
import os

init()

class StartQuiz():
    def __init__(self, capital_dict: str = {}, randomize_keys: str = []):
        self.capital_dict = capital_dict
        self.randomize_keys = randomize_keys

    def set_up(self):
        with open('capitals.txt') as file:
            for data in file:
                [country, capital] = data.split(',')
                self.capital_dict[country] = capital.strip()
            self.randomize_keys = list(self.capital_dict)
            random.shuffle(self.randomize_keys)
            return [self.capital_dict, self.randomize_keys]

class DisplayAnswer(StartQuiz):
    def __init__(self, capital_dict, randomize_keys):
        super().__init__(capital_dict, randomize_keys)

    def show_answer(self):
        for city in self.randomize_keys:
            print(Fore.BLUE + f'{self.capital_dict[city]}', end='  ')
        print('\n')

class DisplayQuestion(StartQuiz):
    score: int = 0
    def __init__(self, capital_dict, randomize_keys):
        super().__init__(capital_dict, randomize_keys)

    def ask_question(self):
        for country in self.randomize_keys:
            print(Fore.YELLOW + f'Capital of {country} is ? ', end='')
            answer = input(Fore.WHITE)
            if answer.lower() == self.capital_dict[country].lower():
                print(Fore.BLUE + 'Correct!')
                self.score += 1
            else:
                print(Fore.RED + 'Incorrect!')
        return [self.score, len(self.capital_dict)]

def main():

    startQuiz = StartQuiz()
    while True:
        os.system('CLS')
        print(Fore.WHITE + '***  Capital City Quiz  ***\n')
        print('Choose the correct city from the list below:\n')

        DisplayAnswer(startQuiz.set_up()[0], startQuiz.set_up()[1]).show_answer()
        total_score = DisplayQuestion(startQuiz.set_up()[0], startQuiz.set_up()[1]).ask_question()

        print(Fore.WHITE + f'\nYou scored: {total_score[0]} out of {total_score[1]}')
        input('\nPress <Enter> to play again')

if __name__ == "__main__":
    main()


texts: C code, rewritten to use a Person struct without pointers

texts:
I'm new to C and I have been assigned the task of converting some code that uses structs with pointers to code that doesn't use pointers. I would be interested to know if the code I have written is 'good' code and how I could improve it. Here is the code I have written which creates a Person struct then creates a few sample persons.

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

struct person {
    char *name;
    int age;
    int height;
    int weight;
};

typedef struct person Who;

struct person Person_create(char *name, int age, int height, int weight)
{

    Who w;

    w.name = strdup(name);
    w.age = age;
    w.height = height;
    w.weight = weight;

    return w;
}

void Print_person(Who w)
{
    printf("Name: %s\n", w.name);
    printf("\tAge: %d\n", w.age);
    printf("\tHeight: %d\n", w.height);
    printf("\tWeight: %d\n", w.weight);
}

int main(int argc, char *argv[])
{
    struct person ryan = Person_create("Ryan McGovern", 37, 182, 67);
    struct person sandy = Person_create("Sandy McGovern", 32, 167, 49);

    printf("Ryan is at memory location: %p\n", &ryan);
    Print_person(ryan);

    printf("Sandy is at memory location: %p\n", &sandy);
    Print_person(sandy);

    ryan.age += 2;
    ryan.weight += 4;

    Print_person(ryan);

    return 0;
}

Prints out:

Ryan is at memory location: 0x7fff52b7ea68
Name: Ryan McGovern
    Age: 37
    Height: 182
    Weight: 67
Sandy is at memory location: 0x7fff52b7ea50
Name: Sandy McGovern
    Age: 32
    Height: 167
    Weight: 49
Name: Ryan McGovern
    Age: 39
    Height: 182
    Weight: 71

Original code using pointers (from the book Learn C the Hard Way by Z. A. Shaw):

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

struct Person {
    char *name;
    int age;
    int height;
    int weight;
};

struct Person *Person_create(char *name, int age, int height, int weight)

{

    struct Person *who = malloc(sizeof(struct Person));
    assert(who != NULL);

    who->name = strdup(name);
    who->age = age;
    who->height = height;
    who->weight = weight;

    return who;
}

void Person_destroy(struct Person *who)
{
    assert(who != NULL);
    free(who->name);
    free(who);
}

void Person_print(struct Person *who)
{
    printf("Name: %s\n", who->name);
    printf("\tAge: %d\n", who->age);
    printf("\tHeight: %d\n", who->height);
    printf("\tWeight: %d\n", who->weight);
}

int main(int argc, char *argv[])
{
    struct Person *ryan = Person_create("Ryan McGovern", 37, 182, 67);

    struct Person *sandy = Person_create("Sandy McGovern", 32, 167, 48);

    // print them out and where they are in memory
    printf("Ryan is located at memory location %p:\n", ryan);
    Person_print(ryan);

    printf("Sandy is at memory location %p:\n", sandy);
    Person_print(sandy);

    // Make them age 20 years and print them out again
    ryan->age += 20;
    ryan->height -= 2;
    ryan->weight += 4;
    Person_print(ryan);

    sandy->age += 20;
    sandy->weight += 10;
    Person_print(sandy);

    // Clean up
    Person_destroy(ryan);
    Person_destroy(sandy);

    return 0;
}


texts:
I'm learning C and I am currently implementing a memory pool.

I'm writing it in steps, first I implemented a fixed-sized memory pool then I will try to implement a memory pool with a known size of elements but an unknown number of elements and ultimately try to write a generic one that is just a block of memory that can allocate any size.

The pool is actually a block of memory that is initialized with values that are pointers to the next memory like so:

 ______________
|0x8 |0x10|NULL|
|____|____|____|
 ^    ^    ^
 0x0  0x8  0x10

I want to know if I'm heading in the right direction.
There is the code

allocator.h:

#include <stdlib.h>

typedef struct FixedPoolAllocator FixedPoolAllocator;

FixedPoolAllocator* FixedPoolAllocator_new(size_t nmemb, size_t size);

void* FixedPoolAllocator_alloc(FixedPoolAllocator *allocator);

void FixedPoolAllocator_free(FixedPoolAllocator *allocator, void *ptr);

void FixedPoolAllocator_destroy(FixedPoolAllocator *allocator);

allocator.c:

#include "allocator.h"

#define MAX(a, b) (((a) > (b)) ? (a) : (b))

typedef struct FixedPoolAllocator {

    // The currently free space in which a value can be stored
    size_t *currentFree;
    size_t numOfMembers;
    size_t memberSize;
    // The actual memory block, It is of type char* so that pointer arithmetic will be easier
    char *mem;

} FixedPoolAllocator;

FixedPoolAllocator* FixedPoolAllocator_new(size_t nmemb, size_t size)
{
    if (0 == size || 0 == nmemb) return NULL;

    FixedPoolAllocator *ret = malloc(sizeof *ret);
    if (NULL == ret) return NULL;

    // Make sure that the size of each member is atleast size_t so that the members can store a memory address
    size_t member_size = MAX(sizeof(size_t), size);

    ret->mem = malloc(nmemb * member_size);
    if (NULL == ret->mem) return NULL;
    // The initial free member
    ret->currentFree = (size_t*)ret->mem;

    ret->numOfMembers = nmemb;
    ret->memberSize = size;

    size_t *temp = ret->currentFree;

    // Assign each member with the address of the next member
    size_t i;
    for (i = 0; i < nmemb - 1; i++) {
        *temp = (size_t) (ret->mem + (i+1) * member_size);
        temp = (size_t*) ((char*)temp + member_size);
    }

    // The last member points to NULL
    *temp = (size_t)NULL;

    return ret;
}

void* FixedPoolAllocator_alloc(FixedPoolAllocator *allocator)
{
    if (NULL == allocator || NULL == allocator->currentFree) return NULL;

    // Return the currently free member and update currentFree to the next member in the list
    void *ret = allocator->currentFree;
    allocator->currentFree = (size_t*)*allocator->currentFree;

    return ret;
}

void FixedPoolAllocator_free(FixedPoolAllocator *allocator, void *ptr)
{
    size_t ptr_as_value = (size_t)ptr;

    // Assign the pointed value with the current free member
    *(size_t*)ptr = (size_t)allocator->currentFree;
    // Update the currenty free member to be the one that was just freed
    allocator->currentFree = ptr;
}

void FixedPoolAllocator_destroy(FixedPoolAllocator *allocator)
{
    free(allocator->mem);

    free(allocator);
}


texts:
I would like a complete threshing of this code so that I can see what I did wrong and what I am using incorrectly.

I made this super simple, trying to learn a little bit about List<T> while I was doing this.  I have never actually tried to do this before, so I thought it would be a good learning experience, but it just seems too easy (simple), especially when I look at other people's renditions of this algorithm.  Am I missing a vital piece of the algorithm?

Note: Console app, if you want to see all the primes you will have to set the buffer of your console.

static void Main(string[] args)
{
    var upperLimit = 9999;
    List<Int64> primes = new List<Int64>();
    for (Int64 i = 2; i < upperLimit; i++)
    {
        primes.Add(i);
    }
    List<Int64> numbers = primes;

    for (var i = 2; i < upperLimit; i++)
    {
        foreach (var number in numbers.ToArray())
        {
            if (number == i) { continue; }
            if (number % i == 0)
            {
                primes.Remove(number);
            }
        }
        numbers = primes;
    }
    primes.ForEach(delegate(Int64 prime)
    {
        Console.WriteLine(prime.ToString());
    });

    Console.WriteLine("The Last Prime is " + primes[primes.Count - 1]);
    Console.WriteLine("what are you waiting for? Exit the program!");
    Console.ReadLine();
}

I figured that I would give this a try after I saw this.

The reason for var number in numbers.ToArray() is because it wouldn't let me .Remove(number) from primes if I foreach'ed through the list otherwise.  Credit to this answer for the solution to my dilemma.

Follow-up can be found here


texts:
Can random string generation be faster in Java?

Here is my current code

import java.util.ArrayList;
import java.util.List;

public class FastestStringGeneration {

    private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final char[] ch = ALPHA_NUMERIC_STRING.toCharArray();
    private static final java.util.concurrent.ThreadLocalRandom random = java.util.concurrent.ThreadLocalRandom.current();

    public static void main(String[] java) {
        // warmup code
        String[] warmUp = new String[10000];
        for (int j=0; j<10000; j++){
           warmUp[j] = getAlphaNumeric(1024);
        }
        // real code begins
        int numIterations = 1000000;
        String[] randomStrings = new String[numIterations];
        long start = System.currentTimeMillis();
        for(int i=0; i<numIterations; i++){
            randomStrings[i] = getAlphaNumeric(1024);
        }
        System.out.println(System.currentTimeMillis()-start);
        System.out.println(randomStrings.length);
    }

    public static String getAlphaNumeric(int len) {
        char[] c = new char[len];
        for (int i = 0; i < len; i++) {
            c[i] = ch[random.nextInt(ch.length)];
        }
        return new String(c);
    }
}

The total time it takes to generate 1 million random strings is about ~ 5.9 seconds. Can it be faster?

I was using java.util.Random but when I changed to java.util.concurrent.ThreadLocalRandom according to comments below I got the most performance improvement!


texts: SQL query with dynamic unpivot+pivot for cross product

texts:
In this Data Explorer query I am trying to do the following:

For each tag:

Compute sum of answer scores in this tag ("S")
Compute count of answers in this tag ("A")
For each tag class (Bronze, Silver, Gold)
add two columns:

S divided by this class's score goal
A divided by this class's answer goal

I wanted to do this in the most general way possible, allowing more tag classes/goals to be added later. I came up with this:

-- Predefined tag badge goals
... TagBadges as (
  select * from
    (values
      (1, 'Bronze', 100, 20),
      (2, 'Silver', 400, 80),
      (3, 'Gold', 1000, 200))
    as Badge(Idx, Class, Score, Answers)
),

-- Progress per tag, per badge class
TypeProgress as (
  select
    RawData.TagName,
    format(iif(RawData.Score > TagBadges.Score, 1,
               cast(RawData.Score as float)/TagBadges.Score), '#0.#%') as Score,
    format(iif(RawData.Answers > TagBadges.Answers, 1,
               cast(RawData.Answers as float)/TagBadges.Answers), '#0.#%') as Answers,
    TagBadges.Class
  from RawData cross join TagBadges
),

-- Combine class & type columns
AllProgress as (
  select TagName, Progress, Class+' '+Type as Category
  from TypeProgress
  unpivot (Progress for Type in (Score, Answers)) p
) ...

But in the end I still had to list all the cases (2 × 3 = 6) explicitly:

select *
from AllProgress
pivot (
  max(Progress) for Category in
    ([Bronze Score], [Bronze Answers],
     [Silver Score], [Silver Answers],
     [Gold Score], [Gold Answers])
) q

Is there a better way of doing this?


texts: Compare performance of simple addition on one to many cores

texts:
I read recently that ENIAC originally was capable of 5000 additions per second.  Naturally, I had to test my own laptop's capabilities and this became an instructive experiment in F#, which I suck at.

So, I am looking for feedback in two areas:

What is the most concise way to write this in F#, or at least most closely aligned with the functional paradigm?
Did I miss something for performance? Can this be done in a much more performant fashion?

module Program

open System
open System.Diagnostics

[<AutoOpen>]
module timingStuff =
    let pickRunmode() =
        Console.WriteLine("choose number of processes to spawn (default 1)")
        Console.ReadLine()

    let feedback (input : string) =
        Console.WriteLine("you picked {0}", input)
        Console.WriteLine("now running")

    let quitOrContinue() =
        Console.WriteLine("q to quit else continue with keypress")
        Console.ReadKey().KeyChar <> 'q'

    let rec addOne x stop =
        let r = x + 1
        if stop() then r
        else addOne r stop

    let finished stopticks = (fun _ -> Stopwatch.GetTimestamp() >= stopticks)
    let secondsToTicks x = x * 1000L * 10000L
    let prettyNumbers (x : int) = String.Format("{0:#,0}", x)

    let printResult result start =
        let final = (Stopwatch.GetTimestamp() - start |> TimeSpan).TotalSeconds
        let pretty = prettyNumbers result
        sprintf "performed %s operations in %f seconds" pretty final |> Console.WriteLine

    let op duration start =
        duration
        |> secondsToTicks
        |> (+) start
        |> finished
        |> addOne 0

    let opAsync duration start procs =
        [ for i in [ 1..procs ] -> async { return op duration start } ]
        |> Async.Parallel
        |> Async.RunSynchronously

[<EntryPoint>]
let main argv =
    let loop() =
        let input =
            match Int32.TryParse(pickRunmode()) with
            | true, i -> i
            | _ -> 1
        input
        |> string
        |> feedback
        |> ignore
        let start = Stopwatch.GetTimestamp()
        let result = opAsync 1L start input |> Seq.sum
        printResult result start |> ignore
        quitOrContinue()
    while loop() do
        ()
    0


texts:
I have written code for a binary index tree. My problem is that there are many functions based on the binary index tree the function stores the sum of element within a given range of binary index tree. My task is to compute the sum of all the functions with provide range.

This example will clarify:

My array elements: A = 1 2 3 4 5

The function \$f(x,y)\$ is the sum of all elements of array between index \$x\$ and \$y\$ (inclusive)

\$f(1,3) = 6\$
\$f(2,5) = 14\$
\$f(4,5) = 9\$
\$f(3,5) = 12\$
\$f(1,2) = 3\$

For a given query of the form sum(a,b), I have to compute the sum of all the function from a to b.

sum(1,4) is the sum of the function from 1 to 4:

\$f(1,3) + f(2,5) + f(4,5) + f(3,5) = 6+14+9+12 = 41\$

The above data structure must also support for updating in the array.

update(a,b) replaces the element stored in index a of the array with b
update(3,7) will cause my new array to be A = 1 2 7 4 5

For any further clarification you can refer to this link.

My code is working for smaller range of input. How can I tune it to work for larger inputs?

def initupdate(x, y, n, lst):
    while x <= n:
        lst[x] += y
        x += (x & -x)

def update(x, y, n, lst):
    a = lst[x]
    initupdate(x, -a, n, lst)
    initupdate(x, y, n, lst)

def sumk(k, lst):
    res = 0
    while k:
        res += lst[k]
        k -= (k & -k)
    return res

def sumfunc(k, nfunc, lst):
        res = 0
        a, b = nfunc[k]
        res += sumk(b, lst)
        res -= sumk(a - 1, lst)
        return res

def sumfuncxy(x,y, nfunc, lst):
    res=0
    for k in range(x,y+1):
        res+=sumfunc(k,nfunc,lst)
    return res

n = int(input())
array = [0] + list(map(int, input().split()))
number = [ 0 for i in range(n + 1)]

for i in range(1, n + 1):
    initupdate(i, array[i], n, number)

nfunction = [[0, 0] for i in range(n + 1)]

for i in range(1, n + 1):
    lst = input().split()
    lst = list(map(int, lst))
    nfunction[i] = lst

q = int(input())

for i in range(q):
    lst = list(map(int, input().split()))
    if lst[0] == 1:
        'update'
        update(lst[1], lst[2], n, number)
    else:
        print(sumfuncxy(lst[1], lst[2], nfunction, number))

I know my naming of the variable is poor.

Is the choice of data structure (binary index tree) good for the problem?
Have I properly modularized my code?
Are there any vulnerability in my code?
Are there any further suggestions for cleaning the code?


texts:
this is my first time on this stack exchange :)

I created a little script to check for the latest version of specified API version available, but I am wondering if I am using the best way possible for checking regex and includes?

The var arr will be filled dynamically with version folders using fs.readdir, but for simplicity I wrote them in the array manually and the var pattern will come from req.params.v using nodejs express router middleware.

Just looking for an approval or if there is a better way, thank you!

var arr = ['v1.0.0', 'v5.2.4', 'v5.2.9', 'v5.20.4', 'v6.4.0'];
var pattern = 'v5.2';

const regex = /^v[0-9](\.[0-9]{1,2})?(\.[0-9])?$/;

if (regex.test(pattern) && (arr.filter(s => s.includes(pattern)) != 0)) {

    if (pattern.match(/\./g) == null) {
        console.log('major version');
        console.log(pattern);
    } else if (pattern.match(/\./g).length == 1) {
        console.log('minor version');
        console.log(pattern);
        pattern = pattern + '.';
    } else {
        console.log('patch version');
        console.log(pattern);
    }
    const matches = arr.filter(s => s.includes(pattern));
    console.log(matches[matches.length - 1]);

} else {
    console.log('Specify correct API version!');
}

Thank you in advance!


texts: Calculating the minimum and maximum of a byte array

texts:
I've been working with binary files with this last assignment and part of it was to determine the maximum and minimum byte. Initially this was 2 functions but a bonus portion was to make them into 1 function through usage of an enum, I imagine to reinforce their utility. I would like to know if there are better ways of doing this, be it efficient, elegant or otherwise. I'd also like tips on my C code, as this is the first real project I've done in C in several years.

I've also included the relevant bits from the header file.

#define GOOD 1
#define BAD 0

typedef unsigned int uint;
typedef unsigned char byte;

typedef enum uMaxOrMin
{
    Max,
    Min
} MaxOrMin;

typedef enum uBitStyle
{
    BitsOn,
    BitsOff
} BitStyle;

int MaxOrMinValue(byte src[], uint size, byte *val, MaxOrMin mom)
{
    uint srcTemp;
    uint srcIndex = 0;
    uint largest;
    uint smallest;
    uint* data = src;

    switch (mom)
    {
    case Max:
    {
        largest = src[0]; //initialize largest
        while (*data++) //iterate over binary array
        {
            srcTemp = *(src + srcIndex++); //start at beginning of array, grab first byte and increment by 1
            if (srcTemp > largest) //current byte is greater than our saved largest byte
                largest = srcTemp; //set new largest
        }

        *val = largest; //return max to caller
        return GOOD;
    }

    case Min:
    {
        smallest = src[0]; //initialize smallest
        while (srcIndex < size) //iterate over binary array
        {
            srcTemp = *(src + srcIndex++); //start at beginning of array, grab first byte and increment by 1
            if (srcTemp < smallest) //current byte is less than our saved smallest byte
                smallest = srcTemp; //set new smallest
        }

        *val = smallest; //return min to caller
        return GOOD;
    }
    return BAD; //if we hit here, we've failed
    }
}

I know that under normal circumstances, C functions should return 0 upon success and -1 or otherwise upon failure, but this configuration was mandated by the assignment.

I would like to know why my while loop for BitsOn works but if I use the same construct for BitsOff, while (*data++), it fails to give me the correct results. Can someone explain this? Perhaps my understanding is lacking here. I'm trying to get more used to pointers so it seems pertinent to maximize my use of them, even in non-ideal circumstances.


texts: Create an array of categories from comma-seperated text input

texts:
This code works just fine, but could obviously be more elegantly written.

The basic idea is to create an array of categories from a text input.   The code splits up the text input by commas to create the array and trims away white space.

I considered using unshift to add the 'Inbox' default category to the beggining, but figure there must be an even better way.  All in all, this is probably the 4th or 5th version of this code.

    var CategoriesForm = event.target.category.value;
    var CategoriesFormTrimmed = CategoriesForm.replace(" ", "");
    var categoriesDefault = ['Inbox']; //default category
    var categoriesJoined = [];
    if (CategoriesForm) {
      var splitUpCategories = CategoriesFormTrimmed.split(',');
      categoriesJoined = categoriesDefault.concat(splitUpCategories);
      console.log(categoriesJoined);
    } else {
      categoriesJoined = ['Inbox'];
    }


texts: I finally solved the Birthday Problem using Java

texts:
I like to put ideas and mathematics into code whenever I am interested in the subject. Ever since I was introduced to The Birthday Problem I wanted to throw it into a Java program.

I started writing the program in several different ways, all of which in the end would return "Infinite" for one of the variables dealing with the factorial numbers.

I finally stumbled across "BigInteger" and "BigDecimal", I was annoyed at first of how hard it was to use them, but I stuck with it.

Others have built similar programs that generate random dates and run x amount of times ( like 1000) to find an average percentage rate at with birthdays collide, mine finds the mathematical statistic.

Check this out, how cool is this?

//Author: Joseph Kreifels II
//  Date: June 30, 2017
// Purpose: To find that percentage at which 2 students share a birthday.

import java.io.*;
import java.util.*;
import java.lang.Math;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Testing {

    public static void main(String[] args) {

        int n, r, i;
        double d;

        BigDecimal abd = new BigDecimal("0");

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Number of Students: ");
        i = sc.nextInt();

        n = 365;
        System.out.printf("Value of n: %d\n",n);
        r = 365 - i;
        System.out.printf("Value of r: %d\n",r);

        System.out.println("");
        System.out.println("Factorial of n = " + fact(n) );
        System.out.println("Factorial of r = " +  fact(r) );

        // First get the NPR
        abd = fact(n).divide(fact(n-(n-r))) ;

        // Display NPR for FUN.
        System.out.println("NPR of n and (n-r) = " + abd);

        // Now we must divide it by  x^y.. (e.g 365^5)
        abd = abd.divide(BigDecimal.valueOf( Math.pow(n,i) ),4, RoundingMode.HALF_UP);

        // I am lazy, So I turned it into a double to make the last 2 display statements easier to write.
        d = abd.doubleValue();

       System.out.printf("\nNot Same Birthday chance: %.0f%%\n", (d * 100) );
       System.out.printf("Same Birthday chance: %.0f%%\n", ((1 - d) * 100)  );

    } // main

        public static BigDecimal fact(int num)
    {

        BigDecimal abd = new BigDecimal("1");

        int i;
        for(i=0; i<num; i++)
        {
            abd = abd.add(abd.multiply(BigDecimal.valueOf(i)));
        }
        return abd;
    }

}

EDIT: I feel like the results could come out better. So Here are some changes.

Now 4 Decimal Places

abd = abd.divide(BigDecimal.valueOf( Math.pow(n,i) ),4, RoundingMode.HALF_UP);

Now outputs a percentage with 2 decimal places (e.g. 25.65%)

 System.out.printf("\nNot Same Birthday chance: %.2f\n", (d * 100 ) );
 System.out.printf("Same Birthday chance: %.2f\n", ((1 - d) * 100 )  );


texts: Union based encoding of .csv file into a data table with different types

texts:
I am writing a program that has a row-based data table class. It also has an encoder class that is intended to take in some .csv data and convert it into a 2darray of encoded data of unknown type at compile time.

The idea is that the user will point to a .csv file they would like to read from and specify a runtime schema (column 1 == int, column 2 == bool, column 3 == string, etc) that will be used to encode the raw .csv data into the proper types needed for comparison and such elsewhere in the program.

I have been reading a lot about this and decided to try a union based approach.
I mocked this up in a simple project to see how this might work out on one single piece of data ("DataPoint."). Here is the code.

#include "pch.h"
#include <iostream>
#include <sstream>

union DataPoint
{
    bool Bool;
    int  Integer;
    float FloatingPoint;
    //std::string String;
};

enum DataTypes
{
    Bool,
    Integer,
    FloatingPoint,
    //String
};

DataPoint EncodeData(DataPoint InDataPoint, DataTypes InDataTypes, std::string InData)
{
    std::stringstream DataStream(InData);

    switch (InDataTypes)
    {
    case Bool:
        std::cout << "Type is Bool" << std::endl;
        if (InData == "True" || InData == "true"  || InData == "1") InDataPoint.Bool = true;
        else if (InData == "False" || InData == "false" || InData == "0") InDataPoint.Bool = false;
        else std::cout << "This data is not compatable with the bool type." << std::endl;
        break;
    case Integer:
        std::cout << "Type is Integer" << std::endl;
        DataStream >> InDataPoint.Integer;
        break;
    case FloatingPoint:
        std::cout << "Type is Floating Point" << std::endl;
        DataStream >> InDataPoint.FloatingPoint;
        break;
    /*
    case String: InDataPoint.String = InData;
        break;
    */
    default:
        break;
    }

    return InDataPoint;
}

void PrintData(DataPoint InDataPoint, DataTypes InDataTypes)
{
    switch (InDataTypes)
    {
    case Bool: std::cout << "Encoded data value : " << InDataPoint.Bool << std::endl;
        break;
    case Integer: std::cout << "Encoded data value : " << InDataPoint.Integer << std::endl;
        break;
    case FloatingPoint: std::cout << "Encoded data value : " << InDataPoint.FloatingPoint<< std::endl;
        break;
    /*
    case String:
        break;
    */
    default:
        break;
    }
}

int main()
{
    DataPoint DataPoint1{};
    DataTypes DataType{ Bool };
    std::string Data{ "true" };

    std::cout << "Raw data value : " << Data << std::endl;

    PrintData(EncodeData(DataPoint1, DataType, Data), DataType);

    return 0;
}

This all seems to work, however, as you can see... I have commented out string entries because I cannot figure out a good way to handle them. One issue I run into is though unions apparently support strings in c++ now, I error out when I try to add a string as a union member. Here is the error I get if I uncomment the string member of the union.

Severity   Code    Description Project File    Line    Suppression State
Error (active)  E1776   function "DataPoint::DataPoint(const DataPoint &)" (declared implicitly) cannot be referenced -- it is a deleted function

Is there some way to handle the string?
Also, in general, does this approach seem sound?


texts:
I've implemented a to_string function that takes a player_t instance and format it into a string.

Code:

#include <stdio.h>
#include <string.h>

typedef struct player {
  int id;
  float points;
  char display_name[256];
} player_t;

#define MAX_OUTPUT_SIZE sizeof(int) + sizeof(float) + 256

void to_string(player_t, char [MAX_OUTPUT_SIZE]);

int main()
{
  char stringified[MAX_OUTPUT_SIZE];

  player_t p1 = {.id = 1, .points = 17.4, .display_name = "Tester"};

  to_string(p1, stringified);

  printf("player: %s\n", stringified);

  return 0;
}

void to_string(player_t player, char output[MAX_OUTPUT_SIZE])
{
  char temp[MAX_OUTPUT_SIZE];

  snprintf(temp, sizeof(temp), "\n\tid: %d", player.id);
  strncat(output, temp, 6 + 1);

  snprintf(temp, sizeof(temp), "\n\tpoints: %f", player.points);
  strncat(output, temp, 10 + 9);

  snprintf(temp, sizeof(temp), "\n\tdisplay_name: %s", player.display_name);
  strncat(output, temp, 18 + 256);
}

Output:

player:
    id: 1
    points: 17.400000
    display_name: Tester

Questions:

Is there a better way to define MAX_OUTPUT_SIZE instead of manually adding the size of each element?
Is there a better way to implement to_string instead of using a temporary variable, the separate combination of strncat & snprintf and explicitly counting the characters for strncat?.
Am I over complicating my usage of snprintf & strncat?
(slightly out of topic) Do you recommend any C project to read it's code that implement similar functionalities and is following best practices?

Thanks in advance and I'm sorry if I've missed any obvious mistakes (still in the process of learning C with Ruby/JS background).


texts: Putting a border around the selected list item

texts:
I have an HTML list. The goal is that:

When an li is clicked, the .my-list--selected class will be applied. And, since the inner div also has a border-bottom, the .border-bottom class must be removed (or else it appears as though there is a 2px wide border along the bottom if both classes are applied).
When another li is clicked, the previously selected li's .my-list--selected is removed and the .border-bottom class is reinstated (there can only be 1 '.my-list--selected' at a time).

I've written the below code and it works, but it seems really messy and overly complicated to me.

Is there a better way to go about achieving this goal?

$("li").click(function() {
  //Remove the my-list--selected class from any elements that already have it
  $('.my-list--selected').removeClass('my-list--selected');
  //Add the .border-bottom class back to any element that is missing it
  $('.my-list--selected').addClass('border-bottom');
  //Add the my-list--selected class to the clicked element
  $(this).addClass('my-list--selected');
  //Remove the border-bottom class from the clicked element
  $(this).find('.border-bottom').removeClass('border-bottom');
});
li div {
  padding: 0 10px;
}

.border-bottom {
  border-bottom: 1px solid #ccc;
}

.my-list--selected {
  border: 1px solid #ccc;
}

Content

Content

Content


texts:
We have a base module consuming the company API. In each app I've written almost always a service per controller. Because most controllers are specific to a entity (a single user, a single post, list of posts written by a user), when I initialize them to query the data I have to request for that Id. So the service requires the controller to specify an Id.

Because of this I've decided the following: this services return a function which will construct the service object receiving the Id as parameter. Then the controller builds the service. With this I'm reusing those services, i.e.: A user edit his personal information on AccountController and administrator edit the personal user information on UsersListController both building the UserEditService passing the Id.

    // View User Service
function(UserResource, $log, ErrorHandler) {
    var fn = function(userId) {
       var id = userId,
           svc = {
               user: {}
           };

       svc.get = function(){
           UserResource.get(userId)
               .then(function(res)  {
                    svc.user = res.data.user;
                    svc.interests = res.data.interests;
               }, ErrorHandler.error);
       };
       return svc;
    };
    return fn;
}

// View User Controller
function(UserViewService, $scope, $stateParams) {
    var svc = new UserViewService(stateParams.id);

    this.user = svc.user;
    function watchUser() {
        return svc.user;
    };
    $scope.$watch(watchUser, function(current, previous) {
        svc.user = current;
    });
};

Am I implementing some ugly/confuse code to deal with this? I'm only doing this on applications, the base modules services and methods are encapsulated, they always receive the Id in methods parameters. But on apps, each service would had to receive the Id on each parameter in order to be reused across several controllers (they could be loaded in the same session consuming the same service).

I've tried to avoid this extra service and calling the UserResource on controller but I always end up with controller handling business operations.


texts: Simple Binary Search Tree Class with Insert and Search Functions

texts:
I am trying to learn to implement DSs in C++ and here is a simple implementation. Please review in terms of optimization, memory management, coding standards, etc

#include <stdio.h>
#include <iostream>

class BstNode{
int data;
BstNode* left;
BstNode* right;

public:
BstNode(int data)
{
    this->data = data;
    this->left = NULL;
    this->right = NULL;
}
~BstNode();

void Insert(int data)
{
    if(this->data >= data)
    {
        if (this->left == NULL)
            this->left = new BstNode(data);
        else
            this->left->Insert(data);
    }
    else
    {
        if (this->right == NULL)
            this->right = new BstNode(data);
        else
            this->right->Insert(data);
    }
}

bool Search(int data)
{
    if(this->data == data)
        return true;
    else if(this->data >= data)
    {
        if(this->left == NULL)
            return false;
        else
            return this->left->Search(data);
    }
    else
    {
        if(this->right == NULL)
            return false;
        else
            return this->right->Search(data);
    }

}
};

int main()
{
BstNode* ptr_root = new BstNode(15);
ptr_root->Insert(10);
ptr_root->Insert(16);
int num;
std::cout<<"Enter the number: \n";
std::cin>> num;
if (ptr_root->Search(num))
    std::cout<<"Found\n";
else
    std::cout<<"Not Found\n";

return 0;
}


texts:
I'm preparing for an exam on C++, as part of my preparation I want to implement a generic map without using anything from the STD for educational purposes.

Before jumping into implementation of everything, I want to know that the skeleton for my Map is solid and I use templates and template inheritance correctly.

Above is the skeleton of my Map.  I would like to get an opinion about that skeleton.

#ifndef  MAP_H_
#define MAP_H_

template <class K, class V>
class Map {
public:
    /*
        Map c'tors and d'tors.
    */
    Map(); //C'tor
    Map(const Map& map); //Copy c'tor
    ~Map(); //D'tor

    /*
        Map methods
    */
    void insert(const K& key, const V& value);
    bool isIn(const K& key) const;
    void remove(const K& key);
    void clear();
    bool isEmpty();
    int size() const;

    template <class F>
    Map filter(F& filterFunction);

    /*
        Map methods using Iterators
    */
    class Iterator;
    class ConstIterator;
    Map::ConstIterator begin() const;
    Map::ConstIterator end() const;
    Map::Iiterator begin();
    Map::Iterator end();

    /*
        Map operators
    */
    const DataType& operator[](const KeyType key) const;
    DataType& operator[](const KeyType key);
};

/*
    Map::Pair class
*/
template <class K, class V>
class Map<K,V>::Pair {

};

/*
    Map::Iterator class
*/
template <class K, class V>
class Map<K,V>::Iterator {
    //to do
};

/*
    Map::ConstIterator class
*/
template <class K, class V>
class Map<K,V>::ConstIterator : public Map<K,V>::Iterator {
    //to do
};

/*
    Map c'tors, methods and operators implementation
*/

//to do

#endif /*  MAP_H_  */


texts: Clean code attempt at ATM problem on codechef.com

texts:
The problem asks you to take an integer (debit amount) and a double (credit or initial balance amount) and process the requested debit verifying that 1 it's a multiple of the minimum denomimation amount of $5 and that it's also smaller than the credit/balance.  If either is untrue, it is supposed to return the initial deposit amount otherwise it will return the new balance.

Full problem description

I have created 3 objects for this problem:

Transaction - This object reads in the two initial values given and then is used in ATM
ATM - Takes the transaction and applies them to the account and then displays the new balance.
Account - This object keeps track of the current account balance and updates the balance if the ATM passes it a value.

Limitations:

I understand that it can only process a single account, but that is more a limitation set by the problem description than it is me not accounting for multiple accounts.  Also no error is returned if the balance cannot be updated, but it is not a requirement.  I also understand I made a mountain out of a molehill with this problem as it can be solved by much less code.

In what ways can I improve this code other than the limitations mentioned?

#include <istream>
#include <iostream>
#include <iomanip>

class Account {
public:
    Account()
        :   mBalance(0.0)
    {}

    void updateBalance(double transaction) {
        mBalance += transaction;
    }

    double getBalance() {
        return mBalance;
    }

private:
    double mBalance;
};

class Transaction {
public:
    Transaction()
        :   mDebit(0)
        ,   mCredit(0.0)
    {}

    int getDebit() {
        return mDebit;
    }

    double getCredit() {
        return mCredit;
    }

    friend std::istream& operator>>(std::istream& input, Transaction& transaction) {
        input >> transaction.mDebit;
        input >> transaction.mCredit;
        return input;
    }

private:
    int     mDebit;
    double  mCredit;
};

class ATM {
public:
    ATM()
        :   mAccount()
        ,   mMinDenomination(5)
        ,   kWithdrawal_fee(0.50)
    {}

    void processTransaction(Transaction& transaction) {
        credit(transaction);
        debit(transaction);
    }

    void displayBalance() {
        std::cout << mAccount.getBalance() << '\n';
    }

private:
    Account             mAccount;
    int                 mMinDenomination;
    const double        kWithdrawal_fee;

    bool debit(Transaction& transaction) {
        if(isWithdrawable(transaction.getDebit())){
            mAccount.updateBalance(-1*(transaction.getDebit() + kWithdrawal_fee));
            return true;
        }
        return false;
    }

    void credit(Transaction& transaction) {
        if(transaction.getCredit() > 0) {
            mAccount.updateBalance(transaction.getCredit());
        }
    }

    bool isWithdrawable(int transaction) {
        if(transaction % mMinDenomination == 0) {
            return mAccount.getBalance() >= transaction + kWithdrawal_fee;
        }
        return false;
    }
};

int main() {
    std::iostream::sync_with_stdio(false);
    std::cout << std::setprecision(2) << std::fixed;

    Transaction transaction;
    ATM         atm;

    std::cin >> transaction;
    atm.processTransaction(transaction);
    atm.displayBalance();

    return 0;
}


texts:
I am working on a large project that requires information about the monitor(s). Please don't be confused by the organization of the following structs. The design intent is to be cross-platform, so they don't contain any operating system-dependent types. Currently, I am working on the Windows implementation of the following functions.

Please bear with me as I am a beginner at C++. Even though I have been programming with it for a while now, I am completely self taught, and my understanding isn't comprehensive.

Is there anything I could be doing differently, or maybe better? Also, is there anything I am not understanding correctly? I'm open to any and all suggestions, tips, and criticisms.

/**
 * Monitor structure.
 */
struct tsMonitor
{
    /**
     * Windows specific data.
     */
    typedef struct SWin32 { std::string adapterName; std::string displayName; } _win32;

    std::string adapterName;            // Name of the adapter (GPU).
    std::string displayName;            // Actual monitor name.

    _win32 win32;                       // Windows adapter and display names. Fuck you Windows and your stupid "DeviceName" vs "DeviceString".

    unsigned short widthMM, heightMM;   // Physical dimensions in millimeters.
};

/**
 * Video mode structure.
 */
struct tsVideoMode
{
    unsigned short width, height;   // Dimensions in pixels.

    unsigned char refreshRate;      // Refresh rate.

    unsigned char colorDepth;       // Number of bits per pixel.
};

std::vector<tsMonitor> tsGetMonitors()
{
    std::vector<tsMonitor> returnVal;

    for(unsigned char adapterIndex = 0;; adapterIndex++)
    {
        DISPLAY_DEVICE adapter;

        ZeroMemory(&adapter, sizeof(DISPLAY_DEVICE));
        adapter.cb = sizeof(DISPLAY_DEVICE);

        if(!EnumDisplayDevices(NULL, adapterIndex, &adapter, 0)) break;
        if(!(adapter.StateFlags & DISPLAY_DEVICE_ACTIVE)) continue;

        for(unsigned char displayIndex = 0;; displayIndex++)
        {
            DISPLAY_DEVICE display;

            ZeroMemory(&display, sizeof(DISPLAY_DEVICE));
            display.cb = sizeof(DISPLAY_DEVICE);

            if(!EnumDisplayDevices(adapter.DeviceName, displayIndex, &display, 0)) break;

            HDC hDC = CreateDC("DISPLAY", adapter.DeviceName, NULL, nullptr);

            tsMonitor monitor;

            monitor.adapterName = adapter.DeviceString;
            monitor.displayName = display.DeviceString;

            monitor.win32.adapterName = adapter.DeviceName;
            monitor.win32.displayName = display.DeviceName;

            monitor.widthMM = (unsigned short)GetDeviceCaps(hDC, HORZSIZE);
            monitor.heightMM = (unsigned short)GetDeviceCaps(hDC, VERTSIZE);

            returnVal.push_back(monitor);
        }
    }

    return returnVal;
}

unsigned char tsGetMonitorCount()
{
    return (unsigned char)GetSystemMetrics(SM_CMONITORS); // NOTE: I don't exactly understand pseudo-monitors.
}

bool tsGetVideoMode(const tsMonitor& monitor, tsVideoMode* mode)
{
    DEVMODE devMode;

    ZeroMemory(&devMode, sizeof(DEVMODE));
    devMode.dmSize = sizeof(DEVMODE);

    if(!EnumDisplaySettings(monitor.win32.adapterName.c_str(), ENUM_CURRENT_SETTINGS, &devMode)) return false;

    mode->width = (unsigned short)devMode.dmPelsWidth;
    mode->height = (unsigned short)devMode.dmPelsHeight;
    mode->refreshRate = (unsigned char)devMode.dmDisplayFrequency;
    mode->colorDepth = (unsigned char)devMode.dmBitsPerPel;

    return true;
}


texts:
I have the object with values. I trying to filter based on values.
var data = {
  "map": {
    "0": ["abcd"],
    "1": ["efgh"],
    "2": ["xyz"],
  }
}

In above object I am trying to filter xyz which are have in array values.
Expecting output:
 { '0': [ 'xyz' ] }

I done the code but I am not sure it's efficient way. Can someone help me this.

const  data = {
  "map": {
    "0": ["abcd"],
    "1": ["efgh"],
    "2": ["xyz"],
    "3": ["abcd", "xyz"],
  }
}

const filtered = Object.keys(data.map)
  .filter((key) => {
    return data.map[key].includes('xyz');
  })
  .reduce((obj, key, cIndex) => {
    obj[cIndex] = data.map[key];
    return obj;
  }, {});

  console.log('filtered', filtered);


texts:
I got a function that has as input 2 strings, computes the string similarity of all the combinations and give back and output the highest similarity. For example, "you are" and "are you" will have 1 as similarity value.

import itertools
from difflib import SequenceMatcher
import numpy as np

def _compare_names(a, b):
    return SequenceMatcher(None, a, b).ratio()

def _compare_names_with_combinations(name_1,name_2):
    name_1 = name_1.lower().split()
    name_2 = name_2.lower().split()
    combinations_name_1 = list(itertools.permutations(name_1))
    combinations_name_2 = list(itertools.permutations(name_2))
    combinations_name_joined_1 = [' '.join(list(name)) for name in combinations_name_1]
    combinations_name_joined_2 = [' '.join(list(name)) for name in combinations_name_2]
    distances = []
    for name1 in combinations_name_joined_1:
        for name2 in combinations_name_joined_2:
            distance = _compare_names(name1,name2)
            distances.append(distance)
    return max(distances)

examples:

_compare_names_with_combinations('you are','are you')
>> 1
_compare_names_with_combinations('you are','are yos')
>> 0.85714285

My concerns come when I have to compare a lot of texts and it seems that there should be around a more efficient way of computing this value. Do you think there is space in this function to decrease the computational time?


texts:
I have this little function to validate e-mail. It's a little piece of code to search major mistakes in e-mail input and it's part of a bigger program I have to complete as a school assignment. Is there a better way to do it in C?

I'd like to do it in regex but if I have understood correctly,  C under Windows doesn't support complex regex. And I use scanf to make testing this code simpler. Later, I replace it with another function that reads user input. Test is an array test[40] that is declared in main.

In addition there is a compiler warning about my for loop, that value computed is not used. It probably means *ch. I use it to end for loop when *ch reaches '\0'. I know I could use while loop. However, is there a solution to fix that or a workaround or a better solution using for loop? And I'd like to know, what would you do differently or what would you also check in addition to what I am checking in my code.

int test(char test[])
{
    int     i;
    char    *pos1, *pos2;
    char    *ch;

    puts("Enter email!");
    scanf("%39s", test);

    while (1) {
        for (i = 0, ch = test; *ch; *ch++) {
                if (*ch == '@') {
                    pos1 = ch;  // <-stores last @ address
                    i++;
                }
            }
            pos2 = ch;          // <-stores end address ("\0") of test

        /* If there is only one "@" */
        if (i == 1) {

            /* Pos1 - test <-a character must be before "@". Ch - pos1 <-Counts
             * backwards from the end of the string towards "@". A character
             * must be between "@" and "." */
            while (pos1 - test && ch - pos1 > 1) {

                /* From the end of string to "." has to be atleast 2 chars */
                if ((pos2 - ch) > 2 && *ch == '.') {
                    printf("pos2 - ch is %d and *ch is %c",pos2 - ch, *ch);
                    return 1;
                }
                ch--;
            }
        }
        puts("Email wrong! Enter again");
        scanf("%39s", test);
    } /* End while */

    return 1;
}


texts: Dijkstra's algorithm using priority queue running slower than without PQ

texts:
I need to implement dijkstra's algorithm and I've done so using this Wikipedia page. I've done it both with priority queue and without.

Both versions work 100% correct, however I need the faster one (priority queue one). The problem is that it isn't faster. My tests show "faster" one runs in more than double the time that "slower" one does, it shouldn't do that. What am I doing wrong?

//more primitive version that in fact runs faster (it shouldn't)

//source is starting node, adj adjacency list, Road represents one edge
private static int dijkstra (int source, ArrayList<Road>[] adj) {
    HashSet<Integer> vertices = new HashSet<>();

    int[] dist = new int[adj.length];
    int[] prev = new int[adj.length];

    for (int i = 0; i < adj.length; i++) {
        dist[i] = Integer.MAX_VALUE;
        prev[i] = Integer.MAX_VALUE;
        vertices.add(i);
    }

    dist[source] = 0;

    while (!vertices.isEmpty()) {
        int currentPathLen = Integer.MAX_VALUE, current = -1;
        for (int v: vertices) {
            if (dist[v] < currentPathLen) {
                current = v;
                currentPathLen = dist[current];
            }
        }

        vertices.remove(current);

        for (Road v: adj[current]) {
            int alt = dist[current] + v.distance;

            if (alt < dist[v.end]) {
                dist[v.end] = alt;
                prev[v.end] = current;
            }
        }
    }
}

//this one should run faster

//same variables as primitive version, except for Node,
//which is made only for PQ prioritizing
private static int improvedDijkstra(int source, ArrayList<Road>[] adj) {
    PriorityQueue<Node> vertices = new PriorityQueue<>();

    int[] dist = new int[adj.length];
    int[] prev = new int[adj.length];

    dist[source] = 0;

    for (int i = 0; i < adj.length; i++) {
        if (i != source) {
            dist[i] = Integer.MAX_VALUE;
            prev[i] = Integer.MAX_VALUE;
        }

        vertices.add(new Node(i, dist[i]));
    }

    while (!vertices.isEmpty()) { //O(n)
        Node u = vertices.poll(); //this should have O(logn)

        for(Road v: adj[u.value]) {  // I suspect the problem is this loop, but it is same
                                     // as in Wikipedia page

            int alt = dist[u.value] + v.distance;

            if (alt < dist[v.end]) {
                dist[v.end] = alt;
                prev[v.end] = alt;

                vertices.add(new Node(v.end, alt)); //this should have O(logn)
            }
        }
    }


texts:
Given this method, we don't know which syntax is the more appropriate.

async finishUpgrade({id}) {
    return new Promise((resolve, reject) => {
      let options = {
        method: 'POST',
        uri: this.apiUrl + `${id}/?action=proceed`,
        body: {}
        json: true
      };

      try {
        const res = await req(options);
        resolve(res);
      } catch(err) {
        reject(err);
      }
    });
  }

As you can see we use return new Promise(...).

Would it be correct/a better way to refactor it this way:

async finishUpgrade({id}) {
  let options = {
    method: 'POST',
    uri: this.apiUrl + `${id}/?action=proceed`,
    body: {}
    json: true
  };

  try {
    const res = await req(options);
    return Promise.resolve(res);
  } catch(err) {
    return Promise.reject(err);
  }
}


texts:
I am trying to use a custom sql query to display different attributes for a product i.e. Size and Price. The query I have when running in console displays as it should

SELECT products.id, products.name, variant_properties.description, LEFT(variant_properties.description,1) as short_desc, variants.price FROM products
  INNER JOIN product_properties ON product_properties.product_id = products.id
  INNER JOIN variant_properties on product_properties.property_id = variant_properties.property_id AND variant_properties."primary" = true
  INNER JOIN properties ON properties.id = product_properties.property_id AND properties.id = variant_properties.property_id AND properties.display_name = 'Size'
  INNER JOIN variants on variants.product_id = products.id AND variants.id = variant_properties.variant_id

In my HAML template I have done the following

- @products.each_with_index do |product, i|
  .product-list.grid-block
    .small-8.grid-content.text-center
      %h4= product.name.titlecase
      - @sizes.each do |size|
        = link_to size.short_desc, product, class: 'hollow button tiny'
        %small= size.price

and in the controller

products = Product.active
    # products = Product.active.includes(:variants)

    product_types = nil
    if params[:product_type_id].present? && product_type = ProductType.find_by_id(params[:product_type_id])
      product_types = product_type.self_and_descendants.map(&:id)
    end
    if product_types
      @products = products.where(product_type_id: product_types)
    else
      @products = products
    end

      @sizes = Product.find_by_sql("SELECT products.id, LEFT(variant_properties.description,1) as short_desc, variants.price FROM products
  INNER JOIN product_properties ON product_properties.product_id = products.id
  INNER JOIN  variant_properties on product_properties.property_id = variant_properties.property_id
  INNER JOIN properties ON properties.id = product_properties.property_id AND properties.id = variant_properties.property_id AND properties.display_name = 'Size'
  INNER JOIN  variants on variants.product_id = products.id AND variants.id = variant_properties.variant_id")


texts:
If I draw something in Illustrator and extract it with AI2Canvas I want it to be customizable so I wrote this simple program. It adds two variables: one to resize and one to shift the path coordinate.

#include <fstream>
#include <regex>
#include <string>

int main(int argc, char *argv[]) {
  std::string path = argv[1];
  std::ifstream input(path);

  std::size_t found_name = path.find_last_of("/\\");
  std::size_t found_extension = path.find_last_of(".");
  const int steps = found_extension - found_name - 1;
  std::ofstream output(path.substr(found_name + 1, steps) + ".txt");

  std::regex pattern("(\\d+(\\.\\d+)?), (\\d+(\\.\\d+)?)");
  std::string in;
  while (!input.eof()) {
    std::getline(input, in);
    output << std::regex_replace(in, pattern, "($1 * resize.x) + pos.x, ($3 * resize.y) + pos.y")
           << '\n';
  }
  return 0;
}

Test file Raw: https://pastebin.com/fDh9qbd8

Test file Resolved: https://pastebin.com/R2gpXD8Q


texts:
I'd like to simplify  this Scala code:

private def getToken() = {
    val token = getTokenFromDb()
    token match {
      case Some(x) => token
      case None => {
        val remoteToken = getTokenRemote()
        remoteToken match {
          case Some(x) => {
            writeTokenToDb(x)
            remoteToken
          }
          case None => None
        }
      }
    }
  }


texts: Onclick radio buttons to change background color

texts:
We are displaying two radio buttons in page. Click on Radio buttons, it will change background color.  Is there any way to improve the quality of the code?

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  text-align: center;
}

body {
  box-sizing: border-box;
  padding-top: 180px;
  background: #ffffff;
}

input {
  display: none;
}

.button {
  display: inline-block;
  position: relative;
  width: 50px;
  height: 50px;
  margin: 10px;
  cursor: pointer;
}

.button span {
  display: block;
  position: absolute;
  width: 50px;
  height: 50px;
  padding: 0;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  border-radius: 100%;
  background: #eeeeee;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
  transition: ease .3s;
}

.button span:hover {
  padding: 10px;
}

.orange .button span {
  background: #FF5722;
}

.amber .button span {
  background: #FFC107;
}

.layer {
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: transparent;
  /*transition: ease .3s;*/
  z-index: -1;
}

.orange input:checked ~ .layer {
  background: #F4511E;
}

.amber input:checked ~ .layer {
  background: #FFB300;
}

  <input type="radio" name="color" value="orange">

  <input type="radio" name="color" value="amber">


texts:
I wrote a simple function that converts an array of words into proper case (using bitwise operations) and returns the array. I performed a simple test using std::chrono to check how fast it was able to perform the conversion. Using a vector of 1000 words the function was able to do it in an average of 27 microseconds.

My question is, if there is a faster way of doing this or if there is anything that I have missed that may be detrimental to the performance of the function. In addition, if there is any syntactical issues or changes that you would recommend that would be greatly appreciated.

#include <vector>
#include <string>

std::vector<std::string> ToProperCase(std::vector<std::string>& array)
{
    if (array.empty())
        return array;

    // Loop through each word
    for (std::string& value : array)
    {
        // Loop through each character in the word
        for (unsigned int i = 0; i < value.size(); ++i)
        {
            // Capitalise first character
            value[0] &= (~(1 << 5));

            // Convert character to lower case
            if (i > 0)
                value[i] |= (1 << 5);
        }
    }

    return array;
}


texts: Sort pandas DataFrame first by subject ID then pick their corresponding values from other columns

texts:
NOTES=[]
hadm=[]
for i in sorted(list(notes_df.SUBJECT_ID.unique())):
    #print(i)
    NOTES.append(list(notes_df[notes_df.SUBJECT_ID == i].TEXT))
    hadm.append(list(notes_df[notes_df.SUBJECT_ID == i].HADM_ID.astype(float)))
notes_1_df = pd.DataFrame(list(zip(sorted(list(notes_df.SUBJECT_ID.unique())),hadm,[item for sublist in NOTES for item in sublist])), columns =['SUBJECT_ID','HADM_ID','NOTES'])
notes_1_df.HADM_ID=notes_1_df.HADM_ID.astype(str)

The above code works fine to generate a new Dataframe with sorted values of subject ID and its corresponding values of other column. I used lists to store values and then used them to create a Dataframe.

But it is slow. How to make it fast?

notes_df structure:

ROW_ID|SUBJECT_ID|HADM_ID|TEXT
1      4           89     Here is the text
2      23          433    Here is the text,and so on
3      65          1212   Here is the text,and
4      914         2212   Here is the text,and so on
5      23          112    Here is the text,and so on
6      23          773    Here is the text,and so on
7      65          1210   Here is the text,and so
8      23          1212   Here is the text,and so on


texts:
I needed a simple way to add this test to certain click events:

if isUser then fireClickEvent else openSignInModal

So I made this directive:

angular.module 'openLETS.core.lib.guestLock', []
.directive 'authGuestLock', ($compile, $state, olString, Auth) ->

  ######### Private #########
  restrict = 'A'
  priority = 1
  terminal = true

  link = (scope, elem, attrs) ->
    $compile(elem.contents())(scope) # Terminal breaks translate, this is a workaround
    elem.on 'click', (e) ->
      e.preventDefault()
      e.stopPropagation()
      if scope.currentUser
        if attrs.ngClick then scope.$eval attrs.ngClick
        if attrs.uiSref
          params = scope.$eval olString.objFrom attrs.uiSref
          state = olString.until attrs.uiSref, '('
          $state.go state, params
      else
        Auth.openModal 'signUp'

  ######### Config #########
  restrict: restrict
  link: link
  priority: priority
  terminal: terminal

What do you think of it's readability and functionality?

This can be made generic quite easily by passing the condition and fallback expressions to the directive:

angular.module 'openLETS.core.lib.clickInterceptor', []
.directive 'clickInterceptor', ($compile, $state, olString, Auth) ->

  ######### Private #########
  restrict = 'A'
  priority = 1
  terminal = true
  scope    =
    condition: '='
    fallback: '&'

  link = (scope, elem, attrs) ->
    $compile(elem.contents())(scope) # Terminal breaks translate, this is a workaround
    elem.on 'click', (e) ->
      e.preventDefault()
      e.stopPropagation()
      if attrs.condition
        if attrs.ngClick then scope.$eval attrs.ngClick
        if attrs.uiSref
          params = scope.$eval olString.objFrom attrs.uiSref
          state = olString.until attrs.uiSref, '('
          $state.go state, params
      else
        scope.fallback()

  ######### Config #########
  restrict: restrict
  priority: priority
  terminal: terminal
  scope: scope
  link: link


texts: Java/Swing GUI code/layout, am I doing this wrong?

texts:
I've never done Java GUI's before. After much trouble I've gotten my GUI to look how I want, however it feels as if my code is very inefficient, as if I'm going about this the wrong way?

     //main panels
private JPanel westPanel = new JPanel(new BorderLayout());
private JPanel eastPanel = new JPanel(new BorderLayout());

//door panels
private JPanel doorsPanel = new JPanel(new BorderLayout());
private JPanel doorsGrid = new JPanel(new GridBagLayout());
private JPanel doorButtons = new JPanel(new FlowLayout());

//light panels
private JPanel lightsPanel = new JPanel(new BorderLayout());
private JPanel lightsGrid = new JPanel(new GridBagLayout());
private JPanel lightTimerGrid = new JPanel(new GridBagLayout());
private JPanel lightButtons = new JPanel(new FlowLayout());

//list panels
private JPanel listPanel = new JPanel(new BorderLayout());
private JPanel listButtons = new JPanel(new GridBagLayout());
private JLabel itemDesc = new JLabel("Item Name - Item Price");
private JLabel totalPrice = new JLabel("Total Price: ");

doorsPanel.setBorder(BorderFactory.createTitledBorder("Manage Doors: "));
doorsPanel.add(doorsGrid, BorderLayout.NORTH);
doorsPanel.add(doorButtons, BorderLayout.SOUTH);

lightsPanel.setBorder(BorderFactory.createTitledBorder("Manage Lights: "));
lightsPanel.add(lightsGrid, BorderLayout.NORTH);
lightsPanel.add(lightButtons, BorderLayout.SOUTH);
lightsPanel.add(lightTimerGrid, BorderLayout.CENTER);

listPanel.setBorder(BorderFactory.createTitledBorder("Manage Shopping List: "));
listPanel.add(listButtons, BorderLayout.EAST);

westPanel.add(doorsPanel, BorderLayout.NORTH);
westPanel.add(lightsPanel, BorderLayout.CENTER);

eastPanel.add(listPanel, BorderLayout.SOUTH);

add(westPanel, BorderLayout.WEST);
add(eastPanel, BorderLayout.EAST);


texts:
So what I'm trying to do is to get "bad" ip's from this page
https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt
Then I made a script that replaces ipsets to block, by replacing old ipset with one that holds the ip numbers from above mentioned place.
Was long time ago I wrote it. Now I came back to it. And I'm not really shure it works. Because when I run ipset list > temporaryfile
then I dont think all numbers in temporaryfile are found in newblacklist.txt
Here is the bash script:
#!/bin/bash

# Variable holding the path to the textfile used in this script
textfile='/home/userName/Blacklist/newblacklist.txt'

# create and add blacklist if not created and add to iptables
created=$(ipset list -name | grep -c blacklist)
if [[ $created == 0 ]]; then
    echo creating blacklist
    ipset create blacklist hash:net
    iptables -I INPUT -m set --match-set blacklist src -j DROP
else
    echo blacklist already there
fi

# create and add tempblacklist if not created and add to iptables
created=$(ipset list -name | grep -c tempblacklist)
if [[ $created == 0 ]]; then
    echo creating tempblacklist
    ipset create tempblacklist hash:net
    iptables -I INPUT -m set --match-set tempblacklist src -j DROP
else
    echo tempblacklist already there
    ipset flush tempblacklist
fi

# create a new blacklis.txt file if not there
# If there, clear it by means of rm and touch
if [ ! -e $textfile ]; then
    echo creating new blacklist.txt file
    touch $textfile
else
    echo Emptying existing blacklist.txt file
    rm $textfile;
    touch $textfile;
fi

# Get the bad ip list from site and save in newblacklist.txt file
curl --compressed https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt 2>/dev/null>$textfile

#check if there is a list with new bad ips
#$created shows 0 if there is no such list
created=$(ipset list -name | grep -c newblacklist)

# Uses $created to check if there is a newblacklist list in ipset
# If there is no list creates one, otherwise flushes the existing one
if [[ $created == 0 ]]; then
    echo Creating new newblacklist list in ipset
    ipset create newblacklist hash:net
else
    echo Flushing existing list
    ipset flush newblacklist
fi

# Clean input from comments and other stuff
variable=$(grep -v "#" $textfile | grep -v -E "\s[1-2]$" | cut -f 1)
for ip in $variable;
do
    ipset add newblacklist $ip
done

ipset swap blacklist tempblacklist

ipset flush blacklist

ipset swap newblacklist blacklist

ipset flush tempblacklist

The newblacklist.txt does seem to look identical to the content in the repo mentioned above.
Basically Im not confident the iptable gets updated to ban whats currently in the repo, when I run the script.


texts:
About to get back into coding, so I implemented linear probing in Python. How did I do? Anything unnecessary? Am I using "global" right? I originally wanted to use an array with a fixed length, but couldn't get it to work.

list = ["x", "x", "x", "x", "x", "x", "x"]
state = 0

def main():
#tests
    linearProbing(1)
    linearProbing(1)
    linearProbing(1)
    print(list)

def linearProbing(x):
    global state
    global list
    c = x % len(list)
    while state != 1:
        if list[c] == "x":
            list[c] = x
            state = 1
        elif c == 0:
            c = len(list) - 1
        else:
            c -= 1
    state = 0

if __name__ == '__main__':
    main()


texts: Get the last activity per user per day in a dataframe

texts:
I have many users. Each time a user uses their smartphone it register them. I am determining the last time each user used their smartphone each day.
Additionally smartphone usages from 18:00 to 06:00, the next day, should be considered as an entry on the previous day. I have created a dummy example.
I did the following:

First subtract the number of hours.
Sort the data frame based on user and date time.
Get the last row.

Is there a more efficient approach to this? Are there other tips I can follow to improve my code?
df_example = {'id': [1,1,1,1,1],
             'activity': [datetime.datetime(2019, 12, 1, 19, 30, 1),
                         datetime.datetime(2019, 12, 1, 20, 22, 2),
                         datetime.datetime(2019, 12, 2, 2, 13, 2),
                         datetime.datetime(2019, 12, 3, 19, 12, 2),
                         datetime.datetime(2019, 12, 3, 21, 3, 1)
                         ]}
df_example = pd.DataFrame(df_example, columns = ['id', 'activity'])
df_example['activity'] = df_example['activity'] - datetime.timedelta(hours=6, minutes=0)
df_example['date'] = df_example['activity'].apply(lambda x: x.date())
df_example.sort_values(by=['id', 'activity'])
df_example.groupby(['id', 'date']).tail(1)


texts: Determine if one string is a permutation of the another

texts:
Can anyone give me some feedback if I'm using std::unordered_multimap optimally? I don't know the ins-and-outs of the std::unordered_multimap implementation.

I'm wondering if comparing two maps iterates through each of the elements in the map, making the algorithm \$O(N^2)\$ or if it just compares the hash of the map or something making the algorithm \$O(N)\$. Or would it just be better to use an array if I'm given this question in an interview?

bool is_permutation(const std::string& s1, const std::string& s2)
{
    assert(s1.size() && s2.size());

    if(s1.length() != s2.length())
        return false;

    std::unordered_multimap<int, char> m1, m2;

    for(int i = 0; i < s1.length(); ++i)
    {
        m1.insert({s1[i], s1[i]});
        m2.insert({s2[i], s2[i]});
    }

    if(m1 == m2)
        return true;

    return false;
}