texts: Printing calculator - Stephen Kochan exercise

texts:
I'm a newbie at programming, just one month into C. Working with Stephen Kochan's programming in C. There is a question in chapter 6 to write a printing calculator where 's' tells the program to set the accumulator, 'e' tells that the execution must end. And the operators tell the operations to be performed on the accumulations.

The sample run according to the book looks like this:

10 s
=10.000000
2 /
=5.000000
55 -
=-50.000000
100.25 S
=100.250000
0 E
=100.250000

I got this to work but I'm not sure about how correct this code is.

#include<stdio.h>
// write a program for a printing calculator
// exercise 4, chapter 6, kochan

int main(void)
{
 float value, output;
 char operator;
 _Bool exit;

 printf("Please enter a value and operator to begin\n");
 scanf("%f %c", &value, &operator);

while(operator != 'e' || operator != 'E')
{
   exit = 0;

 switch(operator)
 {
    case 'S':
    case 's':
    output = value;
    printf("= %.3f\n", output);
    scanf("%f  %c", &value, &operator);
    break;

    case '+':
    output = output + value;
    printf("= %3f\n", output);
    scanf("%f  %c", &value, &operator);
    break;

    case'-':
    output = output - value;
    printf("= %.3f\n", output);
    scanf("%f  %c", &value, &operator);
    break;

    case '*':
    output = output * value;
    printf("= %.3f\n", output);
    scanf("%f  %c", &value, &operator);
    break;

    case '/':
    if(value == 0)
    printf("Division by zero\n");
    else
    output = output / value;
    printf("= %.3f\n", output);
    scanf("%f  %c", &value, &operator);
    break;

    case 'E':
    case 'e':
    output = output + value;
    printf("= %.3f\n", output);
    exit = 1;
    return 0;

    default:
    printf("Unidentified operator\n");
    return 0;

  }
}

   return 0;
}


texts: Can this LINQ lambda expression be written any better?

texts:
For the sake of knowledge, I wanted to convert a SQL query to a LINQ query expression. Here is the original SQL:

SELECT CT.COURSE_NODE_ID AS CNID, CT.NODE_TEXT
FROM    COURSE_RELATED_VERSIONS AS CRV INNER JOIN
        COURSE_TREE AS CT ON CRV.COURSE_NODE_ID = CT.COURSE_NODE_ID
WHERE (CRV.COURSE_ID = '38890') AND (CRV.COURSE_PARENT_NODE_ID = '-1')

Basically, just grabbing two fields from a table based on certain criteria (keys match, course ID matches criteria, parent node not equal -1). Here's the LINQ query expression that I came up with, using LINQPad:

from ct in COURSE_TREEs
join crv in COURSE_RELATED_VERSIONS on ct.COURSE_NODE_ID equals crv.COURSE_NODE_ID
where crv.COURSE_ID == 38890 && crv.COURSE_PARENT_NODE_ID == -1
select new {ct.COURSE_NODE_ID, ct.NODE_TEXT}

Not too bad, still understandable to my SQL-centric brain. But, for grins, I wondered what this query expression would look like as a lambda expression. For the life of me, I could not figure out the syntax. So, I used the lambda tool in LINQPad to see what my LINQ query expression would look like. Here it is:

COURSE_TREEs
.Join (
   COURSE_RELATED_VERSIONS,
   ct => ct.COURSE_NODE_ID,
   crv => crv.COURSE_NODE_ID,
   (ct, crv) =>
      new
      {
         ct = ct,
         crv = crv
      }
)
.Where (temp0 => ((temp0.crv.COURSE_ID == 38890) && (temp0.crv.COURSE_PARENT_NODE_ID ==      -1)))
.Select (
   temp0 =>
      new
      {
         COURSE_NODE_ID = temp0.ct.COURSE_NODE_ID,
         NODE_TEXT = temp0.ct.NODE_TEXT
      }
)

Whoah! Not what I figured the lambda expression query would look like. So, I'm studying the output from LINQPad on how my query expression looks as a lambda expression, and I'm wondering if it can be written any better? I'm still learning the ropes of LINQ (and lambda expressions), but I can't help but feel that the resulting lambda expression here is too complex! Am I wrong? Is it possible to write a lambda expression that produces the same output as the original SQL and query expression, but not be needlessly complex? Perhaps 'complex' is subjective, since it may only appear complex to my SQL brain. I just feel like the lambda expression generated in LINQPad can be written better... I just don't know how.


texts: Using findInterval to assign vector elements to corresponding brackets

texts:
The following function receives a vector of positive integers and list of brackets. The function returns a data frame with a logical vector for each bracket indicating whether a given element of a vector falls within that bracket.

Background

Received arguments

Vector x consisting of unique positive integers, usually corresponding to:

1:6000
c(1:100, 753:4000)

List of brackets, for instance:

list(c(1, 325),
     c(1, 651),
     c(1, 976),
     c(1, 1301),
     c(1, 1626),
     c(1, 1952))

Behaviour

For each of the brackets, the function creates a column int_brakcet_value consisting of TRUE / FALSE values indicating whether i element of vector falls within the designed bracket

Function

assign_interval <- function(x, brackets) {
    do.call("cbind",
            lapply(
                X = brackets,
                FUN = function(bracket) {
                    findInterval(x = x,
                                 vec = bracket,
                                 rightmost.closed = TRUE)
                }
            )) -> int_dta

    # Create friendly names
    int_nms <- lapply(
        X = brackets,
        FUN = function(brc) {
            paste0("int_", paste0(brc, collapse = "_"))
        }
    )

    # Set friendly names
    int_dta <- setNames(object = as.data.frame(int_dta),
                        nm = unlist(int_nms))

    # Replace findInterval outputs with T/F
    apply(X = int_dta, MARGIN = 2,
          FUN = function(col) {
              ifelse(col == 1, TRUE, FALSE)
    }) -> int_dta

    dta_res <- data.frame(int_dta)
    rownames(dta_res) <- x

    return(dta_res)
}

Tests

x <- 1:6505

res <- assign_interval(x = x, brackets = list(c(1, 325),
                                              c(1, 651),
                                              c(1, 976),
                                              c(1, 1301),
                                              c(1, 1626),
                                              c(1, 1952)))


texts:
I'm wondering if I could handle the following situation with a single function or regex call. Given the folowing input:

Some text

> Foo
> Bar
>> Baz
> Foo

The output should be:

Some text

Foo
Bar

        Baz

Foo

The following two functions do handle this situation, but I think there must be a more elegant way to handle it. I thought about regular expressions, but could not think of any pattern that replaces the input with the output (see above).

<?php
function toArray($str, $currLevel = 0, $i = 0) {
  $return = array();
  $lines = explode("\n", $str);
  for($j = count($lines); $i < $j; $i++) {
    $line = trim($lines[$i]);
    $level = preg_replace('/^((?:>|\s)+).*/','\1', $line);
    $level = substr_count($level, '>');
    if($level == $currLevel) {
      array_push($return, preg_replace('/^((?:>|\s)+)(.*)/','\2', $line));
    }
    else if($level > $currLevel) {
      array_push($return, toArray(join("\n", $lines), $currLevel  + 1, &$i));
    } else if($level < $currLevel) {
      $i--;
      return $return;
    }
  }

  return $return;
}

function toQuote($lines) {
  $return = "
\n";
  foreach($lines as $line) {
    if(is_array($line)) {
      $return .= toQuote($line);
    }
    else {
      $return .= $line . "\n";
    }
  }
  $return .= "
\n";
  return $return;
}

$str = <<<INPUT
  Some text

  > Foo
  > Bar
  >> Baz
  > Foo
INPUT;

echo toQuotes(toArray($str));


texts: Small improved std::list to manage doubloons and pointers

texts:
I am extending std::list in order to have access to convenience member functions that simplify my everyday developments (e.g. ways to deal with doubloons, delete all the stored pointers, etc.). I removed some of these member functions, but I kept the essential ones.

#ifndef __PJ_LIST_H__
#define __PJ_LIST_H__

#include <list>
#include <iostream>

// This class is a wrapper of std::list to provide some smarter functionalities
template<class T>
class PjList: public std::list<T>
{
    public:

        typedef typename PjList<T>::iterator PjIterator;

        PjList() {};
        virtual ~PjList() {};

        // Helper functions to deal with doubloons
        bool contains(const T& t);
        bool containsDoubloons();
        PjList<T> removeDoubloons();

        // Calls destructor of all list item and empty the list
        void destroyContents();

        // Accessing elements at index
        T& at(int index);

        // Inserting element around "ref"
        bool insertItem(const T& item, const T& ref, bool before = true);

};

template<class T>
bool PjList<T>::contains(const T& t)
{
    PjIterator it;

    for( it = std::list<T>::begin(); it != std::list<T>::end(); it++ )
    {
        if ( *it == t )
            return true;
    }
    return false;
}

template<class T>
bool PjList<T>::containsDoubloons()
{
    PjIterator it;
    PjIterator jt;
    int nb_occurence;

    for( it = std::list<T>::begin(); it != std::list<T>::end(); it++ )
    {
        nb_occurence = 0;
        for( jt = std::list<T>::begin(); jt != std::list<T>::end(); jt++ )
        {
            if ( *it == *jt )
                nb_occurence += 1;
        }
        if ( nb_occurence > 1 )
            return true;
    }
    return false;
}

template<class T>
PjList<T> PjList<T>::removeDoubloons()
{
    PjList<T> output;

    PjIterator it;
    for( it = std::list<T>::begin(); it != std::list<T>::end(); it++ )
    {
        T& t = *it;
        if ( !output.contains(t) )
            output.push_back(t);
    }

    return output;
}

template<class T>
void PjList<T>::destroyContents()
{
    PjIterator it;

    for( it = std::list<T>::begin(); it != std::list<T>::end(); it++ )
        delete *it;

    std::list<T>::clear();
}

template<class T>
bool PjList<T>::insertItem(const T& t, const T& ref, bool before)
{
    bool ref_found = false;

    PjIterator it;

    for( it = std::list<T>::begin(); it != std::list<T>::end(); it++ )
    {
        if ( *it == ref )
        {
            ref_found = true;
            break;
        }
    }

    if ( !ref_found )
    {
        std::cerr << "Insertion in list failed since ref item is not found" << std::endl ;
        return false;
    }

    insert(it, t);
    return true;
}

template<class T>
T& PjList<T>::at(int index)
{
    static T dummy;
    int i = 0;
    PjIterator it;

    for( it = std::list<T>::begin(); it != std::list<T>::end(); it++ )
    {
        if ( index == i++ )
            return *it;
    }
    std::cerr << "Bad index " << index << std::endl ;
    return dummy;
}

#endif


texts:
I am trying to use IXMLDOMDocument for XML reading/writing. I am not good COM, and I am not aware that I am doing things right or wrong. I am very unsure that there could be some problems with COM initialization and relase. Here is my code below and let me know If there are any possibles bugs / memory leaks here due to COM.

void MyClass::ReadXML(BSTR *pVal)
{
    IXMLDOMDocument * pXMLDoc;
    IXMLDOMNode * pXDN;

    HRESULT hr = CoInitialize(NULL);
    hr = CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER,
       IID_IXMLDOMDocument, (void**)&pXMLDoc);

    if (SUCCEEDED(hr))
    {
        IXMLDOMNode* pEntityNode = CDOMHelpers::InsertDOMElement(pDoc, NULL, L"Person", NULL);

        if (SUCCEEDED(hr))
        {
            SomeClassObject->SerializeXML(pXMLDoc, pXDN);
            pXMLDoc->get_xml(pVal);
            pXDN->Release();       // Is this proper way to release COM?
            pXDN = NULL;
            pXMLDoc->Release();
            pXMLDoc = NULL;
        }
    }
}

void SomeOtherClass::SerializeXML(IXMLDOMDocument* pDoc, IXMLDOMNode* pXDN)
{
    CStringW text;
    IXMLDOMNode* pNewNode;

    text.Format(L"%u", Name);
    pNewNode = CDOMHelpers::InsertDOMElement(pDoc, pEntityNode, L"Name", text);

    text.Format(L"%u", Address);
    pNewNode = CDOMHelpers::InsertDOMElement(pDoc, pEntityNode, L"Address", text);
}


texts:
I have written this code which finds duplicate numbers and the occurrence of a particular number in an array. I have used a HashMap, but I want to know if there is a more efficient way to do the same, or whether I should be using another method.

import java.util.*;
class test7
{
    public static void main(String ...a)
    {
        int []arr={10,20,10,2,11,10,32,15,15,10,10};
        HashMap<Integer,Integer> num=new HashMap<Integer,Integer>();
        for(int t: arr)
        {
            Integer tmp_int=new Integer(t);
            if(num.containsKey(tmp_int))
            {
                Integer i_ob=num.get(tmp_int);
                num.put(tmp_int,new Integer(i_ob.intValue()+1));
            }
            else
            {
                num.put(tmp_int,new Integer(1));
            }
        }
        System.out.println(num);
    }
}

Output:

{32=1, 2=1, 20=1, 10=5, 11=1, 15=2}


texts:
What do you think about this file system manipulation helper? There is an utility class Folder which I can use to define directory structure of my app:

static class Folders
{
    public static Folder Bin =>
        new Folder(Assembly.GetExecutingAssembly());

    public static Folder App => Bin.Up();
    public static Folder Docs => App.Down("Docs");
    public static Folder Temp => App.Down("Temp");
}

Then I can do some manipulations in an easy way:

    static void Main(string[] args)
    {
        Folders.Temp.Create();
        Folders.Bin.Run("scan.exe.", "-no-ui");
        Folders.Temp.CopyTo(Folders.Docs, f => f.EndsWith(".pdf"));
        Folders.Temp.Empty();
    }

Here is the library class Folder used above:

public class Folder
{
    readonly string _path;

    public Folder(Assembly assembly)
        : this(Path.GetDirectoryName(assembly.Location))
    {
    }

    public Folder(string path)
    {
        _path = path;
    }

    public override string ToString() => _path;

    public static implicit operator string(Folder folder) =>
        folder.ToString();

    public IEnumerable<Folder> Folders =>
        Directory.GetDirectories(this, "*", SearchOption.TopDirectoryOnly)
            .Select(p => new Folder(p));

    public IEnumerable<Folder> AllFolders =>
        Directory.GetDirectories(this, "*", SearchOption.AllDirectories)
            .Select(p => new Folder(p));

    public IEnumerable<string> Files =>
        Directory.GetFiles(this, "*.*", SearchOption.TopDirectoryOnly);

    public IEnumerable<string> AllFiles =>
        Directory.GetFiles(this, "*.*", SearchOption.AllDirectories);

    public Folder Up() =>
        new Folder(
            new DirectoryInfo(this)
                .Parent.FullName);

    public Folder Down(string folderName) =>
        new Folder(
            Path.Combine(
                this,
                folderName));

    public void Create() =>
        Directory.CreateDirectory(this);

    public void Empty()
    {
        var directoryInfo = new DirectoryInfo(this);
        if (!directoryInfo.Exists)
            return;

        foreach (var file in AllFiles)
            File.Delete(file);

        foreach (var folder in Folders)
            Directory.Delete(folder, true);
    }

    public void CopyTo(Folder destination) =>
        CopyTo(destination, file => true);

    public void CopyTo(Folder destination, Func<string, bool> filter)
    {
        //Create directories
        foreach (string directoryPath in AllFolders)
            Directory.CreateDirectory(directoryPath.Replace(this, destination));

        //Copy all the files & replaces any files with the same name
        foreach (string filePath in AllFiles.Where(filter))
            File.Copy(filePath, filePath.Replace(this, destination), true);
    }

    public void Run(string exe, string args = "")
    {
        string defaultCurrentDirectory = Environment.CurrentDirectory;
        Environment.CurrentDirectory = this;
        try
        {
            var process = new Process();
            process.StartInfo.FileName = exe;
            process.StartInfo.Arguments = args;
            process.Start();
            process.WaitForExit();
            if (process.ExitCode != 0)
                throw new InvalidOperationException(
                    $"{exe} process failed with exit code {process.ExitCode}.");
        }
        finally
        {
            Environment.CurrentDirectory = defaultCurrentDirectory;
        }
    }
}


texts: methods in the class so close in what they do

texts:
I have this class that has these two methods that are so closely related to the each other. I do not want to pass the flags so I kept them separate. I was wondering if there is a way to rewrite it so that I do not have to repeat so closely!

  class Test extends Controller
    {
        public static function nonFormattedData($param)
        {
            $arr = array();
            if (is_array($param)) {
                $i = 0;
                $sql = "
                    select *
                    from table1
                    where
                    ";

                if (isset($param['startDate'])) {
                    $sql .= "   date_created between ? AND  ?";
                    $arr[] = $param['startDate'];
                    $arr[] = $param['endDate'];
                    $i++;
                }
                if (isset($param['amount']) && !empty($param['amount'])) {

                    if ($i > 0) $sql .= " AND ";
                    $sql .= " balance= ?";
                    $arr[] = $param['amount'];
                    $i++;
                }
                if (isset($param) && !empty($param['amount'])) {

                    if ($i > 0) $sql .= " AND ";
                    $sql .= " balance= ?";
                    $arr[] = $param['amount'];
                    $i++;
                }
                if (isset($param['createdBy']) && !empty($param['createdBy'])) {

                    if ($i > 0) $sql .= " AND ";
                    $sql .= " column2 like '%Created By: " . $param['createdBy'] . "%'";
                }
                $sql .= ' group by id.table1 ';
                $rs = Query::RunQuery($sql, $arr);
                foreach ($rs as $row) {
                    $records = new Account();
                    $results[] = $records;
                }
                return $results;
            }
        }

        public static function formattedData($serArray, $orderBy = "giftcardaccount_id desc", $offset = 0, $limit = 10)
        {
                $arr = array();
            if (is_array($param)) {
                $i = 0;
                $sql = "
                    select *
                    from table1
                    where
                    ";

                if (isset($param['startDate'])) {
                    $sql .= "   date_created between ? AND  ?";
                    $arr[] = $param['startDate'];
                    $arr[] = $param['endDate'];
                    $i++;
                }
                if (isset($param['amount']) && !empty($param['amount'])) {

                    if ($i > 0) $sql .= " AND ";
                    $sql .= " balance= ?";
                    $arr[] = $param['amount'];
                    $i++;
                }
                if (isset($param) && !empty($param['amount'])) {

                    if ($i > 0) $sql .= " AND ";
                    $sql .= " balance= ?";
                    $arr[] = $param['amount'];
                    $i++;
                }
                if (isset($param['createdBy']) && !empty($param['createdBy'])) {

                    if ($i > 0) $sql .= " AND ";
                    $sql .= " column2 like '%Created By: " . $param['createdBy'] . "%'";
                }
                $sql .= ' group by id.table1 ';
                $rs = Query::RunQuery($sql, $arr);

                return array("data" => $rs);
            }
        }

    }


texts: Simple function to create Tokens from user input

texts:
I am new to programming in Rust and as an exercise I was making a simple Lottery checker program.
It has a simple menu, the user enters a number for the corresponding option such as 'Add a line', 'Check if I am a winner' etc.

So all the user needs to do is enter either a number or a 'y' or 'n'.
So I created a simple Token to see if they have either entered a number or a char and return a token.

This works fine. But as I am on my own I was looking for feedback so that I can improve my skills.

use std::io::{self, Write};

#[derive(Debug, PartialEq)]
enum Token {
    Number(i32),
    Decision(char),
    // Error(String),
}

fn get_number(val: &str) -> Option<Token> {
    if let Some(x) = val.split_whitespace().next() {
        let y: i32 = match x.parse() {
            Ok(val) => val,
            Err(_error) => return None,
        };
        Some(Token::Number(y))
    } else {
        None
    }
}

fn get_char(val: &str) -> Option<Token> {
    if let Some(x) = val.split_whitespace().next() {
        let y: char = match x.parse() {
            Ok(val) => val,
            Err(_error) => return None,
        };
        Some(Token::Decision(y))
    } else {
        None
    }
}

fn get_input(msg: &str, input: &str) -> Option<Token> {
    print!("{}\n{}", msg, ">> ");
    io::stdout().flush().unwrap();

    let buffer = input;
    //let mut buffer = String::new();
    // while buffer.is_empty() {
    // io::stdin()
    // .read_line(&mut buffer)
    // .expect("GET_INPUT: error reading line.");

    //  buffer = buffer
    // .trim()
    // .parse()
    //  .expect("GET_INPUT: error parsing buffer");

    // if buffer.is_empty() {
    //     println!("You didn't enter anything.\n{}", &msg)
    // };
    // }

    if let Some(token) = get_number(&buffer) {
        if let Token::Number(val) = token {
            return Some(Token::Number(val));
        }
    } else if let Some(token) = get_char(&buffer) {
        if let Token::Decision(val) = token {
            return Some(Token::Decision(val));
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn get_input_test() {
        let chars1 = "@  n 23";
        let chars2 = "34 n 23";
        let chars3 = "$ ££$^\"3234y n 23";
        let chars4 = "";
        let chars5 = "      ";

        assert_eq!(Some(Token::Decision('@')), get_input("", &chars1));
        assert_eq!(Some(Token::Number(34)), get_input("", &chars2));
        assert_eq!(Some(Token::Decision('$')), get_input("", &chars3));
        assert_eq!(None, get_input("", &chars4));
        assert_eq!(None, get_input("", &chars5));
    }

}

To get some more fine grain control I understand I will need to use an Iterator, is this correct?


texts:
Fellow students are supposed to review and tell what my code is doing for a grade, this is why I'm asking on here first. I want to see if its clear enough.

public class SpellParser {

private static final String SPELL_PACKAGE_LOCATION = "edu.swosu.wordcraft.spells.";

         private Document dom;

         public SpellParser() {
                 setUpDom();
         }

            public void setUpDom(){
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        dom = docBuilder.parse("resources/Spells.xml");
    } catch(Exception e) {
        e.printStackTrace();
    }
}

public void parse(){
    //get the root element
    Element docEle = dom.getDocumentElement();

    //get a nodelist of elements
    NodeList nl = docEle.getElementsByTagName("spell");
    if(nl != null && nl.getLength() > 0) {
        for(int i = 0 ; i < nl.getLength();i++) {

            //get the spell element
            Element el = (Element)nl.item(i);

            //get the Employee object
            Spell s = getSpell(el);

            //add it to list
            Spell.addSpell(s);
        }
    }
}


texts: Merge two sorted arrays that can be of different sizes

texts:
I think the algorithm implementation itself is reasonably efficient, but I'm not sure about proper use of good practices in software development in the code (variable naming, idioms, comments, error handling in inputs etc).

I'm attempting to get a first developer job, and since interviewers also evaluate how "clean" the code is, the main point of the question is what is considered good practice, but efficiency improvements are also welcome.

mergeSortedArrays = function(arr1, arr2){
  if(!(Array.isArray(arr1) && Array.isArray(arr2))){
    throw new TypeError("Need two arrays to merge")
  };

  if(arr2.length === 0 && arr1.length === 0){
    throw new RangeError("Cannot merge empty arrays")
  };

  let i = 0;
  let j = 0;

  const targetSize = arr1.length + arr2.length;
  const mergedArray = [];
  // main loop
  while(mergedArray.length < targetSize){
    /**
     * Works until completion for arrays of the same size
     */
    if(arr1[i] < arr2[j]){
      valueToPush = arr1[i]
      i++
    }else{
      valueToPush = arr2[j]
      j++
    }
    /**
     * For arrays with different sizes, it is safe to push the remainder to the sorted array, given that both inputs are sorted.
     */
    if(valueToPush === undefined){
      const remainingItems = j > arr2.length ? arr1.slice(i) : arr2.slice(j)
      mergedArray.push(...remainingItems)
      break
    }

    mergedArray.push(valueToPush)
  }
  return mergedArray;
}
```


texts: Project Euler Problem 10. Sum of all primes < 2mil

texts:
I'm new to coding so I can't create complex code yet. I do as much as I can with fors and ifs, since while I know a bit about arrays and other topics, I am not familiar enough with them to apply them on my own. This code works, but if I tell it to go to 2 million in main the program never finishes; 200,000 took about a minute, while 20,000 took a few seconds.

I get that this code is unoptimized and does too many unnecessary checks and calculations. Is there a way to optimize the program with just loops and conditions?

#include<iostream>
int nopf(int k){
    int sn=0,b;
    for(b=2;b<k;b++){
        if(k%b==0)sn++;
    }
    return sn;
}

main(){
    int i,s=0;
    for(i=2;i<200000;i++){
        if(nopf(i)==0)s+=i;
    }

    cout<<s;

}

NB: nopf is a function to check if a number is prime or not.


texts: Multiples of 3 and 5 from Euler code challenge

texts:
I have implemented the first coding challenge on http://projecteuler.net/. I would love to get it reviewed by some expert rubyists!

# Multiples of 3 and 5
#
# If we list all of the natural numbers below 10 that are multiples of
# 3 and 5, we get 3,5,6 and 9. THe sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.

class Multiples

  def multiples
    numbers = Array(1..999)
    multiples = Array.new
    for i in numbers
      if i%3 == 0 or i%5 == 0
        multiples.push(i)
      end
    end
    multiples
  end

  def sumMultiples(multiples)
    total = 0
    multiples.each { |i| total+= i }
    puts(total)
  end

end

multiples = Multiples.new
multiples.sumMultiples(multiples.multiples)


texts:
I have a set of Service, and I want to partition them into ServiceClass, and have a reference from a Service to the Service class its belong.
I am storing the reference in Dictionary<Service, ServiceClass>.

In the code below, I want to split into five service classes. I feel the code below is not well written, such as the naming of variable, but I am not sure how to improve it, can anyone help?

int group = 5;
List<Service> service = FileIO.ReadFeatureFile(@"D:\C Drive\Desktop\input.txt");
int numPerClass = service.Count / group;
Dictionary<Service, ServiceClass> ServiceToServiceClass = new Dictionary<Service, ServiceClass>();

for (int i = 0; i < group - 1;i++ )
{
    List<Service> serviceGrp = service.GetRange(0, numPerClass);
    ServiceClass sc=new ServiceClass(serviceGrp);
    foreach(Service service1 in serviceGrp)
    {
        ServiceToServiceClass.Add(service1, sc);
    }
    service.RemoveRange(0, numPerClass);
}

ServiceClass sc1 = new ServiceClass(service);
foreach (Service service1 in service)
{
    ServiceToServiceClass.Add(service1, sc1);
}


texts: Simple way to prevent duplicate logging of errors

texts:
I've been tasked with updating our current error logging system to prevent the logging of similar errors (from a single client program) that were probably caused by the same event. The code here is what I have added in order to accomplish this. Are there any obvious issues I am missing or is there a simpler way to accomplish this? I need to deal with multiple threads.

Here is the simple error object we use:

public class ErrorObject
{
    //to use when sending an object to a background worker
    public ErrorObject(Exception exception, string additionalinfo,DateTime? dateTime = null,bool showTouser = false)
    {
        Exception = exception;
        AdditionalInfo = additionalinfo;
        Time = dateTime ?? DateTime.Now;
    }

    public Exception Exception { get; set; }
    public string AdditionalInfo { get; set; }
    public DateTime Time { get; set; }
    public bool ShownToUser { get; set; }
}

Other code calls this function to log errors.

public static Int32 LogError(Exception ex, bool runInBackground = true, string additionalInfo = "",
    bool ShownToUser = false)
{

    int retVal = -1;
    if (runInBackground)
    {
        ErrorObject newError = new ErrorObject(ex,additionalInfo,DateTime.Now,ShownToUser);

        ThreadPool.QueueUserWorkItem(LogErrorInBackground, newError);
    }
    else
    {
        try
        {   //Do a Sql Insert in current thread (slow for remote labs...)
            retVal = InsertError(ex, additionalInfo, ShownToUser);
        }
        catch{}
    }
    return retVal;
}

//Store 4 previous errors to compare against
private static Queue<ErrorObject> PreviousErrors = new Queue<ErrorObject>(4);
private static object PreviousErrorLock = new object();

private static void LogErrorInBackground(object state)
{
    ErrorObject error = (ErrorObject) state;

    if (! QueueNewError(error))
    {
        InsertError(error.Exception, error.AdditionalInfo, error.ShownToUser);
    }
}

/// <summary>Adds an error to the PreviousErrors Queue and removes the error at the front of the list.</summary>
/// <returns>Returns true if the error is a duplicate of any other previous errors in the queue.</returns>
private static bool QueueNewError(ErrorObject newError)
{
    //Assume the new error is not a duplicate
    bool isDuplicate = false;

    lock (PreviousErrorLock)
    {

        foreach (ErrorObject previousError in PreviousErrors)
        {
            if (previousError.AdditionalInfo == newError.AdditionalInfo &&
            Math.Abs((previousError.Time - newError.Time).TotalSeconds) < 3 &&
            previousError.Exception.GetType() == newError.Exception.GetType() &&
            previousError.Exception.Message == newError.Exception.Message &&
            previousError.Exception.TargetSite == newError.Exception.TargetSite)
            {
                isDuplicate = true;
                break;//Exit the loop
            }
        }

        if( PreviousErrors.Count > 0)
            PreviousErrors.Dequeue();
        PreviousErrors.Enqueue(new ErrorObject(newError.Exception, newError.AdditionalInfo, newError.Time));
    }
    return isDuplicate;
}


texts:
I have a project where I need ODE solver without dependencies to libraries like Scipy. I decide to implement ODE45. According to tutorials from internet and from what I remember from classes I implement it somehow.

The code below contains also example function (pendulum) with exactly same values as in the scipy ODE tutorial https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.integrate.odeint.html. The resulting plot from my code looks the same.

However, I am not really sure if I done it in the good way. Especially I would really appreciate any hints how to improve the functions ode45_step and ode45 and verification whether my implementation is correct. I do not need to check the input variables, it will be done somewhere else.

import numpy as np
import matplotlib.pylab as plt

def ode45_step(f, x, t, dt, *args):
    """
    One step of 4th Order Runge-Kutta method
    """
    k = dt
    k1 = k * f(t, x, *args)
    k2 = k * f(t + 0.5*k, x + 0.5*k1, *args)
    k3 = k * f(t + 0.5*k, x + 0.5*k2, *args)
    k4 = k * f(t + dt, x + k3, *args)
    return x + 1/6. * (k1 + k2 + k3 + k4)

def ode45(f, t, x0, *args):
    """
    4th Order Runge-Kutta method
    """
    n = len(t)
    x = np.zeros((n, len(x0)))
    x[0] = x0
    for i in range(n-1):
        dt = t[i+1] - t[i]
        x[i+1] = ode45_step(f, x[i], t[i], dt, *args)
    return x

def f(t, y, b, c):
    """
    Pendulum example function.
    """
    theta = y[0]
    omega = y[1]
    dydt = [omega, -b*omega - c*np.sin(theta)]
    return np.array(dydt)

b = 0.25
c = 5.0

N = 101

x0 = np.array([np.pi - 0.1, 0.0])
t = np.linspace(0, 10, N)

x = ode45(f, t, x0, b, c)

plt.plot(x)
plt.show()


texts: Memory leak in Java's stack implementation

texts:
Recently I was asked to implement a stack specifically for storing 'int' type data and find memory leaks. Isn't the garbage collector responsible for releasing all the memory? What are the possible memory leaks and how do I handle them?

import java.util.NoSuchElementException;
public class MyStack {

    private int stack[];
    private int top = -1;

    private MyStack() {

    }

    MyStack(int capacity) {
        stack = new int[capacity];
    }

    public void push(int data) {
        if(top == (stack.length-1))
            throw new IllegalStateException("Stack is full.");
        top++;
        stack[top] = data;
    }

    public int pop() {
        if(top == -1)
            throw new NoSuchElementException("Stack is empty.");
        int data = stack[top];
        top--;
        return data;
    }

    public int peek() {
        if(top == -1)
            throw new NoSuchElementException("Stack is empty.");
        return stack[top];
    }

    public int size() {
        return top + 1;
    }

    public boolean isEmpty() {
        if(top == -1)
            return true;
        return false;
    }

    public static void main(String args[]) {
        MyStack stack = new MyStack(5);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        //stack.push(6);
        System.out.println("capacity::" + stack.size());
        System.out.println("top::" + stack.peek());
        System.out.println("pop::" + stack.pop());
        System.out.println("top::" + stack.peek());
        System.out.println("pop::" + stack.pop());
        System.out.println("pop::" + stack.pop());
        System.out.println("pop::" + stack.pop());
        System.out.println("pop::" + stack.pop());
        System.out.println("isEmpty::" + stack.isEmpty());
        //System.out.println(stack.pop());
    }
}


texts:
I wrote a dynamic stack in C that uses an array as a structure.  I tried to maintain O(1) for push and pop and believe I have done so.  I want to know what can be written in a cleaner way and if there are any non-trivial bugs.
#include <stdio.h>
#include <stdlib.h>

int push(int val, int *c);
int pop(int *c);

int *stack;

int main(){
    int *c = malloc(sizeof(int));
    stack = malloc(sizeof(int));
    *c = 0;
    int i;
    for(;;){
       printf("1. Push\n2. Pop\n3. Stack\n4. Quit\n>>> ");
       scanf("%d", &i);
       if(i == 1){
           printf("Value: ");
           scanf("%d", &i);
           push(i, c);
       }
       else if(i == 2)
           printf("Value popped: %d\n", pop(c));
       else if(i == 3)
           for(int i = 0; i < *c; i++)
               printf("%d\n", stack[i]);
       else
           break;
    }
    free(stack);
    return 0;
}

int push(int val, int *c){
    int *r;
    r = realloc(stack, ((*c)+1)*sizeof(int));
    if (r == NULL){
        free(stack);
        exit(0);
    }
    stack = r;
    stack[*c] = val;
    ++(*c);
    return *c;
}

int pop(int *c){
    if (!(*c)) return -1;
    int x = stack[(*c)-1];
    stack[(*c)-1] = NULL;
    int *r;
    printf("%d\n", *c);
    r = realloc(stack, ((*c)-1)*sizeof(int));
    if(r == NULL){
        free(stack);
        exit(0);
    }
    --(*c);
    stack = r;
    return x;
}

```


texts: Rewriting clumsy code that gets the value of a nested property in JS object

texts:
I have an API that returns JSON, where the value that I need is stored in either one of the two object properties:

data.d.GetContextWebInformation.FormDigestValue

or

data.value.GetContextWebInformation.FormDigestValue

The code that I'm using is pretty clumsy. At first, I used something like this:

if (data && data.d && data.d.GetContextWebInformation && data.d.GetContextWebInformation.FormDigestValue) {
    this.options.token = data.d.GetContextWebInformation.FormDigestValue;
} else {
// check for second one

Now I've rewritten it using try/catch, and it looks a bit cleaner, but still clumsy:

    var token;
    try {
        // If Verbosity was odata=verbose:
        token = data.d.GetContextWebInformation.FormDigestValue;
    } catch (ex) {
        try {
            // If Verbosity was odata=nometadata or odata=minimalmetadata:
            token = data.value.GetContextWebInformation.FormDigestValue;
        } catch (ex) {
            throw 'Unable to obtain authorization token.';
        }
    } finally {
        if (token) { this.options.token = token; }
    }

What would be a better way to write the same code for a cleaner, nicer look? If that matters, I need to support IE9 so probably can't use newer language features.


texts: Dynamic List Application as first Vue.js App

texts:
Task Description:

Create a div-element and take control over it using a Vue-Instance.
Print an array of hobbies into the div-element. Provide some default hobbies.
Add a 'New Hobby' button and a text-input element. So that the user can add additional hobbies.
When a hobby list-item is clicked, it shall be removed from the list.
Add a "Hobby deleted"-paragraph which is only shown when a hobby-item has been deleted at least one time.
Above the list of hobbies add a hobby-counter which shows the current count of hobby-items.
Style the hobby-list depending on whether you have more or less then 3 hobbies in the list.
Outsource  your hobbies (the list-item elements) into a component (so that it becomes re-usable).

Here's my solution for the points 1 to 7:

new Vue({
  el: '#app',
  data: {
    hobbies: [{
        name: 'Running'
      },
      {
        name: 'Chess'
      },
      {
        name: 'Cooking'
      },
      {
        name: 'Hiking'
      }
    ],
    newHobby: '',
    deleted: false
  },
  methods: {
    addHobby: function() {
      this.hobbies.push({
        name: this.newHobby
      });
    },
    removeHobby: function(event) {
      let updatedHobbies = this.hobbies.filter((hobby) => {
        return hobby.name !== event.target.textContent.trim();
      });

      this.hobbies = updatedHobbies;

      if (!this.deleted) {
        this.deleted = true;
      }
    },
    setStyle: function() {
      if (this.hobbies.length < 3) {
        return 'pink';
      } else if (this.hobbies.length === 3) {
        return 'orange';
      } else {
        return 'cyan';
      }
    }
  }
});
#app {
  max-width: 800px;
  margin: 0 auto;
}

li {
  margin: 10px;
}

Hobbies: {{ hobbies.length }}

    <input type="text" id="newHobby" v-model="newHobby" />
    <button v-on:click="addHobby" id="addNewHobby">Add New Hobby</button>

Hobby deleted!

    {{ hobby.name }}

Is everything done in a good way and manner?

Where could my implementation been improved?

Any ideas how to solve point 8?

There I get finally stucked.

Looking forward to read your comments and answers.


texts: Calculate the day when Date is given as input using the Doomsday algorithm

texts:
Was too bored in holidays...here's a code which finds the day of the week using the algorithm in this video. Please give a logical date in the correct format cause I didn't account for improper inputs cause I'm too lazy. My code is short and sweet.

day=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]    #some database numbers and strings
mdoom=[3,28,14,4,9,6,11,8,5,10,7,12]
while True:
    entry=input('\nEnter a date in DD/MM/YYYY format:')         #Input date in a specified format
    date,month,year = map(int,entry.split('/'))                 #Get the date,month and year
    centdoom=[3,2,0,5]
    a=centdoom[((year//100)%4)-3]
    b=(year%100)//12
    c=(year%100)%12
    d=c//4                                                      #Random calculations for doomsday :)
    e=a+b+c+d

    if (year%4==0) and ((year%100!=0) or (year%400==0)):        #Checks for leap year
        mdoom[0],mdoom[1]=4,29

    ddoom=e%7                                                   #finds a date in the 1st week which has the same day as the doomsday
    r=mdoom[month-1]                                            #Gives the doomsdate in the input month
    r=r%7
    r=ddoom-r
    date=date%7                                                 #finds a date in the 1st week which has the same day as the input date
    print('\n',day[(r+date)%7])                                 #prints the output
    k=input('\nTry again?(y/n)')
    if k=='y':
        continue
    else:
        break

And any suggestions or improvements are welcome.


texts:
I recently had an interesting requirement in a test environment where I needed to simulate actions at varied (random) intervals in a node back-end. They needed to be sequentially executed, but queued so I could fire and move on. Using a typical timeout/interval here wouldn't work, since if I set a timeout for fn1 to execute after 500ms and then set a timeout for fn2 to execute after 250ms, fn2 would execute before fn1, which was not desired.

To solve this, I created a queue object that executes queued commands sequentially. It works perfectly for my scenario, but I was wondering if there were any opportunities for improvement. I realize I should probably be checking input parameters to make sure the passed in function is indeed a function, as well as the delay being a number. Maybe there are other opportunities for improvement. Let me know!

var TimerQueue = (function () {
    var timers = [];
    var running = false;
    var currentInterval;
    var currentTimer;

    this.addTimer = function (fn, delay) {
        timers.push({fn: fn, delay: delay});

        function exec() {
            currentTimer.fn();
            clearInterval(currentInterval);
            if (timers.length > 0) {
                currentTimer = timers.shift();
                currentInterval = setInterval(exec, currentTimer.delay);
            } else {
                running = false;
            }
        }

        if (!running) {
            running = true;
            currentTimer = timers.shift();
            currentInterval = setInterval(exec, currentTimer.delay);
        }
    };

    this.clear = function () {
        if (currentInterval) {
            clearInterval(currentInterval);
        }
        timers = [];
        running = false;
    };

    return this;
});

Usage:

var queue = new TimerQueue();
queue.addTimer(function () { console.log('1st') }, 500);
queue.addTimer(function () { console.log('2nd') }, 250);


texts: Finding ideal sport based on weighted attributes

texts:
The program takes weighted strengths of the human body (arms/legs/core/mind) based on the required attributes for a sport, then tells you the resulting sport. The program is obviously really ugly. Is there a way I could use dictionaries and a lambda function to find a max instead? This latter part is what I don't know how to do.

print("Welcome to What's your ideal sport! Answer the following questions on a scale from 1-10.")

leg_strength = int(input("How good is your leg strength / speed?"))
arm_strength = int(input("How good is your arm strength?"))
core_strength = int(input("How strong are your abs?"))
mental_strength = int(input("How intelligent are you?"))
reaction_time = int(input("How fast are your reactions?"))

# Sports are: Soccer, Football, Tennis, Swimming, Basketball, Track, Gymnastics, and Chess.

sports = []

soccer = (arm_strength*5) + (reaction_time*2) + (mental_strength) + (arm_strength) + (core_strength)
sports.append(soccer)
chess = mental_strength * 10
sports.append(chess)
football = (arm_strength*4) + (core_strength*3) + (leg_strength*3)
sports.append(football)
tennis = (reaction_time*3) + (arm_strength*4) + (core_strength*2) + (mental_strength)
sports.append(tennis)
swimming = reaction_time + (core_strength*3) + (arm_strength*3) + (leg_strength*3)
sports.append(swimming)
basketball = (leg_strength*2) + (arm_strength*5) + (mental_strength*2) + core_strength
sports.append(basketball)
track = (leg_strength*6) + (arm_strength*2) + (reaction_time) + (mental_strength)
sports.append(track)
gymnastics = (leg_strength*3) + (arm_strength*3) + (core_strength*3) + mental_strength
sports.append(gymnastics)

print(sports)

best = max(sports)
sports.index(best)

indices = []

for sport in sports:
    if sport == best:
        indices.append(sports.index(sport))

result = []

for index in indices:
    if index == 0:
        result.append("Soccer")
    elif index == 1:
        result.append("Chess")
    elif index == 2:
        result.append("Football")
    elif index == 3:
        result.append("Tennis")
    elif index == 4:
        result.append("Swimming")
    elif index == 5:
        result.append("Basketball")
    elif index == 6:
        result.append("Track")
    elif index == 7:
        result.append("Gymnastics")

    print("Your best olympic sport(s) are: {0}.".format(result))


texts: A Class to Supply an Open Database Connection during the life of a Web Request

texts:
For some database requests, I like to use raw ADO.NET.

In the context of a web request, I have created a class which provides an open IDbConnection object.

I use a Dependency Injection library ("DI") to do this, scoping the object instantiated from this class to a web request. So, disposal of the object is handled by the DI container.

The abstraction for this class is simple and looks like this:

public interface IDbConnectionManager : IDisposable
{
    IDbCommand BuildCommand(DbParameter[] parameters, string query);
    IDbConnection GetOpenConnection();
}

And the concrete implementation, written for Sql Server, looks like this:

public class DbConnectionManager : IDbConnectionManager
{
    public SqlConnection DbConnection;
    public string ConnectionString { get; set; }

    public DbConnectionManager(string connectionString)
    {
        ConnectionString = connectionString;
    }

    public IDbConnection GetOpenConnection()
    {
        return GetOpenSqlConnection();
    }

    private SqlConnection GetOpenSqlConnection()
    {
        if (ReferenceEquals(DbConnection, null))
        {
            DbConnection = new SqlConnection(ConnectionString);
        }

        if (DbConnection.State != ConnectionState.Open)
        {
            DbConnection.Open();
        }

        return DbConnection;
    }

    public IDbCommand BuildCommand(DbParameter[] parameters, string query)
    {
        if (parameters == null) throw new ArgumentNullException(nameof(parameters));
        if (string.IsNullOrWhiteSpace(query)) throw new ArgumentException(nameof(query));

        var command = new SqlCommand { Connection = GetOpenSqlConnection() };
        command.Parameters.AddRange(parameters);
        command.CommandText = query;

        return command;
    }

    public void Dispose()
    {
        DbConnection?.Dispose();
    }
}

You can see the BuildCommand method uses the GetOpenSqlConnection for its connection.

The main reason I have taken this approach is because DbConnections are expensive. But I'm not sure whether that relates to creating a connection or opening one.

I'm aware that connection pooling is available (if enabled), but I figured for simple web requests (think API), with perhaps just 2 queries to the database, that this would probably be a good approach.

And as can be seen, there's not a lot to the code.

I just wanted a bit of feedback on this code/approach.
And if you can see any potential problems with it, by all means let me know that too.

As a last comment, I am aware that a developer could manually call Dispose or use it in a using block (thereby calling Dispose).
This would be on me as lead developer to ensure that this doesn't happen and that devs understand that the DI container disposes of the object.


texts: Hacker rank - Left rotation - PHP code feedback

texts:
Here is the problem description - https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem

  A left rotation operation on an array of size \$n\$ shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array \$[1,2,3,4,5]\$, then the array would become \$[3,4,5,1,2]\$.

  Given an array of \$n\$ integers and a number, \$d\$, perform \$d\$ left rotations on the array. Then print the updated array as a single line of space-separated integers.

I wanted to get some feedback on my solution for this problem, it's a task in the Hackerrank Cracking the Coding Interview series.
I am pretty sure the code is working fine, as it passes 7 of the 9 test cases, but is getting timed-out for the last two cases, since these cases are unknown, I wanted to get some expert feedback, as how can I optimize this code.

<?php
    //$handle = fopen ("input_leftR.txt","r");
    $handle = fopen ("php://stdin","r");
    fscanf($handle,"%d %d",$n,$k); //n and k values are available from here
    $a_temp = fgets($handle);
    $a = explode(" ",$a_temp);
    array_walk($a,'intval');

    //My Code from below
    $i; $j; $temp;
    if($n<0 || $n>1000000 || $k<0|| $k>1000000 || count($a) <=0)
        exit;
    for($i=0; $i<$k%$n; $i++){
    //for($i=0; $i<$k; $i++){
        for($j=0; $j<$n-1; $j++){
            $temp = $a[$j];
            $a[$j] = $a[$j+1];
            $a[$j+1] = $temp;
        }
    }
    //array_walk($a,'intval');
    //print implode(" ", $a);
    /*foreach($a as $key=>$value){
        printf("%d", $value);
        if($key<$n-1)
            printf(" ");
    }*/

    for($i=0;$i<$n;$i++){
    printf("%d", $a[$i]);

    if($i<$n-1)
        printf(" ");
    }
?>


texts:
I am currently in an intro C++ programming class. We have an assignment where we have to convert a dollar and cents amount, say $192.89, to bills and coins using the least amount of both. Below is the program I have written.

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
    double TotalAmount;
    int DollarsConversion;
    int Change;
    int Dollars;
    int Hundreds = 0;
    int Fifties = 0;
    int Twenties = 0;
    int Tens = 0;
    int Fives = 0;
    int Ones = 0;
    int CentsConversion;
    int Cents;
    int Quarters = 0;
    int Dimes = 0;
    int Nickels = 0;
    int Pennies = 0;

    cout << "Please enter the amount to convert: $";
    cin >> TotalAmount;

    //Dollars Calculation.
    DollarsConversion = TotalAmount * 100;
    Hundreds = DollarsConversion / 10000;
    Change = DollarsConversion % 10000;
    Fifties = Change / 5000;
    Change %= 5000;
    Twenties = Change / 2000;
    Change %= 2000;
    Tens = Change / 1000;
    Change %= 1000;
    Fives = Change / 500;
    Change %= 500;
    Ones = Change / 100;
    Change %= 100;

    //Resets the Stack to calculate for the cents.
    Dollars = TotalAmount;
    CentsConversion = TotalAmount * 1000;
    Dollars *= 1000;
    Cents = CentsConversion - Dollars;

    //Cents Calculation.
    Quarters = Cents / 250;
    Change = Cents % 250;
    Dimes = Change / 100;
    Change %= 100;
    Nickels = Change / 50;
    Change %= 50;
    Pennies = Change / 10;
    Change %= 10;

    cout << "\nNumber of Hundred Dollar Bills: " << Hundreds << endl;
    cout << "Number of Fifty Dollar Bills: " << Fifties << endl;
    cout << "Number of Twenty Dollar Bills: " << Twenties << endl;
    cout << "Number of Ten Dollar Bills: " << Tens << endl;
    cout << "Number of Five Dollar Bills: " << Fives << endl;
    cout << "Number of One Dollar Bills: " << Ones << endl;

    cout << "\nNumber of Quarters: " << Quarters << endl;
    cout << "Number of Dimes: " << Dimes << endl;
    cout << "Number of Nickels: " << Nickels << endl;
    cout << "Number of Pennies: " << Pennies << endl;

    return 0;
}


texts: List all repeated substrings with a fixed length

texts:
While fiddling around, I've made a very simple and naive function to retrieve any repeated sub-string within a certain string.

function getRepetitions(str, length){
    if(isNaN(length))
    {
        throw new TypeError('length must be a number');
    }

    if(length < 1 || length > 2147483647)
    {
        throw new RangeError('length must be between 1 and 2147483647');
    }

    var copy = str.toString();

    if(length > (copy.length / 2))
    {
        length = Math.ceil(copy.length / 2);
    }

    var x = {};
    for(var i = str.length - length - 1; i > 1; i--)
    {
        piece = copy.substr(i, length);
        if(!x[piece] && copy.indexOf(piece) !== i)
        {
            x[piece] = copy.split(piece).length - 1;
        }
    }

    return x;
}

It accepts anything that can be converted into a string, and expects the length of the substring to be found.

The length must be withing a certain range and must be a valid number. It will be converted into a 32-bit signed integer later on.

This will be part of a larger project, and just want to make sure it is as polished as it can be.

Performance:

Performance is quite satisfactory. It takes around 2.5s to search 9-bytes long repetitions, on a 8.58MB string, on my machine, using Google Chrome v47.0.2526.106.

Using IE11, it takes over twice the time (around 5.6s)!

Screenshots: Google Chrome, IE11.

The time it takes is always around the same (with very small variations), which is a good thing.

Running this code on a string that is 10% the size will take 10% of the time. That is, for a string that is 0.86MB it will take around 250ms.

This is the code used to test:

var str = Array(1000001).join('123456789');
console.time('x');
getRepetitions(str, 9);
console.timeEnd('x');
console.log((str.length / 1024 / 1024).toFixed(2) + 'MB');

Note: There are a few edge cases, such as (very rarely) substrings like prototype and __proto__ going untouched. I am aware of those and I have no idea how to avoid it.

In terms of performance, readability, boundary checking and reliability, what can be improved?


texts: Work-in-Progress Form to be used throughout an application

texts:
I want to write my own Work-In-Progress form to use it throughout my app (for the time being, mostly as an exercise).

I came up with the following code, I would like to know what are the design issues, if this is not the way to go, if it could be simpler or more generic.

Main form:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    delegate void InvokeMethodDelegate(ProgressBar pb, Label status, string statusText);

    private void button1_Click(object sender, EventArgs e)
    {
        var frmWorking = new Form3();

        var wds = new WorkingDialogSettings("Working...", 1, 1, 1, 10, /*async*/ (pb) =>
        {
            for (long i = 0; i < 10; i++)
            {

                doWork(frmWorking.ProgressBar, frmWorking.Label, $"Progress step {i + 1}");
                Thread.Sleep(TimeSpan.FromSeconds(1));
                //if I use await the task immediately completes, using thread sleep blocks it till completion
                //await Task.Delay(TimeSpan.FromSeconds(1));
            }

        });
        frmWorking.ShowDialog(wds);
    }

    private async void doWork(ProgressBar pb, Label status, string statusText)
    {
        if (pb.InvokeRequired || status.InvokeRequired)
        {
            pb?.Invoke(new InvokeMethodDelegate(doWork), pb, status, statusText);
            return;
        }

        pb.PerformStep();
        await Task.Delay(TimeSpan.FromSeconds(0.5));
        status.Text = statusText;
    }
}

Work-In-Progress form:

 public partial class Form3 : Form
{
    public Label Label { get { return label1; } }
    public ProgressBar ProgressBar { get { return progressBar1; } }

    private WorkingDialogSettings _wds;
    public Form3()
    {
        InitializeComponent();
    }

    private void Form3_Load(object sender, EventArgs e)
    {
        Task.Run(() =>
        {
            _wds.ProgressBarAction(ProgressBar);
        }).ContinueWith((t) =>
        {
            if (t.Status == TaskStatus.RanToCompletion)
            {
                Label.Text = "*** COMPLETED ***";
                Cursor = Cursors.Default;
            }
        });

    }

    public void ShowDialog(WorkingDialogSettings workingDialogSettings)
    {
        _wds = workingDialogSettings;
        ProgressBar.Minimum = workingDialogSettings.Minimum;
        ProgressBar.Maximum = workingDialogSettings.Maximum;
        ProgressBar.Step = workingDialogSettings.Step;
        ProgressBar.Value = workingDialogSettings.Value;
        this.Text = workingDialogSettings.Title;

        this.ShowDialog();
    }
}

public class WorkingDialogSettings
{
    public WorkingDialogSettings(string title, int step, int value, int minimum, int maximum, Action<ProgressBar> progressBarAction, List<string> statuses = null)
    {
        Title = title;
        Step = step;
        Value = value;
        Minimum = minimum;
        Maximum = maximum;
        ProgressBarAction = progressBarAction;
        Statuses = statuses;
    }

    public string Title { get; private set; }
    public int Step { get; private set; }
    public int Value { get; private set; }
    public int Minimum { get; private set; }
    public int Maximum { get; private set; }
    public IEnumerable<string> Statuses { get; private set; }

    public Action<ProgressBar> ProgressBarAction { get; private set; }

}

Any corrections, suggestions, remarks ?


texts:
I recently answered a question
 on Stack Overflow about finding the k-largest element in an array, and
present my implementation of the Quickselect algorithm in Swift for review.

This is essentially the iterative version described in
Wikipedia: Quickselect, only that the
paritioning does not move the pivot element to the front of the second partition.
That saves some swap operations but requires an additional check when updating the lower bound.

The language is Swift 3, compiled with Xcode 8.1.

extension Array where Element: Comparable {

    public func kSmallest(_ k: Int) -> Element {
        precondition(1 <= k && k <= count, "k must be in the range 1...count")

        var a = self // A mutable copy.
        var low = startIndex
        var high = endIndex

        while high - low > 1 {

            // Choose random pivot element:
            let pivotElement = a[low + Int(arc4random_uniform(UInt32(high - low)))]

            // Partition elements such that:
            //   a[i] <  pivotElement    for low <= i < pivotIndex,
            //   a[i] >= pivotElement    for pivotIndex <= i < high.
            var pivotIndex = low
            while a[pivotIndex] < pivotElement {
                pivotIndex += 1
            }
            for i in pivotIndex+1 ..< high {
                if a[i] < pivotElement {
                    swap(&a[pivotIndex], &a[i])
                    pivotIndex += 1
                }
            }

            if k <= pivotIndex {
                // k-smallest element is in the first partition:
                high = pivotIndex
            } else if k == pivotIndex + 1 {
                // Pivot element is the k-smallest:
                return pivotElement
            } else {
                // k-smallest element is in the second partition
                low = pivotIndex
                if a[low] == pivotElement {
                    low += 1
                }
            }
        }

        // Only single candidate left:
        return a[low]
    }

    public func kLargest(_ k: Int) -> Element {
        return kSmallest(count + 1 - k)
    }
}

Examples:

let a = [ 9, 7, 6, 3, 4, 2, 5, 1, 8 ]
for k in 1 ... a.count {
    print(a.kSmallest(k))
}
// 1 2 3 4 5 6 7 8 9

let b = [ "b", "a", "c", "h" ]
print(b.kLargest(2))
// "c"

Feedback on all aspects of the code is welcome, such as (but not limited to):

Possible improvements (speed, clarity, swiftyness, ...).
Naming. In particular: what would be a better name for kSmallest(_ k: Int)
in consideration of the
Swift API Design Guidelines?
The check if a[low] == pivotElement looks artificial, but without that
an infinite loop can occur, e.g. for an array with all elements equal.
Is there a better solution?

Remark: To make this code compile with Swift 4 (or later), just replace the line

swap(&a[pivotIndex], &a[i])

with

a.swapAt(pivotIndex, i)


texts: Nesting versus GOTO: which is better to avoid?

texts:
In Java they're not really known as GOTO statements and are rather referred to as Branching Statements, but I find that the former term is a bit more indicative of what they actually do.

Regardless, I've been designing some code recently which has me in a bind.  On the one hand, I've been taught to avoid avid use of such statements because they make code both non-linear and more difficult to follow.  They of course have excellent uses, and I'm not one of those puritans who says that they should be discarded at any cost.

On the other hand, there's also a common tenet that says I ought to avoid deep nesting of conditions and loops if it's possible and reasonable to do so.

So here's my conundrum.  I'm hoping someone can guide me and give me some solid reasoning and best practices advice, because apparently my brain can't handle the conflicting signals.

Several times through my code, I have a for() loop which is something like the following (where lines is a List<String> and values is a Map<String, String>):

for(String line : lines) {

    if(line.charAt(0) == '#') {
        LOGGER.debug("Skipping commented line in file.");
        continue;
    }

    line = line.trim().toLowerCase();
    String[] pair = line.split("=");

    if(pair.length != 2) {
        LOGGER.error("Skipping malformed line in file: " + line);
        continue;
    }

    pair[0] = pair[0].trim();
    pair[1] = pair[1].trim();

    if(values.containsKey(pair[0])) {
        LOGGER.debug("Value is already assigned.");
        continue;
    }

    values.put(pair[0], pair[1]);

    //...and so on with still more processing
}

The reason I gave a little bit more in this code snippet than is strictly required to understand the use case is because I think the fact that the for loop isn't really "tight" and that it performs a lot of processing is relevant to the style choice.  To me, it makes the code feel somewhat sloppy and messy to have multiple areas scattered throughout it which bump the reader back to the beginning of the loop.  In other words, it feels a lot like the good old GOTO that everyone loves to hate on.

So my other design option is to write it with the following style:

for(String line : lines) {
    if(!line.charAt(0) == '#') {
        line = line.trim().toLowerCase();
        String[] pair = line.split("=");
        if(pair.length == 2) {
            pair[0] = pair[0].trim();
            pair[1] = pair[1].trim();
            if(!values.containsKey(pair[0])) {
                values.put(pair[0], pair[1]);
                //...and so on with still more processing
            }
            else {
                LOGGER.debug("Value is already assigned.");
            }
        }
        else {
            LOGGER.error("Skipping malformed line in file: " + line);
        }
    }
    else {
        LOGGER.debug("Skipping commented line in file.");
    }
}

Both of these techniques/styles makes my eye twitch spastically for various reasons, and I keep rewriting my code to fit whichever rationalization wins out in the current moment.  I also think that if you definitively choose one as "The Style" to always go with, it's trivial to extend the above code snippets to the point where it makes more sense to go with the other.

Does anyone have a more definitive statement of when to use one style over the other?  Or even just some good reasoning to apply to a situation to make sure you are following the best rule and coding practice?  Any general tips, tricks, and advice for dealing with these sorts of situations?


texts: Searching for bad Minecraft questions on Gaming.SE

texts:
To preface this post a little bit, I'll explain a little bit of the "backstory" here. The Stack Exchange site, Gaming.SE, also known as Arqade, often has a large influx of bad questions about the popular video game, Minecraft. Many of these questions are either easy to find on a search engine, horribly unclear, have been asked before, are treating Arqade like a forum, or are asking for things like account support, which only the company that produces the game can provide. A few examples might include:

  what is the best biome to spawn in minecraft
  Can't Log In To Minecraft Account After 1.9
  No .Minecraft folder at school
  What I need to make TNT?
  How to Spawn Herobrine without Mods?

The query essentially searches in a manner like this:

It looks for questions with tags that are like %minecraft% or %minecraft-%%.
It checks to see if it has a score below -1.
It checks to make sure that the post hasn't already been deleted.
It checks to see if it's either been closed, or not closed.

I'd like to know the following things:

Is there a way to make this shorter and less repetitive?
Are there any redundant checks that aren't needed?
Are there any checks that could cause problems?
Anything else?

Here's the code, and the query link:

SELECT
    Id AS [Post Link]
  , OwnerUserId AS [User Link]
  , Score
FROM Posts WHERE
  DeletionDate IS NULL
  AND Score <= -1
  AND (
    Tags LIKE '%minecraft-%%'
    OR Tags LIKE '%minecraft%'
  )
  AND (
    ClosedDate IS NULL
    OR ClosedDate IS NOT NULL
  );

SELECT
  COUNT(*)
FROM Posts WHERE
  DeletionDate IS NULL
  AND Score <= -1
  AND (
    Tags LIKE '%minecraft-%%'
    OR Tags LIKE '%minecraft%'
  )
  AND (
    ClosedDate IS NULL
    OR ClosedDate IS NOT NULL
  );


texts:
Creating a simple object compare function for public system types in a class meaning only looking at the first level of a class no breaking into an object and comparing sub properties.

It performs very quickly however I am unsure about the extensibility of it for the future should criteria evolve

public static IEnumerable<string> Compare<T1, T2>(this T1 Object1, T2 Object2) where T1 : IComparer
{
    if (Object2 == null)
        throw new NullReferenceException("Parameter object not instantiated");

    Type TypeOfObject1 = typeof(T1);
    PropertyInfo[] Object1Properties = TypeOfObject1.GetProperties(BindingFlags.Public | BindingFlags.Instance);

    Type TypeOfObject2 = typeof(T2);
    PropertyInfo[] Object2Properties = TypeOfObject2.GetProperties(BindingFlags.Public | BindingFlags.Instance);

    if (Object1Properties.Count() == 0 || Object2Properties.Count() == 0)
        throw new NullReferenceException("No public properties found");

    var DifferencesFound = Object1Properties
        .Join(Object2Properties,
                Object1Property => Object1Property.Name,
                Object2Property => Object2Property.Name,
                (Object1Property, Object2Property) => new { Object1Property = Object1Property, Object2Property = Object2Property })

        .Where(x => ((Type.GetTypeCode(x.Object1Property.PropertyType) != TypeCode.Object
                        && Type.GetTypeCode(x.Object2Property.PropertyType) != TypeCode.Object
                    )
                    && !x.Object1Property.GetValue(Object1).Equals(x.Object2Property.GetValue(Object2)))
                )
        .Select(x => x.Object1Property.GetCustomAttributes(typeof(DisplayNameAttribute), false).SingleOrDefault() as string ?? x.Object1Property.Name)
        .AsEnumerable();

    return DifferencesFound;
}

Note: Reads DisplayName attribute if it is not found then uses name


texts: Counting points on a given irregular grid that are inside or outside a circle

texts:
Given some points that are represented as (X, Y) coordinates, my task is to count the points that are inside a circle, on the circle, and outside the circle.

The input is given in the following way: first, the number n is provided. Then, n numbers are inputted that represent the SetX. Afterwards, the numbers for m and SetY are given in the same way.

The points that I should consider are Cartesian product of SetX and SetY. For example, given SetX: {0, 3, 4} and SetY: {1, 4}, the points would be: (0, 1), (0, 4), (3, 1), (3, 4), (4, 1), (4, 4).

The maximum element of SetX is guaranteed to be the same as the maximum element in SetY, and must be an even number. The center of previously mentioned circle is determined as (max/2, max/2), with radius max/2.

Additional limitations: n and m are at least 1 and no more than 107. Elements of SetX and SetY are no greater than 107.

My solution is as follows:

#include <iostream>

inline double distance_squared(const unsigned int&, const unsigned int&);

unsigned int center = 0;

int main()
{
    unsigned int n, m, i, inside = 0, on_circut = 0, outside = 0, tmp, distance_sqr;

    std::cin >> n;

    unsigned int set_X[n];
    for(i = 0; i < n; ++i){
        std::cin >> set_X[i]; // reading the set of Xs
        if(set_X[i] > center) center = set_X[i]; // finding maximum
    }
    center = center >> 1; //div by 2

    std::cin >> m;

    while(m--){ // reading elements of Y one by one
        std::cin >> tmp; //
        for(i = 0; i < n; ++i){ // for each pair of tmp (being Y coordinate) and a number from Xs (being coord. X)...
            distance_sqr = distance_squared(set_X[i], tmp); // find the distance^2 and compare it to radius^2
            if(distance_sqr == center*center){ ++on_circut; continue; }
            if(distance_sqr > center*center) ++outside;
            else ++inside;
        }
    }

    std::cout << inside << ' ' << on_circut << ' ' << outside;

    return 0;

}

inline double distance_squared(const unsigned int& x, const unsigned int& y){
    return (x - center)*(x - center) + (y - center)*(y - center);
}

The solution provides correct output, but it appears to be too slow. The online judge gives the "time limit exceeded" on majority of the tests. Please do note that in the original code I do not use std::cin and std::cout, but custom functions that I omitted, since I am certain that they are significantly faster than iostream functions, plus, they are quite long compared to the rest of the program.

Is there any other way I could optimise the code? Is my approach generally bad in terms of time complexity?


texts: Should I split class or keep it all in one?

texts:
Currently, in my project I have one class that is dedicated to the all of the queries for the IBM i and converts it into usable models for my .NET code. There is already 12 methods in this class and there will be many, many more to come. This is for a tool that pulls data from our IBM i and pushes it to our internet database server.

Should I split this class up? Should I make it a partial class and put the code across multiple files? Should I do multiple classes?

Just wondering what the best practice is on something like that.

Currently this is the framework I have in place

class IbmIDatabase
{
    private DateTime ZERO_DATE = new DateTime(1900, 1, 1, 0, 0, 0);
    private string _connString = String.Empty;
    SystemCodeRepository scr = new SystemCodeRepository();

    /// <summary>
    /// Initializes a new instance of the <see cref="IbmIDatabase"/> class.
    /// </summary>
    public IbmIDatabase()
    {
    }

    #region System Codes
    /// <summary>
    /// Gets all system codes.
    /// </summary>
    /// <returns></returns>
    public IEnumerable<SystemCode> GetAllSystemCodes()
    {
    }
    #endregion System Codes

    #region Citations
    /// <summary>
    /// Gets all citations.
    /// </summary>
    /// <returns></returns>
    public IEnumerable<ParkingTicket> GetAllCitations()
    {
    }
    #endregion Citations

    #region Queue
    /// <summary>
    /// Gets the queued records.
    /// </summary>
    /// <returns></returns>
    public IEnumerable<QueuedRecord> GetQueuedRecords()
    {
    }

    /// <summary>
    /// Marks the queue as processed.
    /// </summary>
    /// <param name="id">The id.</param>
    public void MarkQueueAsProcessed(int id)
    {
    #endregion Queue

    #region Utility Bill Customer
    /// <summary>
    /// Gets the utility bill customer.
    /// </summary>
    /// <param name="id">The customer id.</param>
    /// <returns></returns>
    public Customer GetUtilityBillCustomer(int id)
    {
    }

    /// <summary>
    /// Gets the utility bill customer.
    /// </summary>
    /// <returns></returns>
    public IQueryable<Customer> GetUtilityBillCustomer()
    {
    }
    #endregion

    #region Utility Bill Details
    /// <summary>
    /// Gets the customer history.
    /// </summary>
    /// <param name="id">CustomerId</param>
    /// <returns></returns>
    public IQueryable<BillHistory> GetCustomerHistory(int id)
    {
    }

    /// <summary>
    /// Gets the customer history.
    /// </summary>
    /// <returns></returns>
    public IQueryable<BillHistory> GetCustomerHistory()
    {
    }
    #endregion

    #region Utility Bill Payment Details
    /// <summary>
    /// Gets the customer payment history.
    /// </summary>
    /// <param name="id">The id.</param>
    /// <returns></returns>
    public IQueryable<BillPaymentHistory> GetCustomerPaymentHistory(int id)
    {
    }

    /// <summary>
    /// Gets the customer payment history.
    /// </summary>
    /// <returns></returns>
    public IQueryable<BillPaymentHistory> GetCustomerPaymentHistory()
    {
    }
    #endregion

    #region Utility Bill Summary
    /// <summary>
    /// Gets the customer summary.
    /// </summary>
    /// <param name="id">CustomerId</param>
    /// <returns></returns>
    public IEnumerable<BillSummary> GetCustomerSummary(int id)
    {
    }

    /// <summary>
    /// Gets the customer summary.
    /// </summary>
    /// <returns></returns>
    public IQueryable<BillSummary> GetCustomerSummary()
    {
    }
    #endregion
}

Within each method can be quite a few lines of code (up to many 100 or so?). I left one of the longest ones so far in the sample code.


texts:
Write a program reads two integers representing a month and day and prints the season for that month and day. Assume that months are specified as an integer between 1 and 12 (1 for January, 2 for February, and so on) and that the day of the month is a number between 1 and 31.
If the date falls between 12/16 and 3/15, you should print "Winter". If the date falls between 3/16 and 6/15, you should print "Spring". If the date falls between 6/16 and 9/15, you should print "Summer". And if the date falls between 9/16 and 12/15, you should print "Fall".

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

    int month = scan.nextInt();
    int day = scan.nextInt();

    if((month == 12 && day >= 16 && day <= 31) || (month == 1 && day >=1 && day <= 31) || (month == 2 && day >= 1 && day <= 28) || (month == 3 && day >=1 && day <=15))
    {
        System.out.println("Winter");
    }
    else if((month == 3 && day >= 16 && day <= 31) || (month == 4 && day >=1 && day <= 30) || (month == 5 && day >= 1 && day <= 31) || (month == 6 && day >=1 && day <=15))
    {
        System.out.println("Spring");
    }
    else if((month == 6 && day >= 16 && day <= 30) || (month == 7 && day >=1 && day <= 31) || (month == 8 && day >= 1 && day <= 31) || (month == 9 && day >=1 && day <=15))
    {
        System.out.println("Summer");
    }
    else if((month == 9 && day >= 16 && day <= 30) || (month == 10 && day >=1 && day <= 31) || (month == 11 && day >= 1 && day <= 30) || (month == 12 && day >=1 && day <=15))
    {
        System.out.println("Fall");
    }
}

}


texts:
Are there any optimization suggestions?

<?php
# Pascal's Triangle using Recursion.
$rows_to_generate = 15; // Define number of rows you want to generate.
$storage = array();
function get_elem($row,$pos)    // generate element having number of row and number of position.
{
    global $storage;

    if(isset($storage[$row][$pos]))
    {
        return $storage[$row][$pos];
    }

    if($row==1 and $pos==1) // for first row.
    {
        return 1;
    }
    else if($pos==0)    // for left most row element that doesn't exist.
    {
        return 0;
    }
    else if($pos>$row)  // for right most row element that doesn't exist.
    {
        return 0;
    }
    return get_elem($row-1,$pos-1)+get_elem($row-1,$pos);   // Recursion
}
?>

<?php
for($i=1;$i<=$rows_to_generate;$i++)
{
    for($j=1;$j<=$i;$j++)
    {
        echo $storage[$i][$j]=get_elem($i,$j);  // generate
        if($i!=$j)
        {
            echo ' ';
        }
    }
    echo '
';
}
?>


texts:
I read the documentation part of Eloquent, especially scopes:

  Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with scope:

And so, with using Slim, I'm retrieving an object of Employee Type and pass it to my view. I only know two ways to do this.

$app->get('/user/create', $guest(), function() use ($app) {

$employee_type = $app->option->where('type', '=', 'employee_type')->get();
$employee_type = $app->option->employeeType()->get();

$app->render('user/create.twig', [
    'employee_type' => $employee_type
]);
})->name('user.create');

First one is the normal way we do, we retrieve the objects of Option class and get the values of employee_type.

$employee_type = $app->option->where('type', '=', 'employee_type')->get();

Second is, using scopes:

$employee_type = $app->option->employeeType()->get();

And on my Option class, I have this chunk of code:

public function scopeEmployeeType($query) {
    $query->where('type', '=', 'employee_type');
}

It just does the same. Just like in the description above I gave on using scopes, it allows to easily re-use query logic in your models. Now the problem is, which is better to use? I'm starting a project and encountered this part, and I'm kind of worried I might overuse scoping.


texts:
I am trying to ad nested to some flat data, which is nested.

Basically this code works the following way:

"taglevel":1 tags should be key of the array
"taglevel":2 or higher tags should be nested within an array and not be duplicated in its' array
If no "taglevel":1 exists add, it to a generic "NoLevel_1" array

The code is still clunky and I feel there is a much cleaner way to achieve this.

import json
generic = []
result = []

for i in json_data:
    if any(d['taglevel'] == 1 for d in i['tag']):
        tag_data = {}
        tag_child = []
        for tag in i['tag']:
            if tag['taglevel'] == 1:
                tag_data['name'] = tag['name']
                tag_data['taglevel'] = 1
            else:
                tag_child.append(tag)
        filtered = {tuple((k, d[k]) for k in sorted(d) if k in ['name']): d for d in tag_child}
        tag_data['tag_child'] = list(filtered.values())
        if any(d['name'] == tag_data['name']  for d in result):
            for t in result:
                if t['name'] == tag_data['name']:
                    t['tag_child'] = t['tag_child'] + tag_child
                filtered = {tuple((k, d[k]) for k in sorted(d) if k in ['name']): d for d in t['tag_child']}
            t['tag_child'] = list(filtered.values())
        else:
            result.append(tag_data)
    else:
        for tag in i['tag']:
            generic.append(tag)
tag_data = {}
tag_data['name'] = 'NoLevel1'
tag_data['taglevel'] = 1
tag_data['tag_child'] = generic
result.append(tag_data)
print json.dumps(result, indent=4, sort_keys=True)

The data:

json_data = [{
        "title": "Random",
        "tag": [
            {
                "name": "Fruit",
                "taglevel": 1
            },
            {
                "name": "Apple",
                "taglevel": 2
            }
        ]
    },
    {
        "title": "Other",
        "tag": [
            {
                "name": "Fruit",
                "taglevel": 1
            },
            {
                "name": "Apple",
                "taglevel": 2
            }
        ]
    },
    {
        "title": "Words",
        "tag": [
            {
                "name": "Food",
                "taglevel": 2
            }
        ]
    },
        {
        "title": "That",
        "tag": [
            {
                "name": "Food",
                "taglevel": 2
            },
            {
                "name": "Apple",
                "taglevel": 2
            }
        ]
    }
]

Desired result

[
    {
        "name": "Fruit",
        "tag_child": [
            {
                "name": "Apple",
                "taglevel": 2
            }
        ],
        "taglevel": 1
    },
    {
        "name": "NoLevel_1",
        "tag_child": [
            {
                "name": "Food",
                "taglevel": 2
            },
            {
                "name": "Apple",
                "taglevel": 2
            }
        ],
        "taglevel": 1
    }
]


texts:
Here's Problem 5 - Smallest multiple

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

How can I improve this code? How to make it faster? Is there a better/faster solution?

#include <iostream>

bool calculate(int number, int n) {
    if (n == 0) {
        return true;
    }
    return (number % n != 0) ? false : calculate(number,n-1);
}

int main() {
    int number = 20;
    int result = number;
    while (!calculate(result, number)) {
        result += number;
    }
    std::cout << result << '\n';
}


texts:
After coming across Douglas Crockford's views on class-free OOP, and doing away with new and this in Javascript I tried defining an object with its own variable and function, and returning it in JSON, as shown below:

var newObj = function (name, lang){
    var obj = {
            "name":name,
            "greeter":greeter
    };
    return obj;
};

function greeter (lang){
        switch (lang){
                case "en":return "hi";
                case "es":return "hola";
                default: return "hello";
        }
}

//and finally, use the object
var name = "john", lang = "es";
var obj = newObj(name, lang);

console.log(obj.name);
console.log(obj.greeter(lang));

I know this code works in NodeJS, but I wonder if it is actually a good idea to do it this way. More specifically, are there any implications/consequences to returning functions within a javascript object that I should be aware of?


texts:
I need to refactor this class having in mind that the logic inside the call methods is not so short and it require spring dependencies to work, the base class I have is:

@Service
public class ConcurrentService{

    @Autowired
    private Service1 service1;

    @Autowired
    private Service2 service2;

    public executeParallelProcess(){
        List<Callable> callableList = new ArrayList<Callable>();
        callableList.add(new Callable<String>(){

            @Override
            public String call() throws Exception {
                return service1.run();
            }
        });

        callableList.add(new Callable<String>(){

            @Override
            public String call() throws Exception {
                return service2.run();
            }
        });

        final List<Future<?>> futureList = new ArrayList<Future<?>>();

        for(Callable callable : callableList){
            futureList.add(taskExecutor.submit(callable));
        }

        final List<Object> resultObjects = new ArrayList<Object>();

        for(int i = 0 ; i < futureList.size() ; i++){
            try {
                resultObjects.add(futureList.get(i).get());
            }catch (InterruptedException ite){
                serviceExceptionThrown = true;
            }
        }

        if(serviceExceptionThrown)
            throw new ServiceException(ConstantUtil.THREAD_EXCEPTION);

        return resultObjects;

    }
}

After notice that I can not use Mockito to test the logic within the call method I use this way.

@Service
public class ConcurrentService{

    @Autowired
    private Service1 service1;

    @Autowired
    private Service2 service2;

    public executeParallelProcess(){

        Future<String> future1 = this.process1();
        Future<String> future2 = this.process2();

        final List<Future<?>> futureList = new ArrayList<Future<?>>();
        futureList.add(cosmosRequestCall);
        futureList.add(vendavoRequestCall);

        final List<Object> resultObjects = new ArrayList<Object>();

        for(int i = 0 ; i < futureList.size() ; i++){
            try {
                resultObjects.add(futureList.get(i).get());
            }catch (InterruptedException ite){
                serviceExceptionThrown = true;
            }
        }

        if(serviceExceptionThrown)
            throw new ServiceException(ConstantUtil.THREAD_EXCEPTION);

        return resultObjects;

    }

    @Async
    public Future<String> process1(){
        return new AsyncResult<String>(service1.run());
    }

    @Async
    public Future<String> process2(){
        return new AsyncResult<String>(service2.run());
    }
}

I need your advise and help here, to know if there is better way to implement this kind of logic, have in mind that could be more than 2 async processes , I am looking for a generic way to run several callable statements in a way that makes me easy the unit testing of the internal process and not having big blocks of code within the call() method.

The question is more about how to design an executor class that can run several callable in different scenarios for different situation not just tied to an specific implementation. I use anonymous classes, inner classes to create. Just imagine something that I can built to run more than the two thread process that are in the example.


texts: Having a string representing items in a cart, elaborate taxes and totals. Interview task in Python

texts:
A couple of weeks ago I had to do a coding challenge for a job interview. I did the challenge using Python, the code was working and I got the job. But I would like to know how (if possible) I can improve/refactor the code I've written.
The reviewer told my future employer there were too many if statements and that I could have written better code.
I guess this is an example of too many if statements:
def get_row_tax_percentage(product_name: str):
    exempt = is_exempt(product_name)
    imported = is_imported(product_name)
    if exempt and imported:
        return Decimal(".05")
    elif exempt and not imported:
        return Decimal("0")
    elif imported:
        return Decimal(".15")
    else:
        return Decimal(".1")

Link to the task description: https://github.com/xpeppers/sales-taxes-problem
Link to my solution: https://github.com/soulpaul/sales-taxes-solution
I think this could be a chance to learn something new. I don't need you guys to write code for me, but please point me to the right direction.
Thanks to anyone who is going to spend some time on this.


texts:
This URL shortener is just for my own use and it runs on my local machine. I created this for fun and I doubt if I would ever use it in production. Is my script any good?

shortener.php

<?php
require_once 'lib/db.php';

function random_string($length, $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
    $chars_length = strlen($charset) - 1;
    $str = '';

    for ($i = 0; $i < $length; ++$i) {
        $str .= $charset[random_int(0, $chars_length)];
    }

    return $str;
}

$url = $error = '';

if (isset($_GET['id'])) {
    $id = trim($_GET['id']);

    $stmt = $pdo->prepare('SELECT url FROM url WHERE id = ?');
    $stmt->execute([$id]);
    $url = $stmt->fetchColumn();

    header('Location: ' . ($url ?: "http://{$_SERVER['HTTP_HOST']}{$_SERVER['SCRIPT_NAME']}"));
    exit;
}
else {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $url = $_POST['url'];

        if (filter_var($url, FILTER_VALIDATE_URL) !== FALSE) {
            do {
                $id = random_string(5);

                $stmt = $pdo->prepare('SELECT COUNT(*) FROM url WHERE id = ?');
                $stmt->execute([$id]);
                $count = $stmt->fetchColumn();
            }
            while ($count > 0);

            $stmt = $pdo->prepare('INSERT INTO url (id, url) VALUES (?, ?)');
            $stmt->execute([$id, $url]);

            header("Location: http://{$_SERVER['HTTP_HOST']}{$_SERVER['SCRIPT_NAME']}");
            exit;
        }
        else {
            $error = 'Not a valid URL';
        }
    }

    $last_id = $pdo->query('SELECT id FROM url ORDER BY created DESC LIMIT 1')->fetchColumn();
}
?><!DOCTYPE html>

    <meta charset="utf-8">
    <title>Extremely Simple Short URL Generator</title>

    <form method="post">
        <input type="text" name="url" placeholder="URL here" value="<?= htmlspecialchars($url) ?>">
        <button type="submit">Submit</button>
    </form>
    <?php if ($last_id): ?>
<a href="<?= "{$_SERVER['SCRIPT_NAME']}?", http_build_query(['id' => $last_id]) ?>">Latest Link
<?php endif ?>
    <?php if ($error): ?>
<?= $error ?>
<?php endif ?>

I'm aware that separating the view from the script is better, but for a simple app like this, I don't think it's necessary.

db.php

<?php
$pdo = new PDO(
    'mysql:host=host;dbname=dbname;charset=utf8mb4',
    'username',
    'password',
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => FALSE,
    ]
);

Any improvement is welcome.


texts: Refactoring based on OPEN CLOSE PRINCIPLE- C#

texts:
I have some code to write Error Logs to different places like Console/SignalR Messages/Text File.

The code is as follows:-

public class Logger
    {
    public void WriteToLog(string message, LogType logType)
    {
        switch (logType)
        {
            case LogType.Console:
                Console.WriteLine(message);
                break;

            case LogType.SignalR:
                // Code to send message to SignalR Hub
                break;

            case LogType.File:
                // Code to write in .txt file
                break;
        }
    }
}

Where my LogType is a simple Enum as below:-

public enum LogType
{
    Console,
    SignalR,
    File
}

But, when I think of Open-Close Principle, I am not getting optimal solution for it.

Edit:

I need to refactor my code as per open close principle. I need to optimize it, so that I don't need to Modify WriteToLog method once any LogType gets added.


texts:
I wrote an adaptive color thresholding function in Python (because OpenCV's cv2.adaptiveThreshold didn't fit my needs) and it is way too slow. I've made it as efficient as I can, but it still takes almost 500 ms on a 1280x720 image. I would greatly appreciate any suggestions that will make this function more efficient!

Here's what the function does:

It uses a cross-shape of one-pixel thickness as the structuring element. For each pixel in the image, it computes the average values of ksize adjacent pixels in four directions independently (i.e. the average of ksize pixels in the same row to the left, in the same column above, in the same row to the right, and in the same column below). I end with four average values, one for each direction. A pixel only meets the threshold criterion if it is brighter than either both the left AND right averages or both the top AND bottom averages (plus some constant C).

I compute those averages incrementally for all pixels at the same time using numpy.roll(), but I still need to do this ksize times. The ksize will usually be 20-50.

Here is the code, the relevant part is really just what happens inside the for-loop:

def bilateral_adaptive_threshold(img, ksize=20, C=0, mode='floor', true_value=255, false_value=0):

    mask = np.full(img.shape, false_value, dtype=np.int16)

    left_thresh = np.zeros_like(img, dtype=np.float32) #Store the right-side average of each pixel here
    right_thresh = np.zeros_like(img, dtype=np.float32) #Store the left-side average of each pixel here
    up_thresh = np.zeros_like(img, dtype=np.float32) #Store the top-side average of each pixel here
    down_thresh = np.zeros_like(img, dtype=np.float32) #Store the bottom-side average of each pixel here

    for i in range(1, ksize+1):
        roll_left = np.roll(img, -i, axis=1)
        roll_right = np.roll(img, i, axis=1)
        roll_up = np.roll(img, -i, axis=0)
        roll_down = np.roll(img, i, axis=0)

        roll_left[:,-i:] = 0
        roll_right[:,:i] = 0
        roll_up[-i:,:] = 0
        roll_down[:i,:] = 0

        left_thresh += roll_right
        right_thresh += roll_left
        up_thresh += roll_down
        down_thresh += roll_up

    left_thresh /= ksize
    right_thresh /= ksize
    up_thresh /= ksize
    down_thresh /= ksize

    if mode == 'floor':
        mask[((img > left_thresh+C) & (img > right_thresh+C)) | ((img > up_thresh+C) & (img > down_thresh+C))] = true_value
    elif mode == 'ceil':
        mask[((img < left_thresh-C) & (img < right_thresh-C)) | ((img < up_thresh-C) & (img < down_thresh-C))] = true_value
    else: raise ValueError("Unexpected mode value. Expected value is 'floor' or 'ceil'.")

    return mask


texts: Predicting random numbers based on past output

texts:
I've been working on a program to predict random numbers based on previous digits. However, I only get access to numbers from 0-53 inclusive, and one only comes every 30 seconds or so, therefore gathering hundreds or thousands of sequential data points is nigh impossible. I also don't know the algorithm being used, although right now I am assuming it is the Mersenne Twister.

With all that being said, here is the code that I am using:

import random
from multiprocessing import Process, Pool
import time
start = time.time()

data = [5, 49, 9, 2, 8]
datalength = len(data)

def actual():
    for i in range(9999999999):
        l1 = []
        random.seed(i)
        append = l1.append

        for i2 in range(datalength):
            x = random.randrange(0, 54)

            try:
                if data[x] == i2:
                    append(x)
            except IndexError:
                break

def next_100(x):
    l1 = []
    random.seed(x)
    for i in range(datalength):
        x = random.randrange(0, 54)
    for i in range(100):
        l1.append(random.randrange(0, 54))
    return l1

with Pool(processes=3) as pool:
    result = pool.apply_async(actual).get()

z = next_100(result)
print('The next 100 should be: {0}'.format(z))
print('It took {0} seconds'.format(round(time.time()-start)))

I have 2 questions:

Is there a better algorithm than I am currently using? (that works with my limited knowledge)
If not, how else can I optimize this? Right now, I can't really guess more than 100 million seeds in a reasonable amount of time. Seed 100 million takes ~23 minutes, and 1 billion should take about 230 minutes, which is way more time than I have.


texts:
I need to further simplify this solution to auto-format a text-box field intended only for the user to enter their college Grade Point Average (GPA). Here is my code:

<label for="collegeGPA">GPA:</label>
<input type="text" name="collegeGPA" id="collegeGPA" maxlength="4" style="width:45px;" onpaste="return false;" autocomplete="off" >

<script type="text/javascript">

//<!-- When executed this script [BELOW] auto-formats a Grade Point Average (GPA) field given the element ID [BEGIN] -->

function formatGPA(gPAElementID) {

    var rE = /\D/g; // remove any characters that are not numbers
    var originalGPA = document.getElementById(gPAElementID);
    var originalGPAVal = originalGPA.value;
    var gPAVal = originalGPA.value.replace(rE,"");
    var gPAValFirstCharacter = gPAVal.charAt(0);

if  ( ( ( parseFloat(originalGPAVal) ) > 4 ) && ( ( parseFloat(originalGPAVal) ) < 5 ) )

        {
            originalGPA.value = "4.00";
        }

else
        {

        if  ( ( gPAVal >= 0 ) &&  ( gPAValFirstCharacter < 5 ) )
                {

                        gPALen = gPAVal.length;

                        if  ( gPALen > 1 )
                                {
                                    gPAa=gPAVal.slice(0,1);
                                    gPAb=gPAVal.slice(1);
                                    originalGPA.value = gPAa + "." + gPAb;
                                }
                    else if ( gPALen == 1 )
                                {
                                    originalGPA.value = gPAVal + ".";
                                }
                        else
                                {
                                    originalGPA.value = gPAVal;
                                };

                }

            else
                {
                    originalGPA.value = "";
                };

        };

};

//<!-- When executed this script [ABOVE] auto-formats a Grade Point Average (GPA) field given the element ID [END] -->

document.getElementById('collegeGPA').onblur = function (e) { formatGPA(this.id); };
document.getElementById('collegeGPA').onfocus = function (e) { formatGPA(this.id); };
document.getElementById('collegeGPA').onkeypress = function (e) { formatGPA(this.id); };
document.getElementById('collegeGPA').oninput = function (e) { formatGPA(this.id);  };
document.getElementById('collegeGPA').onchange = function (e) { formatGPA(this.id); };

</script>

...and here is my JSFiddle: http://jsfiddle.net/JamesAndersonJr/kxaBJ/1/ I'm looking for a simpler way to format the GPA input dynamically (i.e. as the user types it in). The format should be:

1st Character: any digit 0-4

2nd Character: Always a Period (should also be auto-inserted after user types a valid first digit)

3rd Character: any digit

4th Character: any digit