texts:
Below is a simple class with two methods: the first calls open() to read in a file. The second calls the first method and does error handling.

There is also a corresponding test class that tests the first methods returns data as expected and the other methods test the error handling of potential exceptions thrown by open.

Firstly, I would like to know if these tests are written in the appropriate manner using python3, mocking and patching as I am new to the language and especially to testing.

I also have a query to why mocking an exception to be thrown cannot be handled like the rest of the tests (see last test method)

fileMethods.py

# -*- coding: utf-8 -*-

def readconfig(myfile):
    try:
        filecontent = readfile(myfile)
        #   manipulation of filecontent
    except FileNotFoundError:
        filecontent = "FileNotFoundError"
    except PermissionError:
        filecontent = "PermissionError"
    return filecontent

def readfile(myfile):
    with open(myfile, 'r') as file:
        filecontent = file.read()
    file.close()
    return filecontent

fileMethods_test.py

# -*- coding: utf-8 -*-

import io
import unittest
import unittest.mock as mock
import packageName.fileMethods

class TestIO(unittest.TestCase):

    def test_readfile_returns_string(self):
        mock_file_content = io.StringIO('Content in file')
        with mock.patch('packageName.fileMethods.open', return_value=mock_file_content, create=True):
            result = packageName.fileMethods.readfile('file_to_readin')
        self.assertEqual('Content in file', result)

    def test_readconfig_returns_content(self):
        with mock.patch('packageName.fileMethods.readfile', return_value="string", create=True):
            result = packageName.fileMethods.readconfig('file_to_readin')
        self.assertEqual('string', result)

    def test_readconfig_handles_FileNotFoundError(self):
        with mock.patch('packageName.fileMethods.readfile', side_effect=FileNotFoundError, create=True):
            result = packageName.fileMethods.readconfig('file_to_readin')
        self.assertEqual('FileNotFoundError', result)

    def test_readconfig_handles_PermissionError(self):
        with mock.patch('packageName.fileMethods.readfile', side_effect=PermissionError, create=True):
            result = packageName.fileMethods.readconfig('file_to_readin')
        self.assertEqual('PermissionError', result)

    # Does not work
    def test_readconfig_throws_OSError(self):
        with mock.patch('packageName.fileMethods.readfile', side_effect=OSError, create=True):
            self.assertRaises(OSError, packageName.fileMethods.readconfig('file_to_readin'))


texts: Cleaning Netflix-style recommendation engine datasets

texts:
I am working on a portfolio project that deals with creating a Netflix-style recommendation engine for movies. This code is currently ran locally but I will need to upload it into Jupyter Notebooks and implement it with Amazon SageMaker. The .tsv files are imported from IMDb Datasets.
The code below is working code created by myself. Is there any room for improvement from an efficiency/cleanliness aspect?
import pandas as pd
import numpy as np

basics = pd.read_table('basics.tsv')
origin = pd.read_table('akas.tsv')
ratings = pd.read_table('ratings.tsv')

#setting 'basics' columns
basics.drop(basics.columns[[3,4,6,7]], axis=1, inplace=True)
basics.columns = ['tconst','type','title','year','genre']

#removing all non-movies from index
cond1 = basics['type'].isin(['movie','tvMovie'])

#setting new 'basics' variable
basics2 = basics[cond1]

#setting 'origin' columns
origin.drop(origin.columns[[1,2,5,6,7]], axis = 1, inplace = True)
origin.columns = ['tconst','region','language']

#removing non-english movies from index
cond2 = origin['region'].isin(['US','GB'])
cond3 = origin['language'] == 'en'

#setting new 'origin' variable
origin2 = origin[cond2 | cond3]

#setting 'ratings' columns
ratings.columns = ['tconst','rating','votecount']

#converting strings to integers
ratings.rating = pd.to_numeric(ratings.rating, errors='coerce').astype(np.int64)
ratings.votecount = pd.to_numeric(ratings.votecount, errors='coerce').astype(np.int64)

#setting new 'ratings' variable
ratings2 = ratings[(ratings['rating'] >= 5) & (ratings['votecount'] >= 50)]

#finalizing movie recommendation list
rcmd = basics2.merge(origin2,on='tconst').merge(ratings2,on='tconst')
rcmd.drop_duplicates(subset = 'tconst', keep ="first", inplace = True)
print(rcmd)

Thanks in advance.


texts:
I wrote this code to find opposites of words (i.e., words backwards). Input is a list of words. If this list contains a word + its opposite, then it should form a pair. The output should be a list of tuples (pairs).
The output should:

contain every pair of words only once - it should contain either ('reed', 'deer') or ('deer', 'reed'), but not both.
not contain palindromes (words which are opposite to themselves) - e.g. 'refer'

def find_opposites(lst):
    if lst == [] or len(lst) == 1:
        return []
    else:
        opposites = [] # contains all words backwards (except palindromes)
        result = []
        for word in lst:
            if word != word[::-1]: # avoid palindromes
                opposites.append(word[::-1])

        for word in opposites:
            if word in lst:
            # if word in both opposites list and original list,
            # then it should form a pair with its opposite

                tup = (word[::-1], word) # create tuple
                if tup[::-1] not in result: # append tuple only if its opposite in not already in result
                    result.append(tup)

        return result

I have tried to substitute the list opposites with a dictionary as I know lists are slower to process, but it still takes a very long time.
Please let me know if you have any ideas on how to make it run faster, as it takes ages when I run on my corpora which contains over 11.000 words. Thanks a lot :)


texts: Parse sequence of characters detecting formatting categories

texts:
I am a beginner coder and SonarLint tells me code is too complex. I tried recursion, iterators, slicing but had not luck making this code any simpler.
The code will parse the input string to detect the following categories:

bold
italic
normal

depending on whether the characters are enclosed in 0-2 asterisks.
Sorry for the short description luckily, Iterniam inferred correctly. And side note nested **Bold *and* italic** are not supported by the code. I will read more on Iterniam's answer thank you for that!
Maybe a philosophical question at last, even though cyclomatic complexity in my code is higher the regex answer, the proposed solution is still much harder to understand (if it were not for the comments), debug and has worse performance. So is it the better code or should I just ignore cyclomatic complexity hints in the future?
txt = "A **A** is *italic* **bold** but some are *a* *b* **B**"

def fun(text=None):
    if text:
        bold_splits = text.split('**')
        for i, s in enumerate(bold_splits):
            if i % 2:
                print('BOLD:', s )
            else:
               italic_splits = s.split('*')
               for m, n in enumerate(italic_splits):
                   if m % 2:
                       print('ITALIC:', n )
                   else:
                       if n != '':
                           print('NORMAL:', n )


texts:
I have written an algorithm to do consecutive word match in a dataset

The input is a dataset (list of textlines) and I want to scan that and return repeated word(s) in the dataset along with some metadata like the strings (lines) they matched at.

I am having hard time to wrap my mind around a better approach to hand the consecutive words match. What I have so far is:

hashtable datastructure
I compute the permutations of each sentence's words. So complexity is n+ (n*avg words count). e.g: abc def gg ww will produce the following permutations

-- abc def
-- abc def gg
-- abc def gg ww
-- def gg
-- def gg ww
-- gg ww
I store every possible word combination from each sentence in a dictionary with value of 1
if a word combination exists in the dictionary, I increase the value by 1
using stringBuilder to avoid string immutability
I refine my dictionary at the end to remove any items that has value of 1

I am curios if:
1) this can be improved
2) are there any other datastructures/algo I can use to do the consecutive word matching on a text blob

It is C# now, but we are considering python or Go as well.

public Dictionary<string, List<string>> ConsecutiveMatches { get; set; }

public void Load(List<string> dataset)
{
    for (int i = 0; i < dataset.Count; i++)
    {
        var sentence = dataset[i];
        var words = sentence.Split(" ", StringSplitOptions.RemoveEmptyEntries);

        BuildConsecutiveMatches(words, sentence);
    }

    RefineConsecutiveMatches();
}

private void BuildConsecutiveMatches(string[] words, string sentence)
{
    BuildConsecutiveMatchesRecursive(words, 0, sentence);
}

private void BuildConsecutiveMatchesRecursive(string[] words, int index, string sentence)
{
    if (index >= words.Length - 1)
    {
        return;
    }

    var builder = new StringBuilder(words[index]);
    builder.Append(' ');

    for (int i = index + 1; i < words.Length; i++)
    {
        builder.Append(words[i]);
        var permutation = builder.ToString();
        if (ConsecutiveMatches.TryGetValue(permutation, out var matches))
        {
            ConsecutiveMatches[permutation].Add(sentence);
        }
        else
        {
            ConsecutiveMatches.Add(permutation, new List<string> { sentence });
        }
        builder.Append(' ');
    }

    BuildConsecutiveMatchesRecursive(words, ++index, sentence);
}

private void RefineConsecutiveMatches()
{
    ConsecutiveMatches = ConsecutiveMatches.Where(pair => pair.Value.Count >= 2)
                            .ToDictionary(pair => pair.Key,
                                        pair => pair.Value);
}


texts:
I wrote up a script a while back to let me play around with fractals. The idea was to have direct access to the script that creates the fractal. None of that close, edit, then run hassle; just edit then run.

renderscript.py contains the GUI:

import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfile

class View(tk.Frame):
    count = 0
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        tk.Button(self, text="open", command=self.open).pack(fill=tk.X)
        tk.Button(self, text="save", command=self.save).pack(fill=tk.X)
        tk.Button(self, text="run program", command=self.draw).pack(fill=tk.X)
        self.txt = tk.Text(self, height=30)
        scr = tk.Scrollbar(self)
        scr.config(command=self.txt.yview)
        self.txt.config(yscrollcommand=scr.set)
        scr.pack(side="right", fill="y", expand=False)
        self.txt.pack(side="left", fill="both", expand=True)
        self.pack()
    def draw(self, size=500):
        exec(str(self.txt.get(1.0, tk.END)))
        self.pixels = [[(0, 0, 0) for y in range(size)] for x in range(size)]
        self.pixels = render(self.pixels)
        window = tk.Toplevel(self)
        window.resizable(0,0)
        canvas = tk.Canvas(window, width=size, height=size, bg='white')
        canvas.pack()
        img = tk.PhotoImage(width=size, height=size)
        canvas.create_image((size/2, size/2), image=img, state="normal")
        for y in range(size):
            for x in range(size):
                img.put(self.rgbtohex(self.pixels[x][y]), (x,y))
        window.mainloop()
    def rgbtohex(self, rgb):
        return ("#" + "{:02X}" * 3).format(*rgb)
    def open(self):
        self.txt.delete(1.0, tk.END)
        self.txt.insert(tk.END, open(askopenfilename()).read())
    def save(self):
        f = asksaveasfile(mode='w', defaultextension=".py")
        if f is None:
            return
        text2save = str(self.txt.get(1.0, tk.END))
        f.write(text2save)
        f.close()

if __name__ == "__main__":
    root = tk.Tk()
    root.resizable(0,0)
    main = View(root)
    root.mainloop()

fractal.py contains example fractal routines:

class Fractal:
    def mandelbrot(self, x, y, scale, center=(2.2, 1.5)):
        n = lambda c: self.iterate_mandelbrot(c)
        return self.calcolor(x, y, scale, center, n)

    def julia(self, x, y, scale, center=(1.5, 1.5)):
        n = lambda c: self.iterate_mandelbrot(complex(0.3, 0.6), c)
        return self.calcolor(x, y, scale, center, n)

    def calcolor(self, x, y, scale, center, nf):
        c = complex(x * scale - center[0], y * scale - center[1])
        n = nf(c)
        if n is None:
            v = 1
        else:
            v = n/100.0
        return v

    def iterate_mandelbrot(self, c, z = 0):
        for n in range(256):
            z = z*z +c
            if abs(z) > 2.0:
                return n
        return None

    def griderator(self, w, h):
        for x in range(w):
            for y in range(h):
                yield x, y

    def render(self, pixels):
        scale = 1.0/(len(pixels[0])/3)
        for x, y in self.griderator(len(pixels), len(pixels[0])):
            i = self.mandelbrot(x, y, scale) * 256
            r, g, b = int(i % 16 * 16), int(i % 8 * 32), int(i % 4 * 63)
            pixels[x][y] = (r, g, b)
        return pixels

global render
render = Fractal().render

The script does block while rendering the script. Try replacing mandelbrot with julia. I am looking for feedback on style and usability.


texts:
I have a class with three similar methods. I can't consider which a pattern to use better for refactoring: template method, strategy or something else? I don't know. Can you help me?
Update: This code is a little exercise to be a better programmer. I'm going to add some algorithms, but it's not a production code. I would write good not smelled code for myself. I would have a beautiful code from this, if it's possible.
The main goal of the code : is creating a graph, breadth-first search and breadth-first traversing in graph. I've used a Cormen &al. algorithms from "Introduction to Algorithms" book. The method named BreadthFirstSearch is search. The method named CleanVertex changes color of vertex after search from black to white again. The last method named Path is for traversing the hole graph. All vertexes are traversed and their order are saved in a variable and return.

public class Graph
{

    public bool BreadthFirstSearch(int value)
    {
        if (StartingPoint == null)
        {
            return false;
        }

        var queue = new Queue<Vertex>();
        queue.Enqueue(StartingPoint);
        while (queue.Count != 0)
        {
            var vertex = queue.Dequeue();
            if (vertex.Index == value)
            {
                CleanVertex();
                return true;
            }
            vertex.Color = Color.Black;
            for (int i = 0; i < vertex.Neighbours.Count; i++)
            {
                var vertexNeighbour = vertex.Neighbours[i];
                if (vertexNeighbour.Color == Color.White)
                {
                    vertexNeighbour.Color = Color.Grey;
                    queue.Enqueue(vertexNeighbour);
                }
            }
        }
        CleanVertex();
        return false;
    }

    private void CleanVertex()
    {
        if (StartingPoint == null)
        {
            return;
        }

        StartingPoint.Color = Color.White;
        var queue = new Queue<Vertex>();
        queue.Enqueue(StartingPoint);
        while (queue.Count != 0)
        {
            var vertex = queue.Dequeue();
            for (int i = 0; i < vertex.Neighbours.Count; i++)
            {
                var vertexNeighbour = vertex.Neighbours[i];
                if (vertexNeighbour.Color != Color.White)
                {
                    vertexNeighbour.Color = Color.White;
                    queue.Enqueue(vertexNeighbour);
                }
            }
        }
    }

    public string Path()
    {
        if (StartingPoint == null)
        {
            return string.Empty;
        }

        var queue = new Queue<Vertex>();
        queue.Enqueue(StartingPoint);
        var path = new StringBuilder();
        while (queue.Count != 0)
        {
            var vertex = queue.Dequeue();
            path.Append($"{vertex.Index} ");
            vertex.Color = Color.Black;
            for (int i = 0; i < vertex.Neighbours.Count; i++)
            {
                var vertexNeighbour = vertex.Neighbours[i];
                if (vertexNeighbour.Color == Color.White)
                {
                    vertexNeighbour.Color = Color.Grey;
                    queue.Enqueue(vertexNeighbour);
                }
            }
        }

        return path.ToString().Trim();
    }
}


texts: The Blacklist: Blocking Malicious domains using Bash

texts:
I've made this script to automate blocking some deviant hosts on my router, and was curious if there's anything much else that can be done to make it quicker and more efficient.
Presently I'm restricted to using packages available on the Entware repository and the latest Busybox/ash shell environment. So, for example, I can't use commands like sort -S 25% --parallel=4 -u adblock.sources (though awk/gawk is faster and more memory efficient anyway).
update_the_blacklist.sh
curl -GOs https://raw.githubusercontent.com/T145/packages/master/net/adblock/files/adblock.sources

for key in $(jq -r 'keys[]' adblock.sources); do
        case $key in
        gaming | osid_basic )
                # Ignore these lists
                ;;
        * )
                url=$(jq -r ".$key.url" adblock.sources)
                rule=$(jq -r ".$key.rule" adblock.sources)

                case $url in
                *.tar.gz )
                        curl -s $url | \
                        tar -xOzf - | \
                        gawk "$rule" | \
                        sed "s/\r//g" | \
                        sed 's/^/0.0.0.0 /' >> the_blacklist.temp.txt
                        ;;
                * )
                        curl -s $url | \
                        gawk "$rule" | \
                        sed "s/\r//g" | \
                        sed 's/^/0.0.0.0 /' >> the_blacklist.temp.txt
                esac

                unset url
                unset rule
        esac
done

# Filter duplicate hosts
gawk '!a[$0]++' the_blacklist.temp.txt > the_blacklist.txt

rm the_blacklist.temp.txt
rm adblock.sources


texts: Optimize ineffiecient Jquery - UX list to grid view

texts:
I am fairly new to jQuery and I am making a new search results page. In this snippet I am switching from a grid to list view and vice versa. Can anyone suggest a cleaner method of performing this change? I did try using a variable to minimize all my (this) calls but I couldn't get them to work. Any help would be much appreciated.

JS

    $('.btn.grid').click(function() {
      if (!$(this).hasClass("active")) {
        $(this).addClass("active");
        $('.results-wrapper .grid_12').removeClass("grid_12").addClass("grid_3");
        $('.wrapper .results').addClass("grid-view-active");
        if ($(".btn.list").hasClass("active")) {
          $(".btn.list").removeClass("active");
          $('.wrapper .results').removeClass("list-view-active");
        }
      }
    });
    $('.btn.list').click(function() {
      if (!$(this).hasClass("active")) {
        $(this).addClass("active");
        $('.results-wrapper .grid_3').removeClass("grid_3").addClass("grid_12");
        $('.wrapper .results').addClass("list-view-active");
        if ($(".btn.grid").hasClass("active")) {
          $(".btn.grid").removeClass("active");
          $('.wrapper .results').removeClass("grid-view-active");
        }
      }
    });

HTML

grid
list

Title

Title

Title

Title

Title

Title

Title

Title

Title

Title

CSS

.btn {
  background: #ccc;
  cursor: pointer;
  display: inline-block;
  height: 35px;
  width: 35px;
}
.btn.active {
  background: red;
}
li {
  float: left;
  height: 200px;
  width: 200px;
}
li img {
  max-width: 100%;
  max-height: 100%;
}
.grid_3 {
  width: 25%;
}
.grid_12 {
  width: 100%;
}


texts: Vectorizing a polar coordinate conversion loop in a fingerprint-matching process

texts:
I am working on a fingerprint matching technique and it takes a lot of computation time to obtain the result. I am trying to implement the matching process given in A Minutia Matching Algorithm in Fingerprint Verification. I would like to know if there is any method available to reduce the for loop for this code:

[Tdrow,Tdcol]=size(Td);
[Idrow,Idcol]=size(Id);
matchingscore=zeros(Tdrow,Idrow);
rv = bsxfun(@minus,Td(:,3),permute(Id(:,3),[2 1]));
%convert each minutiae point to polar coordinates with respect to the
%reference minutiae in each case
for i=1:Tdrow
    for j=1:Idrow
        Tdp=zeros(Tdrow,Tdcol);
        Idp=zeros(Idrow,Idcol);
        tref=Td(i,:);
        iref=Id(j,:);
        Tdp(:,1)=sqrt((Td(:,1)-tref(1)).^2 + (Td(:,2)-tref(2)).^2);
        Tdp(:,2)=mod(atan2(tref(1)-Td(:,1),Td(:,2)-tref(2)) * 180/pi,360);
        Tdp(:,3)=mod(Td(:,3)-tref(3),360);
        Tdp(:,4)=Td(:,4);
        Idp(:,1)=sqrt((Id(:,1)-iref(1)).^2 + (Id(:,2)-iref(2)).^2);
        Idp(:,2)=mod((atan2(iref(1)-Id(:,1),Id(:,2)-iref(2)) * 180/pi) + rv(i,j),360);
        Idp(:,3)=mod(Id(:,3)-iref(3),360);
        Idp(:,4)=Id(:,4);
        Tdp1 {i,j}= Tdp(:,:);
        Idp1 {i,j}= Idp(:,:);
    end
end

Here, the variable Td is the fingerprint template to be compared and Id is the input fingerprint template. Both Td and Id have four columns, i.e. 1st and 2nd column provide x and y coordinate respectively, 3rd column is the angle and 4th column is the type of minutiae. Tdp and Idp are calculated using the equation provided in the attachment provided in the link.

Can this code be vectorized? I understand that the indexes have hardly been used. But without changing the index i cannot continue to the further steps. It would be very helpful is anyone could provide me with any suggestions.

The data values are available on Google Drive. These has both the input data and output data.


texts: The Blacklist -- Follow-Up 2: Electric Boogaloo

texts:
One of my main goals regarding this script has been to figure out a way to use the "adblock.sources" file available on its main repository and not my fork. That version has some syntax issues with its JSON, preventing it from being directly piped into jq.
After some research, I came across the jq -n -f {file} command that successfully read in the ill-formatted JSON! I have a couple questions on this feature and one on the sed command.

Is jq -n -f {file} being used properly?
Can the two jq commands be blended into one command?
Can the two sed parameters be blended into one parameter?

#!/bin/sh

set -eu

sources=$(mktemp)
trap 'rm "$sources"' EXIT

curl -s -o "$sources" https://raw.githubusercontent.com/openwrt/packages/master/net/adblock/files/adblock.sources

jq -n -f "$sources" | jq -r 'keys[] as $k | [$k, .[$k].url, .[$k].rule] | @tsv' |
while IFS=$'\t' read key url rule; do
    case $key in
        gaming | oisd_basic | yoyo )
        # Ignore these sources:
        # "gaming" blocks virtually all gaming servers
        # "oisd_basic" is included in "oisd_full"
        # "yoyo" is included in "stevenblack"
        ;;
        * )
            curl -s "$url" |
                case $url in
                    *.tar.gz) tar -xOzf - ;;
                    *) cat ;;
                esac | gawk --sandbox -- "$rule"
        ;;
    esac
done | sed -e 's/\r//g' -e 's/^/0.0.0.0 /' | sort -u >| the_blacklist.txt
# use sort over gawk to merge sort multiple temp files instead of using up limited memory


texts: Abort thread on new request, but complete only last request

texts:
The situation is that a certain asynchronous operation is called multiple times, which is basically to consolidate results. But I want to abort every time a new request comes in, which means that only the last call will run completely. Does this solution look reasonable?

I have tried replicating the process in a test program, where the for loop represents 'x' number of calls generated for consolidation. But because we only need to run calculation once, we can safely run it on the last call.

I am creating a new thread each time, and cancelling the previous ones if there are any. This seems to work, but is there a better way or can this be improved?

static void Main(string[] args)
{
    var listCancellationTokens = new List<CancellationTokenSource>();

    for (var i = 1; i <= 5; i++)
    {
        var cancelSource = new CancellationTokenSource();
        listCancellationTokens.ForEach(c => c.Cancel());

        CreateThread(cancelSource);

        listCancellationTokens.Add(cancelSource);
    }
}

private static void CreateThread(CancellationTokenSource cancellationTokenSource)
{
    new Thread(() =>
    {
        try
        {
            ConsolidateResults(cancellationTokenSource.Token);
        }
        catch
        {
            ;
        }
    }).Start();

}

private static void ConsolidateResults(CancellationToken cancelToken)
{
    UpdateValues();
    if (cancelToken.IsCancellationRequested)
    {
        return;
    }
    TurnOffEvents();
    if (cancelToken.IsCancellationRequested)
    {
        return;
    }
    GetMarginPercentage();

    if (cancelToken.IsCancellationRequested)
    {
        return;
    }
    TurnOnEvents();
}

//This is how it is done at the moment
private void Commit(bool adjustDiscount = false)
{
    lock (_updateRunnerLock)
    {
        _updateRunnerRemainingCycles = 40;
        if (_updateRunner == null)
        {
            _updateRunner = new Thread(UpdateRunner);
            _updateRunner.Start();
        }
    }
}

private void UpdateRunner()
{
    while (_updateRunnerRemainingCycles > 0)
    {
        Thread.Sleep(500);
        _updateRunnerRemainingCycles--;
    }
    lock (this)
    {
        if (_updateRunner != null)
        {
            _updateRunner = null;
            ConsolidateResults();
        }
    }
}


texts:
I am writing a piece of code in c# that mimics the behaviour of following SQL function STR in the following case:

declare @number numeric(19,15)    = 219.37345462345234235
SELECT str(@number,9,9) -- 219.37345

declare @number numeric(19,15)    = 19.37345462345234235
SELECT str(@number,9,9) -- 19.373455

Following is an input output table for this scenario:

I have implemented the following function in C# which accepts a double variable and returns a string which is equal to the result returned by the SQL function STR(@number,9,9).

public static string GetCustomStringQuantity(double quantity)
    {
        string customQuantity ;
        int length = (int) Math.Log10(Math.Abs(quantity))+1;
        if (length>9)
            return "*********";
        quantity = Math.Round(quantity, 8 - length,MidpointRounding.AwayFromZero);
        customQuantity = quantity.ToString();
        customQuantity= (quantity %1==0)?(customQuantity+".").PadRight(9, '0'):customQuantity.PadRight(9, '0');

        if (customQuantity.Length > 9)
            customQuantity = customQuantity.Substring(0, 9);
        else if (customQuantity.Length == 9 && customQuantity.EndsWith("."))
            customQuantity = customQuantity.Substring(0, 8);

        return customQuantity;
    }

How can I make this function better? Or is there a better way to implement this functionality?


texts: C++ class "overload" using variadic templates and wrapped function pointers

texts:
I'm using C++11 and I have the following problem (pseudo C++):

template<typename T, R1 (*F1)(Args1...)>
class one_size_fits_them_all {};

template<typename T, typename U, typename V, R1 (*F1)(Args1...), R2 (*F2)(Args1...)>
class one_size_fits_them_all {};

template<typename T, typename U, R1 (*F1)(Args1...), R2 (*F2)(Args2...), R3 (*F3)(Args3...)>
class one_size_fits_them_all {};

So what I want to do is to overload the class by its template parameters and pass in function pointers.
I came up with this fully compile- and runnable solution:

// compile with `g++ -std=c++11 test.cpp`
#include <iostream>

#define CALLABLE(FUNCTION) callable<decltype(FUNCTION), FUNCTION>

template<typename Signature, Signature & S>
struct callable;

template<typename Return,
         typename ... Args, Return (&Function)(Args ...)>
struct callable<Return(Args ...), Function> {
  Return operator()(Args ... args)
  {
    std::cerr << __PRETTY_FUNCTION__ << std::endl;
    return Function(args ...);
  }
};

template<typename ... Arguments>
class one_size_fits_them_all;

// A generic template
template<typename T, typename U, typename V,
         typename F1, typename F2, typename F3>
class one_size_fits_them_all<T, U, V, F1, F2, F3>
{
  public:
    one_size_fits_them_all(void)
    {
      std::cerr << "generic one_size_fits_them_all" << std::endl
                << __PRETTY_FUNCTION__ << std::endl << std::endl;
      F1()();
      F2()();
      F3()();
      std::cerr << std::endl;
    }
};

// A specialized template
template<typename T, typename Callable>
class one_size_fits_them_all<T, int, int, void, void, Callable>
{
  public:
    one_size_fits_them_all(void)
    {
      std::cerr << "specialized one_size_fits_them_all" << std::endl
                << __PRETTY_FUNCTION__ << std::endl << std::endl;
      Callable()();
      std::cerr << std::endl;
    }
};

void f1(void)
{
  std::cerr << __PRETTY_FUNCTION__ << std::endl << std::endl;
}

void f2(void)
{
  std::cerr << __PRETTY_FUNCTION__ << std::endl << std::endl;
}

void f3(void)
{
  std::cerr << __PRETTY_FUNCTION__ << std::endl << std::endl;
}

int main(int argc, char ** argv)
{
  // generic template
  auto generic = one_size_fits_them_all<
    int, int, int, CALLABLE(f1), CALLABLE(f2), CALLABLE(f3)>();

  // specialized template
  auto specialized_int = one_size_fits_them_all<
    int, int, int, void, void, CALLABLE(f1)>();

  // specialized template
  auto specialized_double = one_size_fits_them_all<
    double, int, int, void, void, CALLABLE(f3)>();

  return 0;
}

My questions are:

Is this a good solution?
Can it be improved?


texts: Generating a list of powers in Elm up to some limit

texts:
I'm looking to generate a list of powers in Elm, up to a certain limit. I've written the following tests:

        [ test "works for negative limit" <| \_ -> equal (powers 2 -5) (Ok [])
        , test "works for 2 up to 63" <| \_ -> equal (powers 2 63) (Ok [1, 2, 4, 8, 16, 32])
        , test "works for 2 up to 64" <| \_ -> equal (powers 2 63) (Ok [1, 2, 4, 8, 16, 32])
        , test "works for 3 up to 81" <| \_ -> equal (powers 3 81) (Ok [1, 3, 9, 27, 81])
        , test "rejects negative bases" <| \_ -> equal (powers -2 63) (Err "negative base")
        ]

I have a solution that I'm not happy with because it seems pretty long. Now I know that when doing these kinds of things in the functional style, we generally use tail recursion (which is no problem). But as I am building up the list from small numbers to large numbers (e.g., 1 2 4 8 16 32 ...) I could keep appending to the accumulated list, but this is much slower than using prepend (::). So... I decided to prepend and then reverse at the very end:

powers base limit =
  if base < 0 then
    Err "negative base"
  else
    let
      helper base exponent limit soFar =
        let next = base ^ exponent in
          if next > limit then
            Ok soFar
          else
            helper base (exponent + 1) limit (next :: soFar)
    in
      case helper base 0 limit [] of
        Ok powerList -> Ok <| List.reverse powerList
        Err message -> Err message

This passes all the tests but I am wondering two things:

Is consing (::) and then reversing at the end the right way to do this or is there a better way?
Is there something amazing in Elm's List module that I missed that I should be using here?
At the very end, when I wanted to reverse, was it necessary to do that matching? It seems unnecessarily verbose because I had to pass through the whole Err part. Since I only wanted to reverse a list in the Ok case and leave the Err part unchanged, was there a better way to write this?


texts: Search object literal and return first key/value pair that matches regex

texts:
This does what I want:

function test(data){
    for(var key in data){
        if(/_is$/.test(key)){
          var obj = {}
          obj[key] = data[key];
          return obj;
        }
    }
}

test( {a: 'a', user_id_is: '1', b: 'b'} )
> Object {user_id_is: "1"}

But 8 lines of code for such a simple task looks inefficient. Is there a more concise way to achieve such a basic task in JavaScript, something like how Ruby does it?

data.detect {|item| item =~ /_is$/}


texts: Sorting numbers using Java Collections.sort()

texts:
Input is a file containing numbers in this format:

1.2 3 5.1 2 7 4 6
5 2 9.22 1 0.0 4 3

I am doing the sorting in the simplest way, using Collections.sort method. The running code is as follows:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class SortedNumbers {

    public static Double integerFromString(String str) {
        return Double.valueOf(str.substring(0, str.length()));
    }

    public static void main(String[] args) throws FileNotFoundException {
         String fileName = "";

        //scanner to read the file
        Scanner fileInput = null;

        List<String> temps = new LinkedList<String>();

        //first check if there is an input parameter
        if(args.length > 0) {
            fileName = args[0];
        }

        else {
            System.out.println("No file specified");
            System.exit(1);
        }

        //connect to the file
        FileReader file = new FileReader (fileName);
        fileInput = new Scanner(file);

        //start reading from the file, store all the lines in the list
        while(fileInput.hasNextLine()) {
            String num = fileInput.nextLine();
            temps.add(num);
        }

        //close the scanner
        fileInput.close();

        //convert the list into array of strings
        String[] str = temps.toArray(new String[0]);

        /**
         * for each string in str array, split it using space as the delimiter and store the splitted strings in an array,
         * for each string value in the array, convert it into Double and store it in a collection
         * Sort the collection, convert it into String
         */
        for(int i = 0; i < str.length; i++){
            List<Double> num = new LinkedList<Double>();
            String[] arr = str[i].split("\\s");
            for(int j = 0; j < arr.length; j++){
                Double currentNumber = integerFromString(arr[j]);
                num.add(currentNumber);
            }
            Collections.sort(num);
            String sortedNumbers = num.toString();
            int indexOfOpenBracket = sortedNumbers.indexOf("[");
            int indexOfLastBracket = sortedNumbers.lastIndexOf("]");
            System.out.println(sortedNumbers.substring(indexOfOpenBracket+1, indexOfLastBracket));
        }
    }
}

I am concerned about the performance, splitting the string and storing it in array, parsing each string from array into double and then adding in the list.  It seems like there could be an efficient way.

Are there any redundant steps in the code which I can avoid?


texts:
I'm not really sure if this is right, so it would be great to have it reviewed.

I'm creating an Android library and made a final class with completely static methods for getting internal resources (res, layout, etc.) since there are conflicts with the host application when using the R class for imported libraries. However, I'm not so sure if I'm in the right path, since I've always read that static classes are a code smell, despite being convinced by some StackOverflow answers. There's also an issue with unit tests since PowerMock cannot be run with some frameworks such as Espresso.

public final class ResourceUtils {

    private static final String TAG = ResourceUtils.class.getSimpleName();

    private ResourceUtils() {}

    /**
     *
Retrieves the id of a resource.

     *
Equivalent to R.[resourceType].[name]

     * @param context
     * @param name the name of the resource
     * @param resourceType the resourceType (see ResourceType enum)
     * @return id of the resource
     */
    public static int getResourceId(Context context, String name, ResourceType resourceType) {
        if (context == null || name == null) {
            return 0;
        }

        return context.getResources().getIdentifier(name, resourceType.toString(), context.getPackageName());
    }

    /**
     *
Retrieves the content of a raw resource file.

     * @param context
     * @param filename the name (excluding the file extension) of the raw file under res/raw
     * @return CharSequence representation of the content of the raw resource
     */
    public static CharSequence readRawResource(Context context, String filename) {
        if (context == null || filename == null) {
            return null;
        }

        int rawId = getResourceId(context, filename, ResourceType.RAW);
        if (rawId == 0) {
            return null;
        }

        Writer writer = new StringWriter();
        char[] buffer = new char[1024];

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(rawId)));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
            reader.close();
        } catch (IOException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }

        return writer.toString();
    }

    public enum ResourceType {
        COLOR("color"),
        DIMENSION("dimen"),
        DRAWABLE("drawable"),
        INTEGER("integer"),
        LAYOUT("layout"),
        RAW("raw"),
        STRING("string"),
        STYLE("style"),
        VIEW("id")
        ;

        private final String text;

        /**
         * @param text
         */
        private ResourceType(final String text) {
            this.text = text;
        }

        /* (non-Javadoc)
         * @see java.lang.Enum#toString()
         */
        @Override
        public String toString() {
            return text;
        }
    }
}

Here's a sample usage for getResourceId:

Actual:

public class SomeActivity {
    ...
        setContentView(ResourceUtils.getResourceId(this, "activity_some", ResourceUtils.ResourceType.LAYOUT));
    ...
}

R class usage equivalent:

public class SomeActivity {
    ...
        setContentView(R.layout.activity_some);
    ...
}

For readRawResource, let's say there's a raw resource named raw.txt, calling ResourceUtils.readRawResource will return the contents of the text file as a string.


texts: Drop-down list with 14 options of RSS feed dates

texts:
The goal of this code is to create drop-down menu where there are 14 options on the list. Those 14 options are the dates that an RSS feed were last updated. The URLs for the feed have the query &issue=2014/10/14, but the trick is that it's set so that if a date is entered when the feed wasn't updated, it returns the most recent one instead of an error.

This code finds today's date, goes back one day, builds the URL for the feed for that day, loads that feed and checks if the publication date matches the date in that URL (thereby confirming that the feed was updated that day), and if it's a valid day it builds the option value and adds it to the drop-down list. Then it does that again until there are 14 options.

It also checks whether a day is a weekend first, to skip all the weekend days because I know this feed won't be updated on weekends.

The problem is that if there are big gaps between valid dates, it takes too long to execute and I get a FastCGI timeout error. I'm not interested in lengthening the FastCGI timeout length. What I've done is set the time limit to 2 seconds, which is enough to go through about a month's worth of days and get as many valid days as there are in there.

I feel like this is a really sloppy way to do it but I can't come up with anything better. Hopefully someone with more experience has a better solution!

<?php
error_reporting(0);
$timer = set_time_limit(2);
echo ("<select id='select1' align=center width=10 onchange='javascript:location.href=this.value;'>");
echo ("<option>-- select past date --</option>");
$i=1;
$j=0;
$pickdate = date("m-d-Y"); //today's date
while ($j <= 13) {
    $pickdate = mktime(0, 0, 0, date("m")  , date("d")-$i, date("Y")); //subtract from today's date
    $new_pickdate = date('D. M. j, Y',$pickdate ); //put date in desired format for dropdown
    $postdate = date('Y/m/j',$pickdate); //put date in desired format for url
    $xml=("http://[IPremoved]/NewsLetter/postfeed?type=1&issue=".$postdate);
    $onchangeurl=("http://enews-archive.php?".$postdate);
    $dayofweek = date('N',$pickdate ); //pull day of week
    if ($dayofweek < 6) { //check for weekdays
        $xmlDoc = new DOMDocument(); //load xml to test if empty
        $xmlDoc->load($xml); //load xml to test if empty
        $channel=$xmlDoc->getElementsByTagName('channel')->item(0); //load xml to test if empty
        $pubdate = $channel->getElementsByTagName('PostDate')->item(0)->childNodes->item(0)->nodeValue; //load xml to test if empty
        $pubdatestamp = strtotime($pubdate);
        $checkdate = date('Y/m/j',$pubdatestamp); //put date in desired format to check
        if ($postdate == $checkdate)  //check if dates match
            {
                echo ('<option value='.$onchangeurl.'>'.$new_pickdate.'</option>'); //if weekday & xml not empty print it
            $j++; //add to counter if it's a valid date
        } //end match check
    } //end weekday check
    $i++; //increase subtraction from date
} //end while
echo ("</select>");
?>


texts: Making the controller clean and readable in (Ruby on Rails)

texts:
I have this rails controller which works fine but a lot of business logic is confined in the controller which I believe is not a good practice.
class MoviesController < ApplicationController
  before_action :set_movie, only: [ :edit, :update, :destroy ]
  rescue_from ActiveRecord::RecordNotFound, with: :render_404

  def index
    year = params[:year].split('-') unless params[:year].nil?
    starting_year = year[0] unless year.nil? || year.empty?
    ending_year = year[year.length - 1] unless year.nil? || year.empty?
    genre = params[:genre][0] unless params[:genre].nil?
    language = params[:language][0] unless params[:language].nil?
    quality = params[:quality][0] unless params[:quality].nil?
    rating = params[:rating_bound][0] unless params[:rating_bound].nil?
    order_by = params[:orders_filter][0] unless params[:orders_filter].nil?
    @movies = Movie.search_title(params[:title]).search_language(language).search_on_starting_year(starting_year).search_on_ending_year(ending_year).search_video_quality(quality).search_genre(
      genre
    ).search_rating(rating).order_on_filter(order_by).includes(:profile_photo)
  end

  def show
    @movie = Movie.includes(
      :profile_photo, :created_by, movie_roles: [:actor], feedback: [:user]
    ).left_outer_joins(:likes, :ratings).select(
      'movies.*, CAST(AVG(ratings.value) AS DECIMAL(10,1)) AS rating, count(likes.likeable_id) * 6 as total_likes'
    ).find params[:id]
    @reviews = @movie.feedback.select { |item| item.type == 'Review' }
    @comments = @movie.feedback.select { |item| item.type == 'Comment' }
    @directors = @movie.movie_roles.select { |role| role.role_played == 'director' }
    @actors = @movie.movie_roles.select { |role| role.role_played == 'actor' }
  end

  def new
    @movie = Movie.new
    @movie.build_profile_photo
  end

  def edit
  end

  def render_404
    render file: "#{Rails.root}/public/404", status: :not_found
  end

  # POST /movies
  # POST /movies.json
  def create
    parameters = movie_params
    @movie = Movie.new(parameters)
    @movie.created_by = current_user

    if @movie.save
      redirect_to @movie, notice: 'Movie was successfully created.'
    else
      render :new, notice: 'Not Saved!'
    end
 end

  def update
    respond_to do |format|
      if @movie.update(movie_params)
        format.html { redirect_to @movie, notice: 'Movie was successfully updated.' }
        format.json { render :show, status: :ok, location: @movie }
      else
        format.html { render :edit }
        format.json { render json: @movie.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @movie.destroy
    respond_to do |format|
      format.html { redirect_to movies_url, notice: 'Movie was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_movie
    @movie = Movie.find(params[:id])
  end

  # Only allow a list of trusted parameters through.
  def movie_params
    params.fetch(:movie, {}).permit(:name, :release_date, :video_quality, :synopsis, :genres, :language)
    params.fetch(:movie, {}).permit(:name, :release_date, :video_quality, :synopsis, :genres, :language, profile_photo_attributes: [:path])
  end
end

I need to shrink the controller size and make the code look much clear and readable!


texts: Enum usage to restrict class attribute values

texts:
I am using enums in python3 for the first time but unsure if I am using them correctly.

I want to restrict the 'allowed values' for a class attribute ArticleMetadata.article_type to those defined within an ArticleTypes Enum class.

Here's my code:

from enum import Enum

class ArticleMetadata(object):

    ArticleTypes = Enum('ArticleTypes', 'original modified', module=__name__)

    def is_in_enum(self, value, Enum):
        """Verify that a value is contained within a defined Enum object.

        Raises:
            ValueError: If the value is not contained within the defined Enum.
        """
        if value in Enum.__members__:
            return True
        else:
            raise ValueError("Value {0} not in Enum list.".format(value))

    def __init__(self, **kwargs):
        """Set class attributes."""

        self.article_type = (kwargs['article_type'] if 'article_type' in kwargs.keys()
                              and self.is_in_enum(kwargs['article_type'], self.ArticleTypes)
                              else None
                              )

Usage

> foo = ArticleMetadata(article_type='original')
> foo.article_type
'original'
> bar = ArticleMetadata(article_type='invalid')
*** ValueError: Value invalid not in Enum list.

This code works, but having to write an is_in_enum method seems clunky, and I would have thought that this functionality would be natively part of enums somehow??

Also, no errors are raised if I later run foo.article_type = 'invalid', which doesn't seem right!

Am I missing a common usage pattern?


texts: Molybdenum2019 challenge efficient implementation

texts:
I'm working on a solution that is correct but inefficient.
https://app.codility.com/programmers/task/leader_slice_inc/
This is my code :
public static void main(String[] args) {
    int[] A = { 2, 1, 3, 1, 2, 2, 3 };
    int[] B = null;
    int M = 5, K = 3;
    int array_lengh = A.length;
    Map<Integer, Integer> counter = null;
    Set<Integer> listaLideres = new LinkedHashSet<Integer>();

    // valor minimo =0 ; valor maximo = Longitud del array - k;
    // el lider sera aquel que ocurra mas de longitud/2

    for (int i = 0; i < array_lengh - K + 1; i++) {
        B = Arrays.copyOf(A, array_lengh);
        counter = new HashMap<Integer, Integer>();

        for (int j = i; j < i + K; j++) {
            B[j] = B[j] + 1;
        }

        for (int n = 0; n < array_lengh; n++) {
            int repeticones = counter.get(B[n]) == null ? 0 : counter.get(B[n]);
            counter.put(B[n], repeticones + 1);
        }

        int liderProvisional = 0;
        for (Map.Entry<Integer, Integer> valorRepeticion : counter.entrySet()) {
            liderProvisional = valorRepeticion.getValue();
            if (liderProvisional > array_lengh / 2) {
                listaLideres.add(valorRepeticion.getKey());
            }
        }
    }

    List<Integer> listaLideresOrdenada = new ArrayList<Integer>();
    listaLideresOrdenada.addAll(listaLideres);

    listaLideresOrdenada.sort(Comparator.naturalOrder());

    for (Integer integer : listaLideresOrdenada) {
        System.out.println(integer);
    }
}


texts: Human readable display of a list of things

texts:
Just for fun, I created this small function that prints an iterator in a String:

use std::fmt::{Display, Write};

fn enumerate<T: Display, I: IntoIterator<Item = T>>(it: I) -> String {
    let mut it = it.into_iter().peekable();
    let mut result = String::new();

    if let Some(first) = it.next() {
        write!(result, "{}", first).unwrap();
        if it.peek().is_some() {
            while let Some(item) = it.next() {
                match it.peek() {
                    Some(_) => write!(result, ", {}", item),
                    None => write!(result, " and {}", item),
                }.unwrap();
            }
        }
    }

    result
}

fn main() {
    assert_eq!(enumerate(Vec::<i32>::new()), "");
    assert_eq!(enumerate(vec![1]), "1");
    assert_eq!(enumerate(vec![1, 2]), "1 and 2");
    assert_eq!(enumerate(vec![1, 2, 3]), "1, 2 and 3");
    assert_eq!(enumerate(vec![1, 2, 3, 4]), "1, 2, 3 and 4");
}

But I am not really satisfied with it. It is not really readable, and I am switching between next and peek in nested blocks. I wonder if this is possible to write the function in a more functional manner?


texts: Custom Exceptions based off the Visual Studio snippet

texts:
I'm creating my own application exception types so I could catch them higher in the call stack and take specific action. I'm looking to get feedback on the latest exception I've written for two reasons:

I'm using the Exception snippet from Visual Studio 2013, and am wondering if it is any good and/or has potential problems;
The main parameter for this Exception type would be a string, and I'm wondering what to do with the parameters. Currently I'm following the built in ArgumentException constructor-signatures-wise, but I fear future users of my exception will fall into the same trap as me with ArgumentException: providing a single argument with the paramName, instead of a message.

PS. I've checked the source for ArgumentException and explicitly decided not to put in the extra work of saving the tenantName in a field + property analogously, because the calling code does not yet need it. (Though I'm happy to get feedback on that choice as well of course.)

Bottom line: anything to improve on this custom exception?

[Serializable]
public class TenantNotFoundException : Exception
{
    public TenantNotFoundException()
    { }

    public TenantNotFoundException(string message)
        : base(message)
    { }

    public TenantNotFoundException(string message, string tenantName)
        : base(string.Format("Tenant '{0}' not found. {1}", tenantName, message))
    { }

    public TenantNotFoundException(string message, Exception inner)
        : base(message, inner)
    { }

    public TenantNotFoundException(string message, string tenantName, Exception inner)
        : base(string.Format("Tenant '{0}' not found.", tenantName), inner)
    { }

    protected TenantNotFoundException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    { }
}

PS. I was almost tempted to write just a single constructor with a string parameter for tenant name, but then I wondered (a) if people would be confused and enter a message instead of a tenant name, and (b) why the snippet suggests all the other constructors. This is what prompted me to post this question.

For reference, this is what you start with as the Visual Studio snippet:

[Serializable]
public class MyException : Exception
{
    public MyException() { }
    public MyException(string message) : base(message) { }
    public MyException(string message, Exception inner) : base(message, inner) { }
    protected MyException(
      SerializationInfo info,
      StreamingContext context)
        : base(info, context) { }
}


texts: Simple program to insert values in a linked list

texts:
I tried to write a simple program using linked list where I just insert the value stored in every node and then through a function print the values.

This is the code:

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

typedef struct Node {
    int value;
    struct Node* link;
} Node;

void print_node(Node * );

int main() {

    Node* head = NULL;
    head=malloc(sizeof(Node));
    if (head==NULL) {
       return 0;
    }
    printf("Insert the number of nodes :\n");
    int N;
    scanf("%d",&N);
    int i;
    Node * Node_c=head;
    for (i=0;i<N;i++) {
        if (i<N-1) {
            int temp;
            printf("Insert value stored into the node %d:\n",i+1);
            scanf("%d",&temp);
            Node_c->value=temp;
            Node_c->link=malloc(sizeof(Node));
            Node_c=Node_c->link;
        } else if (i=N-1) {
            int temp;
            printf("Insert value stored into the node %d:\n",i+1);
            scanf("%d",&temp);
            Node_c->value=temp;
            Node_c->link=NULL;
        }
    }
    printf("\n");
    print_node(head);
    return 0 ;
}

void print_node(Node * head) {
    Node * Node_current = head;
    int i=1;
    while (Node_current != NULL) {
        printf("Value stored into node %d:  %d\n",i,Node_current->value);
        Node_current = Node_current->link;
        i++;
    }
}

The code runs just fine but I want to know if this part where I insert the values stored in each node can be done in an shorter way

Node * Node_c=head;
for(i=0;i<N;i++){
    if(i<N-1){
        int temp;
        printf("Insert value stored into the node %d:\n",i+1);
        scanf("%d",&temp);
        Node_c->value=temp;
        Node_c->link=malloc(sizeof(Node));
        Node_c=Node_c->link;
    } else if (i=N-1) {
        int temp;
        printf("Insert value stored into the node %d:\n",i+1);
        scanf("%d",&temp);
        Node_c->value=temp;
        Node_c->link=NULL;
    }
}


texts:
In order to avoid boilerplate code and make an extensible pool of actions for the same portion of code (a row of texts to edit), I've prepared this code.

var actions = {
    editName: function () {
        var curName = this.nameField.text();

        this.nameField.data('oldName', curName);
        this.nameField.html('<input class="updatedName" type="text" value="' + curName + '"/>');
        this.actionsField.append('Cancel');
        this.remove();
    },
    cancelEdit: function () {
        var oldName = this.nameField.data('oldName');

        this.nameField.html(oldName);
        this.actionsField.append('Edit');
        this.remove();
    }
};

$('.field').on('click', '.actions a[data-action]', function (ev) {
    ev.preventDefault();

    var link = $(this);
    var action = link.data('action');

    if (typeof actions[action] === 'function') {
        var fieldSelector = link.closest('.field');

        this.nameField = fieldSelector.find('.name');
        this.actionsField = fieldSelector.find('.actions');

        actions[action].call(this);
    }
});

    Name:
WiL

        Edit

The main goal is to define, only once, the selectors and use them in the functions. To accomplish this, the selectors are defined out of the function calls and later adding functions like save, copy, erase or whatever your imagination allows.

I have a few concerns, too:

In the early versions of the code, I used var for the nameField selector, but no functions in the actions object were able to see it (and therefore use it). Why does it work with this?
Performance implications of using this to define a variable (instead of var).
In this line:

var action = link.data('action');

I use link "naked", without a jQuery wrapper because I know that already is a jQuery object, but should I wrap it in $() again? Are there any performance issues of "double wrapping"?


texts:
I did a small countdown clock challenge in JavaScript. Please review it, thanks.

const timeControls = document.querySelector('.timer__controls');
const timeLeft = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
let interval;

function secondsToHourMinSec(seconds) {
  const date = new Date(0);
  date.setSeconds(seconds);
  return date.toISOString().substr(11, 8);
}

function advanceCurrentTime(seconds) {
  const date = new Date(0);
  date.setSeconds(Math.floor(Date.now() / 1000) + seconds);
  return date.toLocaleTimeString().substr(0, 7);
}

function displayRemainingTime(seconds) {
  timeLeft.textContent = secondsToHourMinSec(seconds);
}

function displayEndTime(seconds) {
  endTime.textContent = `Be back at ${advanceCurrentTime(seconds)}`;
}

function displayTime(seconds) {
  displayRemainingTime(seconds);
  displayEndTime(seconds);

  interval = setInterval(function() {
    seconds--;
    if (seconds < 0) {
      clearInterval(interval);
      return;
    }
    displayRemainingTime(seconds);
  }, 1000);
}

function startTimer(seconds) {
  clearInterval(interval);
  displayTime(seconds);
}

timeControls.addEventListener('click', e => {
  const button = e.target.closest('button');
  if (button)
    startTimer(parseInt(button.dataset.time));
});

document.customForm.addEventListener('submit', function(e) {
  e.preventDefault();
  const value = this.minutes.value;
  if (value.length !== 0)
    startTimer(parseInt(value) * 60);
  this.reset();
});
html {
  box-sizing: border-box;
  font-size: 10px;
  background: #8e24aa;
  background: linear-gradient(45deg, #42a5f5 0%, #478ed1 50%, #0d47a1 100%);
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 0;
  text-align: center;
  font-family: "Inconsolata", monospace;
}

.display__time-left {
  font-weight: 100;
  font-size: 20rem;
  margin: 0;
  color: white;
  text-shadow: 4px 4px 0 rgba(0, 0, 0, 0.05);
}

.timer {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.timer__controls {
  display: flex;
}

.timer__controls>* {
  flex: 1;
}

.timer__controls form {
  flex: 1;
  display: flex;
}

.timer__controls input {
  flex: 1;
  border: 0;
  padding: 2rem;
}

.timer__button {
  background: none;
  border: 0;
  cursor: pointer;
  color: white;
  font-size: 2rem;
  text-transform: uppercase;
  background: rgba(0, 0, 0, 0.1);
  border-bottom: 3px solid rgba(0, 0, 0, 0.2);
  border-right: 1px solid rgba(0, 0, 0, 0.2);
  padding: 1rem;
  font-family: "Inconsolata", monospace;
}

.timer__button:hover,
.timer__button:focus {
  background: rgba(0, 0, 0, 0.2);
  outline: 0;
}

.display {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.display__end-time {
  font-size: 4rem;
  color: white;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Countdown Timer</title>
  <link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="style.css">

      <button data-time="20" class="timer__button">20 Secs</button>
      <button data-time="300" class="timer__button">Work 5</button>
      <button data-time="900" class="timer__button">Quick 15</button>
      <button data-time="1200" class="timer__button">Snack 20</button>
      <button data-time="3600" class="timer__button">Lunch Break</button>
      <form name="customForm" id="custom">
        <input type="text" name="minutes" placeholder="Enter Minutes">
      </form>


texts: Email subscription queries for a PHP website

texts:
Is this code resistant against injection? I already used 'real-escape-string' but I don't know if this good enough. As you see I replaced my personal info. And the code does work. I'm building this site for a family member so it needs to be very protected against 'hackers'. Thank you in advance.

HTML:

<input type="text" name="email" id="email">

 Subscribe

 Unsubscribe

PHP:

$conn = new mysqli('#', '#', '#', '#');

if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
}

$email = $_POST['email'];

$sql = sprintf("SELECT * FROM ... WHERE email = '%s'", mysql_real_escape_string($email));

$result = $conn->query($sql);

    if ($result->num_rows > 0) {

        die ("Already subscribed");

    } else {

        $sql2 = sprintf("INSERT INTO ... (email) VALUES ('%s')", mysql_real_escape_string($email));
        $result2 = $conn->query($sql2);
        echo "You subscribed!";

    }


texts: Clean up PHP & MYSQL code (Picked up by Swift as blog reader iOS app)

texts:
New to PHP and was just wondering if any improvements can be made, maybe increase efficiency or just clean up code?

I know I'm using an old MYSQL maybe we can update it. Just want to make sure the connection can be as best to its ability. Also, if you can, can you explain on how to improve security?

The JSON gets picked up by Swift iOS app.

<?php

$dbhost = "website";
$dbuser = "user";
$dbpass = "password";
$dbname = "database";

$connection = mysql_connect($dbhost,$dbuser,$dbpass);

// Checking if connection can be established
if(!$connection){

    die("Connection Failed");

} else {

// Selecting Database
$dbconnect = mysql_select_db($dbname, $connection);

// Checking if it can connect to Database
if(!$dbconnect){

    die("Unable to connect to Database");

} else {

    $query = "SELECT * FROM blogs";
    $resultset = mysql_query($query, $connection);
    $records= array();

    // Loop and check all records and add to array
    while($r = mysql_fetch_assoc($resultset)) {

        $records[] = $r;
    }

    // Output data as JSON
    echo json_encode($records);
 }
}

?>


texts: Java Slick 2D Collision Detection Methodology

texts:
I have a collision detection for terrain setup (non-terrain is handled with a quadtree I implemented apart from this) and I was wondering how others have done it compared to mine and what I could learn from people's critiques here.

My map is stored in a 2D array of "GameSquare"s

public class GameSquare extends GameObject {
    private char tileLetter = 'W';
    private int row, col;
}
public boolean isPassable() {
    return tileLetter != 'W';
}

The row and col are the index in the 2D array.
The char corresponds to the graphic, my render checks the char and draws a Wall(W), Floor(O), or Door(X)
The Player
My player class gets track of the player in pixels. The speed and X,Y positions are all in exact pixels. I divide those measures by the width or height of the tile graphics I use and truncate it; in order to find the corresponding array cell that the player is in. In order to do collision detection I wrote a method that takes a cardinal direction, the players current collision box, and a distance which is usually their speed.
The cardinal direction is an enum that has methods for the adjX and adjY.
For example; East would return adjX() = 1 and adjY() = 0 whereas
SouthEast would return adjX() = 1 and adjY() = 1 <-- Positive because this is the movement in a 2D array.

The Collision Check

public int canMove(Direction dir, Rectangle collisionBox, int distance) {
    int goodToGo = 0;
    // Check each 'step' of our attempted movement from 1 - distance(ie speed)
    for(int i = 1; i <= distance; i++) {
        // Assemble suggested new position bounds to check, ie corners of suggested movement
        HashSet<Vector2f> cornerPoints = new HashSet<Vector2f>();
        cornerPoints.add( new Vector2f(collisionBox.getMinX()+dir.adjX()*i, collisionBox.getMinY()+dir.adjY()*i) );
        cornerPoints.add( new Vector2f(collisionBox.getMaxX()+dir.adjX()*i, collisionBox.getMinY()+dir.adjY()*i) );
        cornerPoints.add( new Vector2f(collisionBox.getMinX()+dir.adjX()*i, collisionBox.getMaxY()+dir.adjY()*i) );
        cornerPoints.add( new Vector2f(collisionBox.getMaxX()+dir.adjX()*i, collisionBox.getMaxY()+dir.adjY()*i) );

        // Check each corner of this step
        for( Vector2f point : cornerPoints ) {
            // Out of bounds check
            if( point.y < 0 || point.y > this.dungeonHeight*ratioRow ||
                    point.x < 0 || point.x > this.dungeonWidth*ratioCol ) {
                return goodToGo;
            }

            // Figure out what map square this point falls on
            int checkX = (int) (point.x / ratioCol);
            int checkY = (int) (point.y / ratioRow);

            // If that's a wall square... no go, we're done here, return the number of steps that
            // were OKed so far
            if( this.dungeon[checkY][checkX].getTileLetter('W') ) {
                return goodToGo;
            }
        }
        // If this step, i, didn't have any conflicts on any of the proposed new corners, then
        // increment our ongoing count of how many steps are OK to take
        goodToGo++;
    }
    return goodToGo;
}

I know blocks of code are kind of a bitch but any feedback or just shared attempts at 2D collision detection in Slick/Java are very appreciated.


texts: A binary search implementation for any datatype in C (continuation)

texts:
This is an indirect follow-up to this post.

I've tried to assimilate all that was instructed and here's my attempt at binary search.

binary_search.h

#ifndef _BINARY_SEARCH_H
#define _BINARY_SEARCH_H

/*
 * Summary:
 *  Performs binary search on the given sorted array using the given
 * comparator function. Returns the index of the matching array
 * element (< count), and -1 if the element is not found.
 *
 *  Parameters are independent of type and hence this function
 * can be used for arrays of all data-types, provided that the size
 * (i.e. in terms of bytes) is properly specified.
 *
 * CAUTION: It will not work on unsorted arrays.
 *
 * Parameters:
 *  1. *x    - the address of the element to find in the array
 *  2. *base - the address of the sorted array from whence we start searching.
 *  3. count - the maximum number of elements we are willing to search against.
 *  4. size  - the size of each element of the array (in bytes)
 *  5. compare(void*, void*)
 *           - the function which is used for comparison. Zero is taken to be equality.
 */
void *binary_search(const void *x, const void *base, size_t count, size_t size,
                    int (*compare)(const void *, const void *));

#endif

binary_search.c

#include <stdlib.h>

void *binary_search(const void *x, const void *base, size_t count, size_t size,
                    int (*compare)(const void *, const void *))
{
    char *base_ptr = (char *) base;
    size_t lo = 0, hi = count - 1, mid;
    while (lo <= hi) {
        mid = lo + ((hi - lo) >> 1);
        int result = (*compare)(base_ptr + mid * size, x);
        if (result == 0) {
            return base_ptr + mid * size;
        } else if (result < 0) {
            lo = mid + 1;
        } else {
            hi = mid - 1;
        }
    }
    return NULL;
}

main.c

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "binary_search.h"

int compare(const void *a, const void *b)
{
    const double *p = a;
    const double *q = b;
    // The convention is to send the NaNs to the end, so
    // they are considered to be greater than others here.
    if (isnan(*p)) return +1;
    if (isnan(*q)) return -1;
    // An elegant way to convert the result to int:
    return (*p > *q) - (*p < *q);
}

int main(int argc, char const *argv[])
{
    double *a, *result;
    double x;
    size_t size, count, i;
    double aa = .1, bb = .1;
    size = sizeof(double);

    printf("Enter how many elements : ");
    scanf("%llu", &count);

    a = malloc(count * size);
    if (a == NULL) {
        printf("Error while trying to allocate memory.\n");
        return EXIT_FAILURE;
    }

    printf("Enter elements one-by-one:\n");
    for (i = 0; i < count; i++) {
        printf("%u : ", (i + 1));
        scanf("%lf", (a + i));
    }

    printf("Enter the element to look for : ");
    scanf("%lf", &x);
    result = binary_search(&x, a, count, size, compare);

    if (result) {
        printf("Element found. Index is %u\n", (result - a));
    } else {
        printf("Element not found.\n");
    }

    return EXIT_SUCCESS;
}

Same request. Suggestions and critique are welcome.

Update

In main.c, the line double aa = .1, bb = .1; is unnecessary. I forgot to remove it after debugging. You may disregard it.


texts: Search for everything at a tile in Minesweeper

texts:
I'm writing a Minesweeper clone. I needed a function that returns everything located at a certain tile, and ended up with an atrocious mess. I'd like help making it cleaner and more idiomatic.

The main state of the board is represented by a Field record:

(defrecord Field [dimensions ; Pair: [width height] in cells
                  flags ; Set
                  bombs ; Set
                  hints ; Map: Position -> hint value
                  uncovered-cells]) ; Set

Cell contents are tracked using sets for flags and bombs (since I only care about whether or not they're there), and a map for the hints (since I need to track the value of the hint as well). The keys for the sets/map are [x y] pairs representing a coordinate position, while the value for the hint map is a number between 1 and 8.

As mentioned above, I needed a function that returns everything at a certain coordinate. I ended up with this mess:

(defn- get-by-key [field x y key]
  ((key field) [x y]))

(defn all-at
  "Returns a set of everything at the position.
  Possible contents are :bomb, :flag, or a number representing a hint."
  [field x y]
  (let [g #(get-by-key field x y %)
        flag? (if (g :flags) :flag nil)
        bomb? (if (g :bombs) :bomb nil)
        hint? (g :hints)
        hint'? (if hint? hint? nil)]
    (into #{} ; So it can be easily searched for membership
          (filter #(not (nil? %))
                  [flag? bomb? hint'?]))))

I'm thoroughly unhappy with this though. It's giant for something that superficially seemed like a simple job, and has a lot of copied parts. The need for the filter also seems wrong, especially since I immediately force it into a set, so all laziness is gone.

I need it to check :flags, :bombs, and :hints to see if they contain the given coordinate, and if they do, return a set of everything at the position.

How can I write this better? Any suggestions here would be appreciated.


texts: How to simplify a discord bot remote tool

texts:
After a bit of struggling I've come up with the code

import discord
import os
import subprocess as sub
import psutil

client = discord.Client()

my_path = os.getcwd()
program_instance = False
currently_installed = os.path.isdir("web-application")

def run_command(command):
    value = sub.Popen(command, stdout = sub.PIPE, stderr = sub.PIPE)
    return value.communicate()

def kill():
    global program_instance
    if not program_instance:
        return "Program instance not initiated";
    process = psutil.Process(program_instance.pid)
    for proc in process.children(recursive = True):
        proc.kill()
    process.kill()
    program_instance = False
    return "Instance Killed"

def delete_if_exists():
    global currently_installed
    kill()
    if currently_installed:
        os.system("rmdir /S /Q web-application")
        while currently_installed:
            currently_installed = os.path.isdir("web-application")

def download_from_git():
    #pull from git
    global currently_installed
    kill()
    delete_if_exists()
    instance = sub.Popen("git clone LINKTOWEBAPPLICATION")
    instance.communicate()
    currently_installed = True
    return "Successfully downloaded"

def run(download = False):
    global program_instance
    folders = run_command("dir")
    if not currently_installed or download:
        download_from_git()
    kill()
    path = my_path+"\\web-application"
    #installing values in pipenv
    install_command_instance = sub.Popen("pipenv install", cwd = path)
    install_command_instance.communicate()

    program_instance = sub.Popen("pipenv run app.py", cwd = path)
    return "App Running"

@client.event
async def on_ready():
    print("Gitty woke")

@client.event
async def on_message(message):
    if message.author.bot or not message.channel.id == MYDISCORDUSERID:
        return;
    command = message.content

    checker = lambda command_name: command == command_name

    if checker("run"):
        await message.channel.send(run())

    if checker("kill"):
        await message.channel.send(kill())

    if checker("download"):
        await message.channel.send(download_from_git())

    if checker("run download"):
        await message.channel.send(run(download = True))

    if checker("ping"):
        currently_installed = os.path.isdir("web-application")
        await message.channel.send("Running:" + f"\n{program_instance=}, {currently_installed=}")

with open(".key", "r") as key:
    client.run(key.read())

The biggest problem with this code was killing running processes. I just wanted to know if there are any easier ways to do this. And if I made any choices which are over complicated.
Edit:
This bot is built to pull a repo from GitHub which contains a web-application that needs to be run. The reason I have to kill the application is so I can download a new version and rerun the code (as multiple instances of the website would be bad). The issue is that when the website is running I also have to be able to send the bot commands and thus have to run it as a separate instance so that the bot doesn't get "clogged" up running the site and can still take inputs


texts: Wrote a package in Go. What did I do wrong? What did I do right?

texts:
I wrote a Player package in Go. It builds correctly, but I would love a review on what I did and did not do "the Go way". I'm new to coding in the language, although I've gotten about halfway through Ivo Balbaert's "The Way To Go".

The code consists of a struct and a bunch of setters and getters for the struct.

package Player

import (
    "math/rand"
    "time"
)

type Player struct {
    name   string
    race   string
    id     int64
    pos    Position
    facing int64
    health int64
    wpn_id int64   // Weapon id
    is_buf bool    // Has buff
    buf_mt float64 // Buff multiplier
}

type Position map[int64]int64

func (P *Player) SetPlayer(name string, race string) *Player {
    rand := rand.New(rand.NewSource(time.Now().UnixNano()))

    P.name = name
    P.race = race
    P.id = rand.Int63()
    P.pos = Position{0: 0}
    P.facing = 0
    P.health = 100
    P.wpn_id = 0
    P.is_buf = false
    P.buf_mt = 0.0

    return P
}

func (P *Player) GetPlayer() *Player {
    return P
}

func (P *Player) SetPosition(x int64, y int64) {
    P.pos = Position{x: y}
}

func (P *Player) GetPosition() Position {
    return P.pos
}

func (P *Player) SetFacing(direction int64) {
    P.facing = direction
}

func (P *Player) GetFacing() int64 {
    return P.facing
}

func (P *Player) SetHealth(amount int64, direction string) {
    if direction == "down" {
        P.health = P.health - amount
    } else {
        P.health = P.health + amount
    }
}

func (P *Player) GetHealth() int64 {
    return P.health
}

func (P *Player) SetWeaponId(weapon_id int64) {
    P.wpn_id = weapon_id
}

func (P *Player) GetWeaponId() int64 {
    return P.wpn_id
}

func (P *Player) SetIsBuffed(is_buff bool) {
    P.is_buf = is_buff
}

func (P *Player) GetIsBuffed() bool {
    return P.is_buf
}

func (P *Player) SetBuffMultiplier(multiplier float64) {
    P.buf_mt = multiplier
}

func (P *Player) GetBuffMultiplier() float64 {
    return P.buf_mt
}


texts: Cast inside the method or let the client code cast, which one is better?

texts:
I have two choices of implementing a method, the first one is a generic type where the client code does not have to cast

    public T GetControl<T>(string controlName) where T : Control
    {
        return (T)ControlManager.GetControl( controlName);
        //I simplify the logic here, in my case this is a bit
        //complicated than this, but the object we get is of the Type Control
    }

client code:

MyControl control = GetControl<MyControl>("foo");

The second choice is the non-generic one. Here the client code will have to cast

    public Control GetControl(string controlName)
    {
        return ControlManager.GetControl(controlName);
        // I simplify the logic here, in my case this is a bit
        // complicated than this, but the object we get is of the Type Control
    }

client code:

    MyControl control = (MyControl)GetControl("foo");

Is one of them better than the other? At first I thought first one is better, because casting (which I think is a bit dirty) is refactored in one method, and don't have to be repeated in all client codes. But since the generic type has to be specified by the client code anyway (generic methods can't infer return type), basically the client code only shift (MyControl) in front to <MyControl> in the generic parameter, so it's probably not better anyway.

What is your opinion?


texts:
I figure there is a better way that I should be doing this:

if !db.collection_names.include?("reports".to_s)
  db.create_collection("reports")
end

if !db.collection_names.include?("days".to_s)
  db.create_collection("days")
end

if !db.collection_names.include?("users".to_s)
  db.create_collection("users")
end


texts: A z-shell function to quickly cd into projects

texts:
I think many know the problem of working with multiple projects: private projects, company projects, probably even projects for multiple companies.

From day-one, I've always searched for better ways to handle all those projects on the file system level.  I think I figured out a nice basic directory structure that works for me and my workflow:

~/code/$company_name/$project_name/[$application_name]

But, even with auto-completion and a $CODE var that pointed to ~/code, I had to type a lot more than I wanted when I had to switch between some projects.

So, for the sake of laziness (I also heard some smart guys call it "efficiency," but nah, I'm just lazy) and to learn a bit more about my shell, I decided to write a function that will do some of the work I'm not willing to do.

These were the functional requirements I defined for that function:

quickly cd into a project by given company and project name
possibility to add an optional application name for projects with multiple applications
possibility to pass a flag to create new project directories

Since I'm still a junior developer (1-year work experience, no degree, autodidact) and don't have much experience with shell-scripting, I'm pretty sure there is a lot to improve in my solution.

And since I'm always on the search for improvements, I decided to show my code to those of whom might be more experienced in this than me.

function pcd () {
  local create=false
  local target_dir="$HOME/code"
  local argument_count=$#

  local root
  local app_name
  local project_name

  # When first param is -c, set create flag to true and remove the param
  if [[ $1 == "-c" ]]; then
    create=true
    (( argument_count=argument_count-1 ))
    shift
  fi

  # the root (private, company1, company2, etc...)
  # I really would like to make that optional too, but
  # that would require
  root=$1

  # $PROJECT_ALIASES is a associative array to map some
  # project aliases to their actual names, it's set globally
  # since it's used in other scripts to and maintained through
  # it's own script
  project_name=$PROJECT_ALIASES[$2]

  # if the passed project string wasn't an alias,
  # assume it was the raw project name
  if [[ ! -n $project_name ]]; then
    project_name=$2
  fi

  # the app folder (for multi application projects, optional)
  app_name=$3

  # validate required params
  if [[ ! (( -n $root && -n $project_name )) ]]; then
    echo "[ERROR] - Please pass at least a root dir and a project name" >&2
    return 1
  fi

  target_dir="$target_dir/$root/$project_name"
  if [[ -n $app_name ]]; then
    target_dir="$target_dir/$app_name"
  fi

  # When the create flag is true (-c), create target directory
  if [[ $create == true ]]; then
    mkdir -p $target_dir
  fi

  # Finally, cd to the targeted directory
  cd $target_dir
}


texts:
Please review my code. I am trying to implement a thread-safe LRU cache using std::list and std::unordered_map. This is a header-only template class which you can use to keep an object cache.

The constructor takes a size as an input parameter and creates a cache of a specified size. Items will be removed based on the least recently used from the cache if the cache goes above the size.

#ifndef LRUCache_h__
#define LRUCache_h__

#pragma once
#include <vector>
#include <list>
#include <unordered_map>
#include <shared_mutex>
#include <iostream>

namespace objcache {

template <class T>
class LRUCache
{
    struct _node {
        int _key;
        T    _value;
    };

    // use map of key to iterator of LRU list
    using ListIterator = typename std::list<_node>::const_iterator;
    using CacheMap = std::unordered_map<int, ListIterator>;

    size_t                m_cacheSize;
    std::list<_node>    m_lruList;
    CacheMap            m_lruMap;
    std::mutex            m_lock;            // reader writer lock, multiple getters are allowed

public:

    /***
     * Method:        objcache::LRUCache::LRUCache
     * Access:        public
     * Description: This creates a cache of given size.
     */
    LRUCache(size_t size) :
        m_cacheSize{ size },
        m_lruList{},
        m_lruMap{},
        m_lock{}
    {
        //m_lruList.resize(m_cacheSize, 0);
        m_lruMap.reserve(m_cacheSize);
    }

    /***
     * Method:    objcache::LRUCache::set
     * Access:    public
     * Description : This API updates or sets the value val to key.
     */
    void Set(int key, const T &val) noexcept
    {
        std::lock_guard<std::mutex> guard(m_lock);

        if (auto mapIter = m_lruMap.find(key); mapIter != m_lruMap.end()) {
            //key already exists, just update the queue
            m_lruList.splice(m_lruList.begin(), m_lruList, mapIter->second);
        }
        else {
            // new item in the cache.
            m_lruList.push_front({ key, val });
            m_lruMap.insert(std::make_pair(key, m_lruList.begin()));
        }

        //remove least recently used element if cache is full.
        if (m_lruList.size() > m_cacheSize) {
            m_lruMap.erase(m_lruList.back()._key);
            m_lruList.pop_back();
        }
    }

    /***
     * Method:        objcache::LRUCache::get
     * Access:        public
     * Description: This API gets the value of key if it exists in cache,
     *                otherwise, just returns 0
     */
    T Get(int key) noexcept
    {
        std::lock_guard<std::mutex> gaurd(m_lock);
        T val = 0;
        if (auto key_iter = m_lruMap.find(key); key_iter != m_lruMap.end()) {
            m_lruList.splice(m_lruList.begin(), m_lruList, key_iter->second);
            val = (key_iter->second)->_value;
        }
        return val;
    }

    /***
     * Method:    objcache::LRUCache::printCache
     * Access:    public
     * Description : Prints the keys of the cache one-by-one
     */
    void PrintCache() noexcept
    {
        std::lock_guard<std::mutex> guard(m_lock);
        for (const auto &node : m_lruList)
            std::cout << node._key << std::endl;
    }

};

} // namespace objcache

#endif // LRUCache_h__


texts: Comparing corresponding elements of two equal-length arrays

texts:
I have a helper function I wrote, but it feels like something _.lodash already does or could do if I knew the library better.

function changed(before:any[], after:any[]):boolean[]
{
    if (before.length !== after.length)
    {
        throw new Error(`Length of arrays are not equivalent: ${before.length}, ${after.length}`);
    }
    else
    {
        let changed:boolean[] = [];
        for(let i = 0; i < before.length; i++)
        {
            changed[i] = (after[i] !== before[i]);
        }
        return changed;
    }
}

An example of how this might be used and what would return:

console.log(changed([0,1,0,1], [0,1,1,0]))
// => [false, false, true, true]

Does anyone know if this can be elegantly achieved with lodash?


texts:
I am currently learning Haskell and as an exercise, I am building a simple tic-tac-toe program. I start with
import Data.Vector

data Cell = Empty | X | O
type Board = Vector Cell

and then, to render the board:
render :: Board -> IO ()
render b = do
    renderSep
    renderRow 0 b
    renderSep
    renderRow 1 b
    renderSep
    renderRow 2 b
    renderSep
  where
    renderSep :: IO ()
    renderSep = putStrLn "+---+---+---+"
    renderRow :: Int -> Board -> IO ()
    renderRow r b = do
        putStr "| " >> putStr (cellRepr $ getCell r 0 b)
        putStr " | " >> putStr (cellRepr $ getCell r 1 b)
        putStr " | " >> putStr (cellRepr $ getCell r 2 b)
        putStrLn " |"

How could I abstract my implementation so that there's less repetition? Especially in the main body of the render function. I thought of using sequence together with the list fmap (\x -> renderRow x b >> renderSep) [0, 1, 2]. However, in this case I get a value of type IO [()] and not IO ().


texts:
Given A and B, count the numbers N such that A ≤ N ≤ B and N is a
  palindrome.

  Input:

  First line contains T, the number of testcases. Each testcase consists
  of two integers A and B in one line.

  Output:

  For each testcase, print the required answer in one line.

  Constraints:

  1 ≤ T ≤ 10

  0 ≤ A ≤ B ≤ 10^5

private static boolean[] isPalindrome = isPalindrome();
    public static void main(String args[] ) throws NumberFormatException,
IOException{
       BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        int totalTestCase = Integer.parseInt(reader.readLine());
        StringBuilder outputPalindromeCount = new StringBuilder();
        for (int i = 0; i < totalTestCase; i++) {
            String[] input=reader.readLine().split(" ");
            int startNo = Integer.parseInt(input[0]);
            int endNo = Integer.parseInt(input[1]);
            int totalFoundPalindrome = getPalindromeCount(startNo, endNo);
            outputPalindromeCount.append(totalFoundPalindrome + "\n");
        }
        System.out.println(outputPalindromeCount);

    }

    private static int getPalindromeCount(int startNo, int endNo) {
        int totalPalindromeFound = 0;
        for (int i = startNo; i <= endNo ; i++ ){
            if(isPalindrome[i]){
                totalPalindromeFound++;
            }
        }
        return totalPalindromeFound;
    }

    private static boolean[] isPalindrome() {
        boolean[] isPalindrome = new boolean[100001];
        Arrays.fill(isPalindrome, 0, 10, true);
        for (int i = 10; i <= 100000; i++) {
            if (checkForPalindrome(i)) {
                isPalindrome[i] = true;
            }
        }
        return isPalindrome;
    }

    private static boolean checkForPalindrome(int i) {
        int divNo = 1;
        while (i / divNo >= 10) {
            divNo = divNo * 10;
        }

        while (i != 0) {
            int startingDigit = i / divNo;
            int lastDigit = i % 10;
            if (startingDigit != lastDigit) {
                return false;
            }
            i = (i % divNo) / 10;
            divNo = divNo / 100;

        }
        return true;
    }

}

For this input:

6
0 0
1 1
1 10
1 9
1 1000
1000 100000

this code took 0.18 seconds. It's taking almost 0.18-0.20 seconds for various sets of input (link of all inputs and time).

What are the other Efficient way of checking palindromes (not just a way of conversion to a string and then check but really efficient)?

How could have I optimized the above code further (apart from BitSet which is a trade off for runtime)?


texts:
Long story short, I wrote this jQuery form plugin as an exercise to better understand how other form plugins work. If you have any suggestions about how to improve this (or my coding style in general) let me know.

var Form = function(options) {

    options = options || {};

    this.url = options.url;
    this.$fields = $(options.fields);
    this.$status = $(options.status);
    this.$submit = $(options.submit);
    this.$form = options.form || 'form';
    this.rFields = {
        required: /[^.*]/,
        nodigit: /^[^0-9]+$/,
        email: /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i,
    };
    this.required = [
        this.rFields.nodigit,
        this.rFields.email,
        this.rFields.required,
        this.rFields.required
    ];
    this.errors = ['Please enter a valid name.', 'Please enter a valid email address.', 'You must enter a subject.', 'No message? But I wanted one :('];

}

Form.prototype.init = function init() {

    this.$submit.click($.proxy(function(e) {
        this.process(e);
    }, this));

};

Form.prototype.process = function process(e) {

    var filled = true;

    e.stopImmediatePropagation();
    e.preventDefault();

    this.$fields.each($.proxy(function(i, element) {

        var $element = $(element);

        if (!$element.val().match(this.required[i])) {

            $element.focus();
            this.update(this.errors[i], true);
            filled = false;
            return false;

        }
    }, this));

    filled && this.submit($(this.$form).serialize());

};

Form.prototype.update = function update(message, isError) {

    if (isError && this.$status.hasClass('error')) {

        this.$status.addClass('error')
            .text(message);

        setTimeout($.proxy(function() {
            this.$status.removeClass('shake');
        }, this), 500);

    }
    else {

        this.$status.fadeOut();

        setTimeout($.proxy(function() {
            this.$status.text(message)
                .fadeIn();

            if (isError) {
                this.$status.removeClass('shake')
                    .addClass('error');
            }
            else {
                this.$status.removeClass('error info')
                    .addClass('success');
            }
        }, this), 500);

    }

    return this;

};

Form.prototype.submit = function submit(data) {

    $.ajax({
        type: 'POST',
        url: this.url,
        data: data,
        success: $.proxy(function(msg) {
            this.$fields.fadeOut();
            this.$status
                .empty()
                .append('
Nice one! The form has been sent to the server...
')

            $(this.$submit)
                .animate({
                left: '-=500px',
                opacity: 0,
            }, 300);

        }, this)
    });
};

Here's how to create a new form:

var exampleForm = new Form({
    url: mailUrl,
    fields: 'form input, form textarea',
    status: '#status',
    submit: '#submit'
})

exampleForm.init()

Pretty simple, just pass in..

The url to send the form data too
The form fields all encapsulated in one string seperated by commas in the correct order of validation rules.
Selector string where you want the status message to go
The submit selector. This element will actually submit the form


texts:
/*
Create a random maze
*/

package main

import (
    "fmt"
    "math/rand"
    "time"
)

const (
    mazewidth   = 15
    mazeheight  = 15
)

type room struct {
    x, y int
}

func (r room) String() string {
    return fmt.Sprintf("(%d,%d)", r.x, r.y)
}

func (r room) id() int {
    return (r.y * mazewidth) + r.x
}

// whetwher walls are  open or not.
// There are (num_rooms * 2) walls. Some are on borders, but nevermind them ;)
type wallregister [mazewidth * mazeheight * 2]bool

var wr = wallregister{}

// rooms are visited or not
type roomregister [mazewidth * mazeheight]bool

var rr = roomregister{}

func main() {
    rand.Seed(time.Now().Unix())

    stack := make([]room, 0, mazewidth*mazeheight)
    start := room{0, 0}

    // mark start position visited
    rr[start.id()] = true

    // put start position on stack
    stack = append(stack, room{0, 0})

    for len(stack) > 0 {
        // current node is in top of the stack
        current := stack[len(stack)-1]

        // Slice of neighbors we can move
        availneighbrs := current.nonvisitedneighbors()

        // cannot move. Remove this room from stack and continue
        if len(availneighbrs) < 1 {
            stack = stack[:len(stack)-1]
            continue
        }

        // pick a random room to move.
        next := availneighbrs[rand.Intn(len(availneighbrs))]

        // mark next visited
        rr[next.id()] = true

        // open wall between current and next:
        first, second := orderrooms(current, next)

        // second is either at the right or bottom of first.
        if second.x == first.x+1 {
            wr[first.id()*2] = true
        } else if second.y == first.y+1 {
            wr[first.id()*2+1] = true
        } else { // probably impossible or maybe not...
            panic("Wot?!?")
        }
        // push next to stack
        stack = append(stack, next)
    }

    // print maze

    // print upper border
    for x := 0; x < mazewidth; x++ {
        if x == 0 {
            fmt.Printf("   ")
        } else {
            fmt.Printf("_ ")
        }
    }
    fmt.Println()

    for y := 0; y < mazeheight; y++ {
        fmt.Printf("|") // left border
        for x := 0; x < mazewidth; x++ {

            id := room{x, y}.id()
            right := "|"
            bottom := "_"
            if wr[id*2] {
                right = " "
            }
            if wr[id*2+1] {
                bottom = " "
            }
            if x == mazewidth-1 && y == mazeheight-1 {
                right = " "
            }
            fmt.Printf("%s%s", bottom, right)
        }
        fmt.Println()
    }
}

// return slice of neighbor rooms
func (r room) neighbors() []room {
    rslice := make([]room, 0, 4)
    if r.x < mazewidth-1 {
        rslice = append(rslice, room{r.x + 1, r.y})
    }
    if r.x > 0 {
        rslice = append(rslice, room{r.x - 1, r.y})
    }
    if r.y < mazeheight-1 {
        rslice = append(rslice, room{r.x, r.y + 1})
    }
    if r.y > 0 {
        rslice = append(rslice, room{r.x, r.y - 1})
    }
    return rslice
}

// return rooms that are not visited yet
func (r room) nonvisitedneighbors() []room {
    rslice := make([]room, 0, 4)
    for _, r := range r.neighbors() {
        if rr[r.id()] == false {
            rslice = append(rslice, r)
        }
    }
    return rslice
}

// order to rooms by closeness to origin (upperleft)
func orderrooms(room1, room2 room) (room, room) {
    dist1 := room1.x*room1.x + room1.y*room1.y
    dist2 := room2.x*room2.x + room2.y*room2.y
    if dist1 < dist2 {
        return room1, room2
    }
    return room2, room1
}

http://play.golang.org/p/8W_FbBfUjb (You can run it here. But since time.Now() is fixed there, you will always get same maze.)

In any aspect of it, how does it look?


texts:
I currently have a table with about 29 million records. The table currently has no indexes.  However, I would like to build a clustered composite index built on three columns.

When I attempt to add the NON NULL constraint, my logs fill up. So my approach is to create three new columns with NON NULL, fill them up with data from the original three columns, and create my index on the three new columns.

In order to do this, I first loop through the table in batches to populate the column. This is because I was running out of transaction log space. This was based on the lock escalation page on Microsoft's site. The threshold is 5000 locks. If rows are being locked, I wanted to come in under that limit. So 4000 rows at a time.

I didn't create a new table, insert into it, then drop & rename because I thought it would be more efficient to just change some data than move everything - I might be wrong about this. When I did try it, I ran out of log space again.

This is the SQL I am using to update my new columns looks like this:

DECLARE @Rows INT,
        @BatchSize INT;      -- keep this below 5k

SET @BatchSize = 4000;

SET @Rows = @BatchSize;

BEGIN TRY
    WHILE (@Rows = @BatchSize)
    BEGIN
        UPDATE Top(@BatchSize) Master.VOUCHER_LINE
        SET tempBusinessUnit = BUSINESS_UNIT
        FROM Master.VOUCHER_LINE
        WHERE tempBusinessUnit = 'xxxxx'; /* This is a default value for the column.
        It identifies columns that have not been updated. */

        SET @Rows = @@ROWCOUNT;

        /* This prints the time that each loop is completed.
        I use it to estimate how much time this script will take. */
        DECLARE @Time nvarchar(100)
        SET @Time = CAST(CURRENT_TIMESTAMP as nvarchar)
        RAISERROR(@Time, 0, 1) WITH NOWAIT

    END
END TRY

BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT @ErrorMessage = ERROR_MESSAGE(), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE();

    RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH;

With 29 million records (and about 100 columns), I expect this operation to take a while. After running for the first hour, the performance is 4,000 records about every 2 minutes.  At that rate this single column will be done in approximately 10 days.

Is there something I can do to improve performance?