texts:
I am learning C, and wrote this pig-latin translator.

If no argument is given, it operates on standard input. Otherwise, it operates on the arguments given.

Here are some examples:

$ echo "The quick brown fox jumps over Vladmir's lazy young Yggdrasil!" | ./piglatin
Ethay ickquay ownbray oxfay umpsjay overway Admir'svlay azylay oungyay Yggdrasilway!

$ ./piglatin "Now is the time, for all good men to come to the aid of their party"
Ownay isway ethay imetay, orfay allway oodgay enmay otay omecay otay ethay aidway ofway eirthay artypay

#include <err.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define SUFFIXC  "ay"
#define SUFFIXV  "way"

static void usage(void);
static void piglatin(const char *s);
static int isvowel(const char *s);

/* Encodes English-language phrases into Pig Latin. */
int
main(int argc, char *argv[])
{
    int c;

    while ((c = getopt(argc, argv, "h")) != -1) {
        switch (c) {
        case 'h':
        default:
            usage();
            break;
        }
    }
    argc -= optind;
    argv += optind;

    if (argc == 0) {
        char *line = NULL;
        size_t linesize = 0;
        ssize_t linelen;

        while ((linelen = getline(&line, &linesize, stdin)) != -1) {
            if (line[linelen - 1] == '\n')
                line[linelen - 1] = '\0';
            piglatin(line);
        }
        free(line);
        if (ferror(stdin))
            err(EXIT_FAILURE, "stdin");
    } else {
        while (argc-- > 0)
            piglatin(*argv++);
    }
    if (ferror(stdout))
        err(EXIT_FAILURE, "stdout");

    return EXIT_SUCCESS;
}

/* translate s into Pig Latin */
static void
piglatin(const char *s)
{
    const char *p, *onset, *root, *end, *suffix;
    bool upper;

    while (*s != '\0') {
        while (!isalpha(*s) && *s != '\'' && *s != '\0')
            putchar(*s++);

        upper = false;
        if (isupper(*s))
            upper = true;

        if (*s == '\0')
            break;

        onset = s;

        while (isalpha(*s) && !isvowel(s)) {
            if (*s == 'q' && *(s+1) == 'u')
                s++;
            s++;
        }
        root = s;

        while (isalpha(*s) || *s == '\'')
            s++;
        end = s;

        suffix = (onset == root) ? SUFFIXV : SUFFIXC;

        for (p = root; p != end; p++) {
            if (p == root && upper)
                putchar(toupper(*p));
            else
                putchar(*p);
        }

        for (p = onset; p != root; p++) {
            if (p == onset && upper)
                putchar(tolower(*p));
            else
                putchar(*p);
        }

        printf("%s", suffix);

    }

     printf("\n");
}

/* test if first letter of s is a vowel */
static int
isvowel(const char *s)
{
    switch (tolower(*s)) {
    case 'a': case 'e': case 'i': case 'o': case 'u':
        return 1;
    case 'y':
        return (isvowel(s+1) ? 0 : 1);
    }
    return 0;
}

static void
usage(void)
{
    (void) fprintf(stderr, "usage: piglatin [phrase...]\n");
    exit(EXIT_FAILURE);
}


texts:
This is a follow up to Log probe requests of WiFi devices focussing on a specific element of the code.

How can I indent this code to make it look great and be well formatted?

parser = argparse.ArgumentParser(description='Collect WiFi probe requests')
parser.add_argument('-i', '--interface',
                    default=default_interface,
                    help='the interface used for monitoring')
parser.add_argument('--tshark-path',
                    default=distutils.spawn.find_executable("tshark"),
                    help='path to tshark binary')
parser.add_argument('--ifconfig-path',
                    default=distutils.spawn.find_executable("ifconfig"),
                    help='path to ifconfig')
parser.add_argument('--iwconfig-path',
                    default=distutils.spawn.find_executable("iwconfig"),
                    help='path to iwconfig')
parser.add_argument('-o', '--output',
                    default='-',
                    help='output file (path or - for stdout)')
parser.add_argument('-c', '--channel',
                    default='all',
                    help='channel/s to hop (i.e. 3 or 3,6,9 or 3-14 or all or 0 for current channel')
parser.add_argument('--verbose',
                    action='store_true',
                    help='verbose information')
parser.add_argument('-p', '--only-probes',
                    action='store_true',
                    help='only saves probe data spit by newline')
parser.add_argument('--delay',
                    default=5,
                    help='delay between channel change')
args = parser.parse_args()


texts:
I am working through the exercises in the book Accelerated C++.  I wanted to get some feedback on proper use of the Standard Library, correctness, overall style, portability, etc.

/*******************************************************************************
Accelerated C++ Chapter 3

Write a program to count how many times each distinct word appears in its input
*******************************************************************************/

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::cout << "Enter a list of words followed by end-of-file: ";

    typedef std::vector<std::string>::size_type vector_sz;
    std::vector<std::string> words;
    std::string word;
    while (std::cin >> word)
    {
        words.push_back(word);
    }

    vector_sz size = words.size();
    if(size == 0)
    {
        std::cout << "Please enter some words!";
        return -1;
    }

    std::vector<int> frequency;
    std::vector<std::string> unique_words;
    int count = 0;
    bool isUnique;

    unique_words.push_back(words[0]);

    for(unsigned i = 0; i < words.size(); ++i)
    {
        isUnique = true;

        for(unsigned j = 0; j < unique_words.size(); ++j)
        {
            if(words[i] == unique_words[j])
            {
                isUnique = false;
            }
        }
      if(isUnique)
      {
          unique_words.push_back(words[i]);
      }
    }

    for(unsigned i = 0; i < unique_words.size(); ++i)
    {
        for(unsigned j = 0; j < words.size(); ++j)
        {
            if(unique_words[i] == words[j])
            {
                count += 1;
            }
        }
        frequency.push_back(count);
        count = 0;
    }

    for(unsigned i = 0; i < unique_words.size(); ++i)
    {
        std::cout << unique_words[i] << "   " << frequency[i] << std::endl;
    }
    return 0;
}


texts: Converting an angle in degrees to a pretty string representing it in radians

texts:
Given an angle in degrees, output a pretty string representation of its value in radians as a fraction.

Where pretty means:

Simplified as much as possible.
With no unnecessary ones.
Using the Unicode character that represents pi: π
With a single minus in front if negative (a minus at the denominator is not allowed).

For example: degrees_to_pretty_radians(-120) #=> '-2π/3'

I wanted to write this in Python too to compare it to how it looked implemented in Javascript

The code is pretty straightforward and passes a lot of test-cases, but I am still interested in any kind of feedback:

def degrees_to_pretty_radians(angle: "in degrees") \
                    -> "Pretty string for the value in radians.":
    """
    >>> tests = [0, 1, 18, 31, 45, 60, 120, 180, 270, 360, 480]
    >>> all_tests = tests + [-x for x in tests]
    >>> for angle in all_tests: print(angle, degrees_to_pretty_radians(angle))
    0 0π
    1 π/180
    18 π/10
    31 31π/180
    45 π/4
    60 π/3
    120 2π/3
    180 π
    270 3π/2
    360 2π
    480 8π/3
    0 0π
    -1 -π/180
    -18 -π/10
    -31 -31π/180
    -45 -π/4
    -60 -π/3
    -120 -2π/3
    -180 -π
    -270 -3π/2
    -360 -2π
    -480 -8π/3

    """
    gcd = fractions.gcd(angle, 180)
    denominator = "" if 180 // gcd == 1 else "/{}".format(180 // gcd)
    numerator = "" if abs(angle // gcd) == 1 else abs(angle // gcd)
    sign = "-" if angle < 0 else ""
    return "{}{}π{}".format(sign, numerator, denominator)


texts:
Where I stand on Lisp

So, Lisp. It's been on my radar for years and I'm finally getting around to learning it. The syntax is foreign but I find I'm having the most difficulty in the areas of semantics and the standard library. The symbol semantics are giving me tremendous trouble for sure, mainly because I find it hard to tell when a symbol is needed as opposed to a value. It probably sounds silly, but I find C pointers to be more intuitive and straightforward, and this is probably owed to the fact that C is exclusively pass-by-value, whereas Lisp is ostensibly both pass-by-value and pass-by-reference, and the semantics therein--which behavior is chosen and when--is unknown to me. For example, why is (1 2 3) inappropriate in a situation where '(1 2 3) and list--assuming its value is (1 2 3)--are perfectly okay? Ostensibly, this is an ambiguity in the syntax and Lisp thinks I'm trying to call a function called 1. This type of situation stresses me out precisely because I start thinking of the unknown unknowns--what other situations like this are going to come along and derail me or cause bugs that remain hidden for extended periods of time? I imagine, perhaps without warrant, disasters on par with Undefined Behavior in C.

The code to be reviewed

Long intro, but since this is a code review, I feel it should probably be made clear where I stand so that reviews can take it into account and use it to more effectively communicate the review. I.e. I am a seasoned programmer, I dabble in "language lawyering", and I'm a complete beginner in Lisp.

That said, my first Common Lisp project is FizzBuzz. And what better way to get more comfortable with the language than to put my newbie code out for other people to systematically tear apart?

#|| divisible()
 || I don't usually write functions for something as obvious as
 || "is X divisible by Y", but in this case, I find
 ||
 ||     (divisible 15 5)
 ||
 || easier to read than
 ||
 ||     (= 0 (mod 15 5))
 ||
 || feel free to refute if you disagree and think this is a
 || code smell or you know of a more idiomatic way
 ||
 || Also feel free to say something if you feel
 || this C-like multi-line style is in bad taste
 ||#
(defun divisible (a b) (= 0 (mod a b)))

#|| range()
 || Copy/pasted from somewhere else. I don't know what cons does
 || I do understand that the function is recursive
 || I do not think I would have thought of this on my own
 ||#
(defun range (min max)
  (when (<= min max)
    (cons min (range (+ min 1) max))))

(defun fizzbuzz (n)
  (setf out (string ""))

  (unless (or (divisible n 3) (divisible n 5))
    (return-from fizzbuzz n))

  (when (divisible n 3)
    (setf out (format nil "~d~d" out "Fizz")))

  (when (divisible n 5)
    (setf out (format nil "~d~d" out "Buzz")))

  out)

(setf 1to100 (range 1 100))
(setf 1to100fb (map 'list #'fizzbuzz 1to100))
(mapcar #'(lambda (str) (format t "~d~%" str)) 1to100fb)

I admit, it's hard to break away from imperative programming.

The style isn't completely foreign to me, actually. I've already used (and am very much a fan of) style similar to this in C-like languages...

while(condition)
    if(condition)
        do_something;

And I'm already a fan of functional programming...

return list.map(x => (x * x) % 256).filter(x => x >= 10);

So I believe I'm on the right track. Although Dunning-Kruger is always in effect.


texts: Converting array of bytes to the hex string representation

texts:
Is it possible to make the hexStr function faster?

#include <sstream>
#include <iomanip>
#include <stdio.h>

std::string hexStr(unsigned char* data, int len)
{
    std::stringstream ss;
    ss << std::hex;
    for(int i=0;i<len;++i)
        ss << std::setw(2) << std::setfill('0') << (int)data[i];
    return ss.str();
}

int main()
{
   std::string packet = "";
   packet += 0x6b;
   packet += 0x0f;
   std::string hex = hexStr((unsigned char*)packet.c_str(), packet.length());
   printf("%s\n", hex.c_str()); // 6b0f
   return 0;
}


texts: Rolling mean lag function for multiple variables

texts:
Thanks to @josliber's help (Rolling mean lag function), I was able to speed up a rolling mean function for different groups and rollmean lengths.

Now I'd like to add to this function the ability to loop through different variables and bind everything together.

Minimum reproducible example

library(zoo)
dat <- data.frame(fips = rep(c(1001, 1003), each = 100),
                  x = rnorm(200),
                  x2 = rnorm(200),
                  x3 = rnorm(200))

allFipsRM3 = function(dat, varName, len){
  do.call(rbind, lapply(split(dat, dat$fips), function(x) {
    all.rm <- as.data.frame(sapply(len, function(l) c(rollmean(x[,varName], l), rep(NA, l-1))))
    colnames(all.rm) <- paste0(varName, "_rm", len)
    cbind(data.frame(fips=x$fips[1]), all.rm, data.frame(year=seq_len(nrow(x))-1))
  }))
}

outdat3 <- allFipsRM3(dat, "x", c(1, 2))

       fips      x_rm1      x_rm2 year
1001.1 1001  1.3482892  1.3043620    0
1001.2 1001  1.2604348  0.2990267    1
1001.3 1001 -0.6623813 -0.4243813    2
1001.4 1001 -0.1863812  0.2806624    3
1001.5 1001  0.7477061 -0.5111745    4
1001.6 1001 -1.7700551 -0.8463731    5


texts: Two methods to prompt the user to enter the width and length of a rectangle

texts:
I have two similar methods for setting dimensions of a rectangle. At first, I had them combined into one longer method that set width and length. I read about keeping code modular that performs one task at a time. So split it into two methods. Also, I have separate methods for displaying messages. Am I going overboard breaking methods into smaller ones?

private void userInputWidth() {
    Scanner reader = new Scanner(System.in);
    double loopCondition = 0;
    while (loopCondition <= 0) {
        displayEnterWidth();
        double nextDouble = reader.nextDouble();
        loopCondition = nextDouble;
        if (nextDouble <= 0) {
            displayErrorMessage();
        } else {
            this.rectangleWidth = nextDouble;
            break;
        }
    }
}

private void displayEnterWidth() {
    System.out.println("Please enter the width of the rectangle ");
}

2nd Method

private void userInputLength() {
    Scanner reader = new Scanner(System.in);
    double loopCondition = 0;
    while (loopCondition <= 0) {
        displayEnterLength();
        double nextDouble = reader.nextDouble();
        loopCondition = nextDouble;
        if (nextDouble <= 0) {
            displayErrorMessage();
        } else {
            this.rectangleLength = nextDouble;
            break;
        }
    }
}

private void displayEnterLength() {
    System.out.println("Please enter the length of the rectangle");
}


texts: Best practice and alternatives for string manipulation with an emphasis on readability

texts:
As a personal habit I generally prefer to use string replace and format methods, along with string "patterns", in lieu of string concatenation and other methods in most languages I use (typically C# and Javascript).

For example, if I want to generate a URL with parameters (C#), I use:

string url = "page.aspx?id={id}&ref={ref}";
return url.Replace("{id}", id)
          .Replace("{referrer}", referrer);

// could also be expressed as
return "page.aspx?id={id}&ref={ref}".Replace("{id}", id)
                                    .Replace("{referrer}", referrer);

Instead of:

return "page.aspx?id=" + id + "&ref=" & referrer;

Or:

// StringBuilder is typically more efficient than string concatenation
StringBuiler sbUrl = new StringBuilder();
sbUrl.Append("page.aspx?");
sbUrl.AppendFormat("id={0}", id);
sbUrl.AppendFormat("ref={0}", referrer);
return sbUrl.ToString();

I do the same in Javascript:

function generateUrl(p1, p2) {
    return "page.aspx?1={0}&2={1}".replace("{0}", p1)
                                  .replace("{1}", p2);
}

The reason is I prefer the readability of the code, especially when large amounts of textual data must be processed, such as in the case of a form letter or e-mail:

// this would typically be stored in an XML or other configuration file as a "pattern"
string body = @"Dear {name}:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquam blandit risus, quis imperdiet nibh congue quis.

Pellentesque ullamcorper malesuada ante, ac auctor felis feugiat id. Etiam id eros convallis nisi feugiat tincidunt. Phasellus fringilla erat eu tortor egestas volutpat. Vestibulum in odio lorem, quis fringilla sapien.

Sincerely,

{from-name}
";

return body.Replace("{name}", name).Replace("{from-name}", fName);

My concern is, however, that my methods are generally inefficient and that there may be better, more standardized ways of doing this.

Thoughts?


texts:
Recently I started looking and refreshing about algorithms and decided to try to do the 3 sum algorithm. I did the code below:

public static int[] tripletSum(int[] A, int sum) {

    HashMap<Integer, Boolean> data = new HashMap<>();

    for (int i = 0; i < A.length; i++) {
        data.put(A[i], true);
    }

    int i = 0;
    int j = 1;

    while (i < A.length && j < A.length) {

        Integer a = A[i];

        Integer b = A[j];

        Integer delta = sum - (a + b);

        if (data.containsKey(delta) && a != delta && b != delta && (a + b + delta) == sum) {
            int[] result = {a, b, delta};
            return result;

        }
        i++;
        j++;
    }
    return null;
}

I'd like opinions about if it is good logic, time complexity, improvements. Any tips and comments will be great.

The piece of code below:

if (data.containsKey(remainder) && a != remainder && b != remainder && (a + b + remainder) == sum) {

is included to avoid to repeat values in a and b, and to guarantee the sum result as expected.

Thanks


texts:
I'm trying to implement a re_sub and it's been quite tricky for me to do. I wanted to take the python code to replace a string --  re.sub(r";.+", " ", s) -- and do it in C. Examples of grabbing a single regex match were pretty easy to find (and do) but doing multiple matches and then substituting proved to be quite tricky (for me at least).
Here is what I have so far:
#include <pcre.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>

#define OFFSETS_SIZE 90
#define BUFFER_SIZE (1024*10)
char buffer[BUFFER_SIZE];

void exit_with_error(const char* msg, ...)
{
    va_list args;
    va_start(args, msg);
    vfprintf(stderr,  msg, args);
    exit(EXIT_FAILURE);
}

void re_sub(char buffer[], const char* pattern, const char* replacement)
{
    const char *error;
    int error_offset;
    int offsets[OFFSETS_SIZE];
    size_t replacement_len = strlen(replacement);

    // 1. Compile the pattern
    pcre *re_compiled = pcre_compile(pattern, 0, &error, &error_offset, NULL);
    if (re_compiled == NULL)
        exit_with_error(strerror(errno));

    // 2. Execute the regex pattern against the string (repeatedly...)
    int rc;
    size_t buffer_size = strlen(buffer);
    char tmp[buffer_size * 2];
    int tmp_offset=0, buffer_offset=0;

    while ((rc = pcre_exec(re_compiled, NULL, buffer, strlen(buffer), buffer_offset, 0, offsets, OFFSETS_SIZE)) > 0) {
        int start=offsets[0];
        int end=offsets[1];
        int len =  start - buffer_offset;

        // 1. copy up until the first match if the first match starts after
        //    where our buffer is
        printf("Start: %d | End: %d | Len: %d | BufferOffset: %d\n", start, end, len, buffer_offset);
        if (start > buffer_offset) {
            strncpy(&tmp[tmp_offset], buffer+buffer_offset, len);
            tmp_offset += len;
        }

        // 2. copy over the replacement text instead of the matched content
        strncpy(&tmp[tmp_offset], replacement, replacement_len);
        tmp_offset += replacement_len;
        buffer_offset = end;
    };

    // exit early if there was an error
    if (rc < 0 && rc != PCRE_ERROR_NOMATCH) {
        free(re_compiled);
        exit_with_error("Matching error code: %d\n", rc);
    }
    // now copy over the end if leftovers
    if (buffer_offset < buffer_size-1)
        strcpy(&tmp[tmp_offset], buffer+buffer_offset);

    free(re_compiled);
    strcpy(buffer, tmp);
}

int main(int argc, char* argv[])
{
    strcpy(buffer, "Hello ;some comment");
    re_sub(buffer, ";.+", " ");
    printf("Buffer: %s", buffer);
    return 0;
}

And a working example: https://onlinegdb.com/SJtW_8Tr_ (note you have to go in the upper-right hand corner, click settings gear and add -lpcre into the Extra Compiler Flags (they don't persist on the share link).
A few comments about the code:

I find it very tedious and quite hard to keep track of all the offsets, for example: &tmp[tmp_offset]. Is there a better way to do this? I tried adding a ptr of char *tmp_ptr = tmp but for whatever reason I couldn't get that way to work properly.
I think I need to have the user pass in the size_t buffer_len otherwise it's very easy to get a buffer overflow, as the only thing I know about the buffer is the strlen. In this example here I have 10K in the buffer, so it's not going to overflow, but in other examples it's very possible that it could.
Is there something like a 'package manager' (like pip or npm) for C? For example, if I'm to move this code onto another server, how do I 'build it with pcre, which may not even be on the server? Is this what cmake is for, or what's a common way to 'manage' non stdlib packages?


texts: Semantic implementation of the structure of a web page with header, main, and footer

texts:
I'm new to web development, and currently learning the basics of HTML and CSS. Many web pages follow the structural pattern of header, main, and footer; so I figured it'd be a good idea to try and implement this structure to see how things are carved.

body {
  display: flex;
  flex-direction: column;
  font-family: sans-serif;
  margin: 0;
  min-height: 100vh;
}

header,
footer {
  background-color: dodgerblue;
  color: white;
  text-align: center;
}

main {
  background-color: snow;
  flex: 1;
  padding: 1rem;
}

footer {
  margin-top: auto;
}
<!DOCTYPE html>

  <title>Test</title>
  <link rel="stylesheet" href="main.css">
  <meta charset="UTF-8">

Header

Main content

Footer

I'm looking for all kinds of feedback, from style, to anti-patterns, ways to do things more concisely, and whatever other observation you can find useful. I do have some specific questions:

Are the semantic HTML elements used correctly? There's no need for an article element inside the main element, right?
In the CSS I selected both header and footer for stuff that they have in common, is this good practice? Or should I keep a single header and a single footer selectors, separately? Could be more maintainable that way?
Is this normally handled using Flexbox? Or is Grid display a better tool for this?
What things would you do differently?


texts:
I am trying to work on a WPF application and decided to go for Unit of Work and Repository pattern, along with MVVM. I am using Entity Framework as my ORM. Could you please do a code review?

IGenericRepository.cs

public interface IGenericRepository<T>
{
    T GetById(int id);
    IQueryable<T> GetAll();
    void Edit(T entity);
    void Insert(T entity);
    void Delete(T entity);
}

IUnitOfWork.cs

public interface IUnitOfWork : IDisposable
{
    GenericRepository<T_Asset> AssetRepository { get; }
    GenericRepository<T_ColumnFormula> FormulaRepository { get; }
    GenericRepository<T_Column> ColumnRepository { get; }
    void Save();
}

GenericRepository.cs

    public class GenericRepository<T> : IGenericRepository<T> where T : class
    {
        protected DbContext _objDataContext;
        protected readonly DbSet<T> _objDbSet;

        public GenericRepository(DbContext objDataContext)
        {
            _objDataContext = objDataContext;
            _objDbSet = objDataContext.Set<T>();
        }

        public T GetById(int id)
        {
            return _objDbSet.Find(id);
        }

        public IQueryable<T> GetAll()
        {
            return _objDbSet;
        }

        public void Insert(T entity)
        {
            _objDbSet.Add(entity);
        }

        public void Edit(T entity)
        {
            _objDataContext.Entry(entity).State = EntityState.Modified;
        }

        public void Delete(T entity)
        {
            _objDataContext.Entry(entity).State = EntityState.Deleted;
        }
    }

UnitOfWork.cs

public class UnitOfWork : IUnitOfWork
{
    private GenericRepository<T_Asset> _assetRepository;
    private GenericRepository<T_ColumnFormula> _formulaRepository;
    private GenericRepository<T_Columns> _columnRepository;
    private DbContext _objDataContext;

    public UnitOfWork(string connectionString)
    {
        _objDataContext = new FormulaBuilderContext(connectionString);
    }

    public GenericRepository<T_Asset> AssetRepository
    {
        get
        {
            if (_assetRepository == null)
            {
                _assetRepository = new GenericRepository<T_Asset>(_objDataContext);
            }
            return _assetRepository;
        }
    }

    public GenericRepository<T_ColumnFormula> FormulaRepository
    {
        get
        {
            if (_formulaRepository == null)
            {
                _formulaRepository = new GenericRepository<T_ColumnFormula>(_objDataContext);
            }
            return _formulaRepository;
        }
    }

    public GenericRepository<T_Column> ColumnRepository
    {
        get
        {
            if (_columnRepository == null)
            {
                _columnRepository = new GenericRepository<T_Column>(_objDataContext);
            }
            return _columnRepository;
        }
    }

    public void Save()
    {
        _objDataContext.SaveChanges();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_objDataContext != null)
            {
                _objDataContext.Dispose();
            }
        }
    }
}

Please suggest necessary changes in order to implement the patterns properly. Also I am ready to share more information if necessary.


texts: File Async writer using Tasks or new features of .Net 4.5?

texts:
This code was posted as answer to Async file writer in .Net 3.5.

How would it be done better using Tasks or new features in .Net 4.5?

public sealed class Logger : IDisposable
{
    private delegate void WriteMessage(string message);
    private static readonly Logger Instance = new Logger();
    private static object Locker = new object();
    private static readonly StreamWriter Writer =
                        new StreamWriter("c:\\temp\\logtester.log", true);
    private static bool Disposed;

    private Logger()
    {
    }

    ~Logger()
    {
        Dispose(false);
    }

    public static void Log(string message)
    {
        WriteMessage action = Instance.MessageWriter;
        action.BeginInvoke(message, MessageWriteComplete, action);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private static void Dispose(bool disposing)
    {
        lock (Locker)
        {
            if (Disposed)
            {
                return;
            }

            if (disposing)
            {
                if (Writer != null)
                {
                    Writer.Dispose();
                }
            }

            Disposed = true;
        }
    }

    private static void MessageWriteComplete(IAsyncResult iar)
    {
        ((WriteMessage)iar.AsyncState).EndInvoke(iar);
    }

    private void MessageWriter(string message)
    {
        lock (Locker)
        {
            Writer.WriteLine(message);
        }
    }
}


texts: Cross-site request forgery defense for code to count Likes

texts:
I have the following code which is supposed to insert a row into a DB table "clicks" (consisting of 1 Primary AI column "id" and another column "user" which contains the user's session ID) upon clicking the Like button. For each user assuming they have a session ID set from a login I would like to return to them their most recently inserted ID from the table. So the first time the button is clicked it will return 1 etc. I would like this to be accessible to multiple users through a login system.

Is this vulnerable to Cross-site request forgery and if so, how can I alter the code to defend against it?

index.php:

<?php
include 'init.php';
include 'connect.php';
?>
<!doctype html>

    <?php
    $userid = $_SESSION['user_id'];
   echo 'Like';
    ?>

connect.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "DB";
$conn = new mysqli($servername, $username, $password, $dbname);

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

init.php

<?php
session_start();
$_SESSION['user_id']='1';
$userid = $_SESSION['user_id'];
include 'connect.php';
include 'like.php';
?>

like.js

function like_add(userid) {
$.post('like_add.php', {userid:userid}, function(data) {
   if (data == 'success'){
    add_like($userid);
   } else{
       alert(data);
   }
});
}

like.php

<?php
function add_like($userid){
include 'connect.php';

$stmt = $conn->prepare("INSERT INTO clicks (user) VALUES (?)");
$stmt->bind_param("s", $userid);

$stmt->execute();
$stmt = $conn->prepare("SELECT max(id) FROM clicks WHERE user=?");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt->bind_result($click);
$stmt->fetch();
echo $click;
$stmt->close();
}
?>

like_add.php

<?php
include 'init.php';
if (isset($userid)) {
$userid = $userid;
add_like($userid);
}
?>


texts:
I created a function which has, I believe, truly private variables.  It's not quite production ready for several reasons:

It's using Object.defineProperty -- I can deal with this
It is re-defining every function in the prototype by doing eval( fn.toString() ) -- I do not like this
I'm re-defining the prototypes, hence doing-away with the advantage of prototypes! -- deal breaker

Anyway, I'm putting this out there for critique / suggestions / recommendations for how to fix the above points.  I'm not sure I'll ever really do anything with it, but I find it to be an interesting problem:

function foo(){
    this.definePrivateProperties('foo', 'bar');
}

foo.prototype.setFoo = function(x){
    this.foo = x;
};

foo.prototype.getFoo = function(){
    return this.foo;
};

foo.prototype.definePrivateProperties = function(){
    var   self = this,
          args = arguments,
      validFns = {},
         proto = this.__proto__;

    // replace all functions in prototype with new ones!
    // set a random key on each new function
    //   (not 100% secure, but close enough for now)
    //   this ensures that the function is unique to -this- object
    for(var fn in proto){
        this[ fn ] = eval( '(' + proto[fn] + ')' );
        validFns[ this[ fn ].key = Math.random() ] = 1;
    }

    for(var i=0, l=args.length; i<l; i++){
        (function(){
            var val;

            Object.defineProperty(self, args[i], {
                get          : function getter(){
                    if(validFns[ arguments.callee.caller.key ])
                        return val;
                },
                set          : function setter(v){
                    if(validFns[ arguments.callee.caller.key ])
                        val = v;
                },
                configurable : true,
                enumerable   : false
            });
        })();
    }
};

> var x = new foo();
> x.setFoo(42);
> x.foo = 20;
20
> x.foo;
undefined
> x.getFoo();
42


texts:
Is there anything I need to add or is this the best security possible?

<?php

//Get Sessions Prepared;
session_start();

//If logged in, Logout;
if(!empty($_SESSION['username'])) {

    //Remove Sessions to Logout the user;
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
    session_destroy();

} else {

    //If not logged in redirect to Homepage;
    header("Location: http://gameshare.io/login");

}

?>


texts: Reading input from console in F# (as a sequence of lines)

texts:
Consuming input line-by-line until the end is often useful. In C# I would write the following loop:

while ((line = Console.ReadLine()) != null) {
    // ...

I wanted to do this using "idiomatic" F# (which to me includes avoiding let mutable) and I came up with this:

let rec readlines = seq {
    let line = Console.ReadLine()
    if line <> null then
        yield line
        yield! readlines
}

The last line shows the following warning

  Warning FS0040: This and other recursive references to the object(s)
  being defined will be checked for initialization-soundness at runtime
  through the use of a delayed reference. This is because you are
  defining one or more recursive objects, rather than recursive
  functions. This warning may be suppressed by using '#nowarn "40"' or
  '--nowarn:40'.

The warning would suggest I am actually not writing idiomatic F# (as warnings usually point out problematic code). Is there a better way to write the function that avoids the warnings?


texts: Reading a file and storing the contents in an array

texts:
This is my code for reading a file with a delimiter.  Any suggestions to help improve my code efficiency?

I am not satisfied with using array data structure.  Can any other data structure be used instead of an array?

bool read_file(char *p_file_name,char *file_content[FILE_NO_OF_ROWS][FILE_NO_OF_COL],const char *delimiter, int& token_count )
{

   using namespace std;
   ifstream file_is_obj;
   file_is_obj.open(p_file_name,ios::in);

   string buffer,token;
   int token_pos;
   token_count=0;

   if( file_is_obj.is_open())
   {
      while( !file_is_obj.eof() )
      {
         if(token_count >= FILE_NO_OF_ROWS)
         {
            break;
         }

         buffer.clear();

         token_pos=0;

         std::getline(file_is_obj,buffer);
         for( int iter=0;  token_pos  != -1 || iter >= FILE_NO_OF_COL ; iter++)
         {
            token.clear();

            token_pos=buffer.find(delimiter,0);
            token=buffer.substr(0,token_pos);
            if( !token.empty() )
            {
               buffer.erase(0,token_pos+strlen(delimiter));
               file_content[token_count][iter] = new char[token.length()+1] ;

               memset(file_content[token_count][iter],'\0',(token.length()+1)*sizeof(char));
               token.copy( file_content[token_count][iter], token.length(), 0);
            }
         }
         token_count++;
      }
      token_count-=1; // Token incremented for reading end of file
   }
   else
   {
      printf("\nFile not found (or) Error in opening the file");
      return false;
   }

   return true;
}


texts:
I know I should be using vectors, but I want to learn something.

Please review it and point out any mistakes. Thank you. Here it is:

template< typename T >
class Table2D {
public:
    Table2D( unsigned int sizeX,
             unsigned int sizeY )
            : m_sizeX( sizeX )
            , m_sizeY( sizeY )
    {
        try {
            m_2DTable = new T[ m_sizeX * m_sizeY ]( );
        }
        catch( std::bad_alloc ) {
            std::cerr << "bad_alloc...\n";
        }
    }
    ~Table2D( ) { delete [ ] m_2DTable; }
private:
    unsigned int m_sizeX;
    unsigned int m_sizeY;
    T* m_2DTable;
public:
    void set( unsigned int x, unsigned int y, T val ) {
        m_2DTable[ x + ( y * m_sizeX ) ] = val;
    };
    T get( unsigned int x, unsigned int y ) {
        return m_2DTable[ x + ( y * m_sizeX ) ];
    };
};

Usage example:

Table2D< unsigned int > ui_2DTable( 50, 50 );
ui_2DTable.set( 10, 20, 50 );
std::cout << ui_2DTable.get( 10, 20 ) << std::endl;

Table2D< float > f_2DTable( 3, 7 );
f_2DTable.set( 1, 4, 1.75 );
std::cout << f_2DTable.get( 1, 4 ) << std::endl;


texts:
I am writing a game via SFML. In difference places I want to use loaded fonts. So I decided to write the fonts loader, so that load fonts only one time and use them in the future from class. My code:

enum class FontsID
{
    PIXEBOY,
    DIGITAL7
};

class FontObject
{
public:
    FontObject::FontObject(const std::string &texturePath)
    {
        font->loadFromFile(texturePath);
    }
    std::shared_ptr<sf::Font> font = std::make_shared<sf::Font>();
};

class FontsLoader
{
public:
    static FontsLoader &getInstance()
    {
        static FontsLoader instance;
        return instance;
    }
    const std::shared_ptr<sf::Font> getFont(FontsID fontID) const
    {
        return allFonts[static_cast<int>(fontID)].font;
    }

private:
    FontsLoader()
    {
        allFonts.push_back(FontObject("data/fonts/pixeboy.ttf"));
        allFonts.push_back(FontObject("data/fonts/digital-7.ttf"));
    }
    std::vector<FontObject> allFonts;
};
static FontsLoader &fontsLoader = FontsLoader::getInstance();

I don't think using an enum is good solution, for example, enum count may be more or less than allFonts vector items count, adding in the constuctor in proper sequence also not good , but fontsObject.getFont(FontsID::PIXEBOY); is convenient for me, I will never confuse fonts name. Is there a better way?


texts: LINQ approach to flatten Dictionary to string

texts:
I have a Dictionary<string,string> and want to flatten it out with this pattern:

{key}={value}|{key}={value}|{key}={value}|

I tried with a LINQ approach at first but couldn't solve it, so I ended up writing an extension method like this:

public static string ToString(this Dictionary<string,string> source, string keyValueSeparator, string sequenceSeparator)
{
  if (source == null)
    throw new ArgumentException("Parameter source can not be null.");

  var str = new StringBuilder();
  foreach (var keyvaluepair in source)
    str.Append(string.Format("{0}{1}{2}{3}", keyvaluepair.Key, keyValueSeparator, keyvaluepair.Value, sequenceSeparator));
  var retval = str.ToString();
  return retval.Substring(0,retval.Length - sequenceSeparator.Length); //remove last  seq_separator
}

Is it possible to solve this with LINQ?


texts: Is this password hashing acceptable for a custom MembershipProvider?

texts:
I'm creating a custom MembershipProvider for an ASP.NET MVC5 application and am wanting to know if this code is acceptable for creating hashed and salted passwords.  Is there anything I can do to improve it?

EncodePassword is passed the plaintext password from the override functions.

I picked 38 hash iterations arbitrarily and I honestly don't know if it's even necessary or valuable. Should it be higher?

_machineKey is auto generated by ASP.NET for each machine/VM the software runs on. I will probably remove this to allow a distributed system and use an application key instead. Though, looking through the documentation for HMACSHA1, would it even seem like this key may be necessary?

EncodePassword() result will be stored directly in the database.

    private bool CheckPassword(string password, string dbpassword)
    {
        var salt = GetSalt(dbpassword);
        password = EncodePassword(password, salt);

        if (password == dbpassword)
        {
            return true;
        }

        return false;
    }

    private string EncodePassword(string password, string salt = "")
    {
        if (string.IsNullOrEmpty(salt))
            salt = CreateSalt();
        var hash = new HMACSHA1 { Key = HexToByte(_machineKey.ValidationKey) };
        var bytePassword = hash.ComputeHash(Encoding.Unicode.GetBytes(password + salt));

        for (int i = 0; i < 38; i++)
        {
            bytePassword = hash.ComputeHash(bytePassword);
        }
        return String.Format("{0}:{1}", bytePassword, salt);
    }

    private static string CreateSalt(int size = 64)
    {
        using (var rng = new RNGCryptoServiceProvider())
        {
            var buff = new byte[size];
            rng.GetBytes(buff);
            return Convert.ToBase64String(buff);
        }
    }

    private static string GetSalt(string password)
    {
        var passwordSplit = password.Split(':');
        if (passwordSplit.Length == 2)
        {
            return passwordSplit[1];
        }

        return String.Empty;
    }


texts: Tag helper to add class if the model is invalid

texts:
I need to add a specific class to the input if the model is invalid

ValidationErrorClassTagHelper.cs

[HtmlTargetElement("input", Attributes = ValidationForAttributeName + "," + ValidationErrorClassName)]
public class ValidationErrorClassTagHelper : TagHelper
{
    private const string ValidationForAttributeName = "validation-for";

    private const string ValidationErrorClassName = "validationerror-class";

    [HtmlAttributeName(ValidationForAttributeName)]
    public ModelExpression For { get; set; }

    [HtmlAttributeName(ValidationErrorClassName)]
    public string ValidationErrorClass { get; set; }

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        ViewContext.ViewData.ModelState.TryGetValue(For.Name, out ModelStateEntry entry);
        if (entry != null && entry.Errors.Any())
        {
            output.AddClass(ValidationErrorClass, HtmlEncoder.Default);
        }
    }
}

AccountViewModels.cs

using System.ComponentModel.DataAnnotations;

namespace AccountViewModels
{
    public class LoginViewModel
    {
        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }
}

Login.cshtml

@model LoginViewModel

<form method="post" asp-action="Login">
    <input asp-for="Email" validation-for="Email" validationerror-class="is-invalid"/>
    <input asp-for="Password" validation-for="Password" validationerror-class="is-invalid"/>
    <button type="submit" class="btn btn-primary">Login</button>
</form>

Generated html is the email is invalid for example

<input class="input-validation-error is-invalid" type="text" data-val="true" data-val-required="The Email field is required." id="Email" name="Email" value="">

Is the good way to do this ?
Is there a native way to do that using Asp.Net Core 2?


texts: Handling newly devices added to or removed from a list

texts:
I have two lists that I need to intersect. This is what I'm doing.

    var dfuDevices = _dfuMonitor.GetDevices();

    // new devices
    dfuDevices.Except(Devices).AsParallel().ForAll(device => {
        if (device.GetType() == typeof(DFUDeviceModel)) {
            OnDfuDeviceDetected(device);
        }
    });

    // removed devices
    Devices.Except(dfuDevices).AsParallel().ForAll(device => {
        if (device.Equals(ConnectedDevice))
            Disconnect();

        if (device is DFUDeviceModel)
            OnDfuDeviceRemoved(device);
    });

    // refresh list
    Devices = Devices.Intersect(dfuDevices);

I need to react accordingly to each item that is either removed or added. Is there any way to reduce this code?


texts: Show first n elements of array, and count elements not shown

texts:
This code mimics the "likes" tooltip from Facebook.

Given an array with the list of users that liked the content, it shows the first n users and displays a final item with the count of the users not shown.

It works as expected, but I'm sure it could be better written.

<?  if ($count = $this->likes->count()) {
        $visible = 12;
        $hidden = $count > $visible ? $count - $visible : 0;
?>

<?      $r = 0;
        foreach ($this->likes as $like) {
?>
            <?= $like->name ?>
<?          $r++;
            if ($r >= $visible) { break; };
        }
        if ($count > $visible) {
?>
            and <?= $hidden ?> more&hellip;
<?      } ?>

<?  } ?>

Edit: Removed revised code after reading this meta post.


texts: Validate URL with Regex and java.net.URL

texts:
I'm writing a URL validator. Firstly, it checks for special characters in the input. Secondly, it adds 'http://' and checks for validity.

    /* Returns true if url is valid */
    private static boolean isValidURL(String url) {
        boolean containsSpecialCharacters = specialCharactersExists(url);
        if ( !containsSpecialCharacters ) {
            /* Try creating a valid URL */
            try {
                new URL(String.format("%s%s", "http://", url)).toURI();
                return true;
            } catch (Exception e) {
                /* Not a valid URL */
            }
        }
        return false;
    }

    /* Returns true if url contains special characters */
    private static boolean specialCharactersExists(String input) {
        Pattern regex = Pattern.compile("[^A-Za-z0-9.-]");
        Matcher matcher = regex.matcher(input);
        return matcher.find();
    }

This serves my purpose. I'm seeking advice on how to improve the code (especially the Regex part)


texts: Finding the root of a function by Bisection Method

texts:
The program has to look for a root in an interval [a,b]. The root should be declared with a certain accuracy eps. I.e it should look for a part-interval in [a,b], which has the length of eps.

The bisection algorithm should be:

Save the interval boundaries
Look if [a,b] has a root. (original given interval)
look if a-b < eps. If yes, part-interval found.
If no, divide [a,b] in half and continue with point 2. etc.

(We can assume that there is already a root in the given original interval [a,b])

I've tested it with following functions:

log x + 2

x*x*x

-3.*x*x + x + 2.

Are there any improvements possible or did I make a big mistake?

Bisection.cpp

#include "Bisection.hpp"
#include <cmath>

using namespace std;

void bisection(std::vector<double>& interval, double eps) {
  double a;
  double b;
  double c;

  a = interval[0];
  b = interval[1];

  if (b - a < eps) // interval already 'found'
  {
    return;
  }

  do
  {
    c = (a + b) / 2.0;

    if (f(c) == 0)
    {
      a = c;
      b = c;
    }
    else
    {
      if (f(a) * f(c) > 0)
      {
        a = c;
      }
      else
      {
        b = c;
      }
    }

  } while (f(c) != 0 || b - a > eps);

  /*found part-interval with the length of < eps*/
  interval[0] = a;
  interval[1] = b;
}


texts:
I've an IEnumerable<T> source which takes time to generate each item. Once an item is generated, I want to cache it to avoid recomputing the same thing. I want to separate out caching logic from original source.

A few things that bother me are:

Where should I have _cache? In CachedEnumerable or CacheEnumerator?
Thread safety in adding into cache.
Reinventing? Any existing .NET or other library which does this.
Why Dispose in IEnumerator? Should I be doing something there? _cache nuke?

class CachedEnumerable<T> : IEnumerable<T>
{
    private IList<T> _cache = new List<T>();
    IEnumerator<T> _cacheEnumerator = null;
    IEnumerable<T> _source = null;

    public CachedEnumerable(IEnumerable<T> source)
    {
        _source = source;
        _cacheEnumerator = _source.GetEnumerator();
    }

    public IEnumerator<T> GetEnumerator()
    {
        return new CachedEnumerator<T>(_cache, _cacheEnumerator);
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

class CachedEnumerator<T> : IEnumerator<T>
{
    private IList<T> _cache;
    private IEnumerator<T> _source;
    private T _current;
    private int _index;
    private bool _moveNextStatus;

    public CachedEnumerator(IList<T> cache, IEnumerator<T> source)
    {
        _cache = cache;
        _source = source;
        Reset();
    }

    public T Current
    {
        get
        {
            if (_moveNextStatus)
            {
                return _current;
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
    }

    public void Dispose()
    {
        _source.Dispose();
    }

    object System.Collections.IEnumerator.Current
    {
        get { return Current; }
    }

    public bool MoveNext()
    {
        _moveNextStatus = _MoveNext();
        return _moveNextStatus;
    }

    private bool _MoveNext()
    {
        _index++;

        if (_index < _cache.Count)
        {
            _current = _cache[_index];
            return true;
        }
        else
        {
            if (_source.MoveNext())
            {
                _current = _source.Current;
                _cache.Add(_current);
                return true;
            }
            else
            {
                return false;
            }
        }
    }

    public void Reset()
    {
        _index = -1;
        _current = default(T);
        _moveNextStatus = false;
    }
}


texts: Checking number of messages in jms queue code

texts:
I need to check number of messages in a jms queue for that i am using queuebrowser.
Actually i have 2 queues. I check if there are more then 10 messages in second queue then the first queue should not send messages to the second queue.

This is my code snippet

            connection = connectionFactory.createConnection();

            Queue queue = (Queue) initialContext.lookup(inputQueue); // this is the first queue (named iniputQueue)

            session = connection.createSession();

                consumer = session.createConsumer(queue);

            // change code for browsing queue
            Queue senderqueue = (Queue) initialContext
                    .lookup(senderQueue);
            QueueBrowser queueBrowser = session.createBrowser(senderqueue); //this is second queue named senderQueue

            connection.start();
//by queuebrowser i check if messages in second queue is more then 10 then do  //not send the message
            Enumeration e = queueBrowser.getEnumeration();
            int numMsgs=0;
            // count number of messages
            while (e.hasMoreElements()) {
                numMsgs++;
                if(numMsgs>10){
                    checkFlag=false;
                    break;
                }else{
                    checkFlag=true;
                }
            }

            LOG.debug("checkflag is" +checkFlag);

            if (checkFlag) {

                ObjectMessage objectMessage = (ObjectMessage) consumer
                        .receive(1);

                if (objectMessage != null) {
                    objectMessage.acknowledge();
                    //
                    LOG.debug("sending one batch out");
                    InputJSON inputJson = (InputJSON) objectMessage
                            .getObject();

                    SendService messageService = new SendService();

                    messageService.processInputFromQueue(inputJson);

                }

            }

the above code is called by a schedular every 2 secs which keeps checking the sender queue and based on that sends message out from input queue.

Is there any better way to do this..


texts: Search rows in dataframe corresponding to a value in R - Performance & Scalability

texts:
Overview of the Question
I would like to ask for performance/scalability feedback on an R function that I recently wrote. I have a large 4-column dataframe (the lookup_dataframe; i.e., output of a simulation study). The first column contains an integer value and the other three columns parameter values that correspond to that integer value.
I have a second dataframe (data), that contains a column of input values. For each input value, I want to look up (from the lookup_dataframe) a possible combination of parameters that led to that input value.
Create some sample data
# Load packages
library(furrr)
#> Loading required package: future
library(tidyverse)

# Set amount of cores
plan(multisession, workers = 4)

# Set seed
set.seed(123)

# Create `data`
data <- data.frame(input = raster::sampleInt(n = 800, size = 1000, replace = TRUE)) %>%
  mutate(status = sample(0:1, n(), replace = TRUE),
         factor = sample(c("A", "B"), n(), replace = TRUE))

# Create `lookup_dataframe`
lookup_dataframe <- data.frame(value = rep(1:800, each = 2500),
                               param_A = rnorm(n = 2e6),
                               param_B = rnorm(n = 2e6),
                               param_C = rnorm(n = 2e6))

Write function to look up data
I wrote a function that takes an input value, filters the lookup_dataframe on that value and randomly selects a row. The row then contains the value + the three parameters.
func_input_to_param <- function(input){
  lookup_dataframe %>%
    filter(input == value) %>%
    select(-value) %>%
    sample_n(size = 1, replace = TRUE) %>%
    flatten_dbl()
}

Map function to input data
Finally, I map the function to the input data, stitch both dataframes together, and the job is done! Note, I am using the furrr package with the future_map function to perform the mapping in parallel.
param_dataframe <- future_map(.x = data$input,
                              .f = func_input_to_param,
                              .progress = TRUE, .options = furrr_options(seed = TRUE))

param_dataframe <- do.call(rbind, param_dataframe) %>%
  as_tibble(.name_repair = ~ c("param_A", "param_B", "param_C")) %>%
  cbind(data, .)

head(param_dataframe, 5)
#>   input status factor    param_A    param_B    param_C
#> 1   231      0      A  0.4533840 -0.4965135 -0.3215218
#> 2   631      1      A  1.1109426  0.8285732 -0.6635507
#> 3   328      1      A  0.9866890 -1.5464006  0.9079893
#> 4   707      0      B -1.8231198 -1.2731512  1.1951422
#> 5   753      1      B -0.5865885 -0.6276842  1.3558658

Feedback request
First of all, I really appreciate any feedback you can provide (of course, also not performance-related)! But I wanted to ask specifically for feedback on the code's performance and scalability. For example, if the input data has a size=1000 the code is fast enough. However, input size=10e6 takes forever to run. How am I able to speed up this code?
It feels like a straightforward problem, so I was wondering if there are smarter ways to approach this problem?
Created in 2021 by the reprex package (v1.0.0)


texts: Querying all items that are in a many-to-many relationship with a child of an object

texts:
I have the following Django models setup:

class Publication(models.Model):
    value=models.CharField(max_length=255, unique=True)

class Article(models.Model):
    filename = models.CharField(max_length=255)
    publication = models.ForeignKey(Publication, on_delete=models.CASCADE)

class Image(models.Model):
    name = models.CharField(max_length=255)
    articles = models.ManyToManyField(Article)

I wanted to add an 'images' property to the Publication model. I have implemented it like this

@property
def images(self):
    images = []
    for article in self.article_set.all():
        images += list(article.images.all())
    return list(set(images))

This works. I also considered trying something like

return Images.objects.filter(articles__publication=self)

But I don't think that I can do this because then I have to define Images above Publications, which won't work with Articles and Images.

Is there a way for me to improve this query to handle less of the filtering in application logic and more of it in the database?


texts: Framed external link redirect - vBulletin

texts:
I'm just looking for some review for my code.  This is a script that checks for outbound links in posts in vBulletin forums, and if it is an external link it will redirect to a template which will load the external site in an iFrame that I also coded, inspired by themeforest and stumbleupon's way of showing external links.

This is my first PHP script on my own that is a little more advanced.  I'm only use to the basics, so any critique is good critique, it's the only way I can learn.

I don't even know if I went about doing this correctly, but it seems to work how I'm wanting currently.  Let me know what I can do differently.

To get an idea of this you can see it in action - Here

HTTPS links don't work, however, I still want them redirected with this so all outbound links on my site will derive from the same page, so I included a button for if a certain page won't load you can click that button and it will take you to the page.

$curdir = getcwd ();
chdir('./');
define('NO_REGISTER_GLOBALS', 1);
define('THIS_SCRIPT', 'drc-redirect');
$globaltemplates = array('drc_redirect');
require_once('./global.php');

if ($_GET) {
    foreach ($_GET as $key => $value) {
        if ($key=="l") {
            $url1 = $value;
        }
        else {
            $url2 = "&". $key. "=". $value;
        }
    }

    $out = strip_tags($url1. $url2);
}

$site = parse_url($_SERVER['HTTP_HOST']);
$site = $site[path];
$url = parse_url($out);

if ($url[scheme] == "http" OR "https" && $url[host]) {
    if ($site == $url[host]) {
        Header( "Location: ". $out );
    }
    else {
        eval('print_output("' . fetch_template('drc_redirect') . '");');
    }
}

I would like to add a few things to it still but first wanted to get some suggestions on my code.


texts:
Here is my code in Ruby that shows the look-and-say sequence. It shows correct result, but my teacher said, that I could actually make it better. Can you tell me what the flaws are there in my code?

In the input I tell how many sequence elements I want to see.
For example I type

5

and get:

1
11
21
1211
111221

class NumberSequence

  def self.start
    puts 'Enter the number of elements in sequence'
    count = gets.to_i - 1
    number = "1"
    times = 1
    puts number
    count.times do
        result = ""
        c = number[0]
        number = number[1..-1]+" "
        number.chars.each do |char|
       if(c!=char)
          result+= times.to_s+c
          times = 1
          c = char
      else
        times+=1
      end
    end
    number = result
    puts(result)
  end
end
end

NumberSequence.start


texts:
A while ago, I was working on a chess project with a couple other people.  In the end, I wrote all but a couple of the lines of code, including these:

class Piece(list):

    def IsValidMovePattern(self, FromCoord, ToCoord):
        print(self, "Validation not done")
        return False

class King(Piece):

    def IsValidMovePattern(self, FromCoord, ToCoord):

        move = [abs(ToCoord[0] - FromCoord[0]), abs(ToCoord[1] - FromCoord[1])]

        # One square in any direction
        if move[0] <= 1 and move[1] <= 1:
            return True

        # Castling - AND has higher priority than OR
        if move[0] == 0 and move[1] == 2:
            if self[1] == Player(1) and FromCoord == (0, 4) or self[1] == Player(2) and FromCoord == (7, 4):
                return True

        return False

class Queen(Piece):

    def IsValidMovePattern(self, FromCoord, ToCoord):

        move = [abs(ToCoord[0] - FromCoord[0]), abs(ToCoord[1] - FromCoord[1])]

        # Diagonal and straight moves
        if move[0] == move[1] or move[0] == 0 or move[1] == 0:
            return True

        return False

class Rook(Piece):

    HasMoved = False

    def IsValidMovePattern(self, FromCoord, ToCoord):

        move = [ToCoord[0] - FromCoord[0], ToCoord[1] - FromCoord[1]]

        if move[0] == 0 or move[1] == 0:
            return True

        return False

class Knight(Piece):

    def IsValidMovePattern(self, FromCoord, ToCoord):

        move = [abs(ToCoord[0] - FromCoord[0]), abs(ToCoord[1] - FromCoord[1])]

        # L-shaped moves
        if move[0] == 1 and move[1] == 2 or move[0] == 2 and move[1] == 1:
            return True

        return False

class Bishop(Piece):

    def IsValidMovePattern(self, FromCoord, ToCoord):

        move = [abs(ToCoord[0] - FromCoord[0]), abs(ToCoord[1] - FromCoord[1])]

        # Can only move diagonal
        if move[0] == move[1]:
            return True

        return False

class Pawn(Piece):

    # Set to True when a pawn moves two squares past
    # Pawn must be on square 3 for PlayerOne or square 4 for PlayerTwo
    EnPassant = False

    def IsValidMovePattern(self, FromCoord, ToCoord):

        move = [ToCoord[0] - FromCoord[0], ToCoord[1] - FromCoord[1]]

        # Player(1) capture
        if self[1] == Player(1) and abs(move[1]) == move[0] == 1:
            return True

        # Player(2) capture
        if self[1] == Player(2) and abs(move[1]) == 1 and move[0] == -1:
            return True

        # Player(1) first move
        if self[1] == Player(1) and FromCoord[0] == 1 and move[1] == 0 and move[0] == 2:
            return True

        # Player(2) first move
        if self[1] == Player(2) and FromCoord[0] == 6 and move[1] == 0 and move[0] == -2:
            return True

        # Player(1) move
        if self[1] == Player(1) and move[1] == 0 and move[0] == 1:
            return True

        # Player(2) move
        if self[1] == Player(2) and move[1] == 0 and move[0] == -1:
            return True

        return False

This is called like this (where self is similar to this in C#; it is being called from the Board class):

if not self.data[FromCoord[0]][FromCoord[1]].IsValidMovePattern(FromCoord, ToCoord):

FromCoord and ToCoord are tuples (similar to immutable arrays) like (FromX, FromY).

Is this a good implementation?  Would this be a slow implementation, or is it reasonable?  The rest of the code (with Checkmate and the AI incomplete) can be found at Github.


texts: Represent pairs of nonnegative integers using 2^a * 3^b

texts:
Given the following exercise:

  Exercise 2.5

  Show that we can
  represent pairs of nonnegative
  integers using only numbers and
  arithmetic operations if we represent
  the pair a and b as the integer that
  is the product 2^a * 3^b. Give the
  corresponding definitions of the
  procedures cons, car, and cdr.

I wrote the following:

(define (cons a b) (* (expt 2 a)
                      (expt 3 b)))
(define (car x)
  (if (= 0 (remainder x 3))
      (car (/ x 3))
      (/ (log x)
         (log 2))))

(define (cdr x)
  (if (= 0 (remainder x 2))
      (cdr (/ x 2))
      (/ (log x)
         (log 3))))

What do you think?


texts:
My task is to find the indices of a vector of booleans that are true. I'm coming from a JavaScript background and would like to learn how to write this in idiomatic Rust.

fn main() {
    let fold_func = |acc: Vec<usize>, p: (usize, &bool)| -> Vec<usize> {
        if *p.1 {
            let mut clone = acc.clone();
            clone.push(p.0);
            clone
        } else {
            acc
        }
    };
    let v = vec![true,false,true];
    let result = v.iter().enumerate().fold(vec![], fold_func);
    print!("{:?}", result) //[0, 2]
}


texts:
How can I avoid so many if statements?

//Radio Button toggle

if (five.isSelected() == true) {
            one.setSelected(false);

    private class JButtonListner implements ActionListener {

//As my code has 4 options (1,5,+,-) to change the label, i have done 4 if else statments. is it possible to avoid such mess?

        public void actionPerformed(ActionEvent e) {
            if (e.getSource().equals(plus) && five.isSelected() == true) {
                count += 5;
                label.setText(Integer.toString(count));

            } else if (e.getSource().equals(minus) && five.isSelected() == true) {
                count -= 5;
                label.setText(Integer.toString(count));

            } else if (e.getSource().equals(minus) && one.isSelected() == true) {
                count --;
                label.setText(Integer.toString(count));

            } else if (e.getSource().equals(plus) && one.isSelected() == true) {
                count++;
                label.setText(Integer.toString(count));
            }
        }


texts: Faster and cleaner SHA-1 leading zero histogram with Python

texts:
I've written a python code for finding the distribution of the leading zeros of SHA-1. Using random inputs and hashing-then-counting. Normally it is expected to fit the n/2^i curve where n is the number of trials. After this, a plot is drawn.
import hashlib
import random
import matplotlib.pyplot as plt

leading = [0] * 160

trials = 10000000000

for i in range(trials):

    randomInput= random.getrandbits(128)

    hasvalue = hashlib.sha1(str(randomInput).encode('ASCII')).hexdigest()

    b = bin(int(hasvalue, 16))
    c= b[2:].zfill(160)
    zeroes = str(c).index('1')
    leading[zeroes] = leading[zeroes] + 1

The most time-consuming part of this code is of course the SHA-1 calculation and we cannot do something for that except parallelization with pymp or some other library. What I'm not mostly unhappy here is the whole conversions between str, bin and back.
Any improvements for a cleaner code and little speed up?


texts: Parse backslash-delimited hierarchy path into separate columns

texts:
I have rows in a database table with a hierarchypath column. The values in the column are hierarchy paths with up to four levels:
HIERARCHYPATH
---------------------------------------------------
FACILITIES \ FIREHALL \ PLUMBING
FACILITIES \ PARK
ROADS \ GRASS/TURF BLVD MAINTENANCE
ROADS \ SIDEWALKS \ REPLACEMENT
FACILITIES \ PARKING - MAIN ST
RECREATION \ BANDSHELL \ PROPERTY \ BUILDING-GENERAL
FACILITIES

I've written a Jython 2.7 automation script that parses the levels at the \ delimiter and inserts the values into individual level columns:

CLASSL1
CLASSL2
CLASSL3
CLASSL4

#Example:
s = "FACILITIES \ FIREHALL \ PLUMBING"

col_prefix = "CLASSL"

#Note: The term "mbo" is an IBM Maximo concept.
#It can be thought of as the currently selected record in the application.

for i in range(0, 4):
    try:
        mbo.setValue(col_prefix + str(i+1), s.split(' \\ ')[i])
    except:
        #Null-out any existing values that were not overriden
        mbo.setValueNull(col_prefix + str(i+1))

HIERARCHYPATH                       CLASSL1       CLASSL2       CLASSL3      CLASSL4
--------------------------------    ----------    ----------    ----------   -----------
FACILITIES \ FIREHALL \ PLUMBING    FACILITIES    FIREHALL      PLUMBING     null

I'm relatively new to coding. How can the script be improved?


texts: What changes should I implement in my templated sorter class so that it performs efficiently?

texts:
I have a college assignment to implement a class called sorter, whose object is a sorted vector (the user is allowed to sort it by the method he/she desires). I have been able to implement it as following. Please review it and suggest me the changes I should make to make it efficient.

template <typename T>
class Sorter {
    std::vector<T> vector;
    int count(T* array) {
        register int i = 0;
        while (*(array + i)) {
            i++;
        }
        i--;
        return i;
    }
    void swap(T& t1, T& t2) {
        T temp = t1;
        t1 = t2;
        t2 = temp;
    }
    void bubbleSort() {
        for (int i = 0; i < vector.size(); i++) {
            for (int j = 0; j < vector.size() - 1; j++) {
                if (vector[j] > vector[j + 1]) {
                    swap(vector[j], vector[j + 1]);
                }
            }
        }
    }
    std::vector<T> mergeSort(std::vector<T> vec) {
        int begin = 0;
        int end = vec.size() - 1;
        auto combine = [=](std::vector<T> lv, std::vector<T> rv) {
            std::vector<T> retVec;
            int i = 0;
            int j = 0;
            while (i < lv.capacity() && j < rv.capacity()) {
                if (lv[i] < rv[j]) {
                    retVec.push_back(lv[i]);
                    i++;
                }
                else {
                    retVec.push_back(rv[j]);
                    j++;
                }
            }
            while (i < lv.capacity()) {
                retVec.push_back(lv[i]);
                i++;
            }
            while (j < rv.capacity()) {
                retVec.push_back(rv[j]);
                j++;
            }
            return retVec;
        };
        if (vec.size() == 1) {
            return vec;
        }
        int mid = (begin + end) / 2;
        auto it = vec.begin();
        std::vector<T> left = mergeSort(std::vector<T>(it, it + mid + 1));
        std::vector<T> right = mergeSort(std::vector<T>(it + mid + 1, vec.end()));
        return combine(left, right);
    }
    void sort() {
        std::cout << "Choose your option:" << "\n";
        std::cout << "1. bubblesort" << "\n";
        std::cout << "2. mergesort" << "\n";
        int op = 2;
        //std::cin >> op;
        switch (op) {
        case 1:
            bubbleSort();
            break;
        case 2:
            vector = mergeSort(vector);
            break;
        }
    }
public:
    Sorter() = delete;
    Sorter(std::vector<T> vec) : vector(vec) {
        sort();
    }
    Sorter(T* array) {
        int num = count(array);
        for (int i = 0; i < num; i++) {
            this->vector.push_back(*(array + i));
        }
        sort();
    }
    std::vector<T> getSorted() {
        return vector;
    }
};

The updated version is always available at this link


texts:
This is my first C++ program with classes, and I don't want to develop bad skills. It's very simple and consists of 3 files.  This is an exercise from a book, hence the name of the driver file.

Please tell me whether it's proper or not!

parity.cpp:

#include <iostream>
#include "parity.h"

void Parity::put(int number)
{
    numbers.push_back(number);
}

bool Parity::test(void)
{
    if (numbers.size() % 2 == 0)
        return true;
    else return false;
}

parity.h:

#ifndef PARITY_H_
#define PATITY_H_

#include <string>
#include <vector>

class Parity
{
    private:
        std::vector<int> numbers;
    public:
        void put(int number);
        bool test(void);
};

#endif

13_1.cpp

#include <iostream>
#include "parity.h"

int main()
{
    int number;
    bool odd_number;
    Parity parity_test;

    while(true)
    {
        std::cout << "Enter an integer: ";
        std::cin >> number;
        if (number == 0)
        {
            break;
        }
        else
        {
            parity_test.put(number);
            odd_number = parity_test.test();
            std::cout << odd_number;
        }
    }
    return 0;
}


texts:
I'm trying to retrieve all the nodes of a jstree and display the data on a textarea, this strange code is working fine, but the execution is very slow, it takes an average of ~3 seconds for the textarea receive the incoming data from the jstree, i would like to know if is there any way to improve the peformance

Dependencies: jQuery 3.3.1 and jsTree 3.3.5

  UPDATE: I made some improvements on the code by replacing the excessive event listeners with a single syncNodes() function

HTML :

<select id="sel_cmd" onchange="exec(this.value)">
    <option value=""># Select a command #</option>
    <option value="inclib">Include library</option>
</select>

A

B

C

<textarea id="jstree-code" cols="60" rows="10"></textarea>

JS file

// Initialize jstree
$("#jstree").jstree({
    core: {
        'check_callback': true
    }
});

// (FUNCTION) Create jstree nodes
function createNode(tree_id, parent_node, new_node_id, new_node_text, position) {
    $(tree_id).jstree("create_node", $(parent_node), {
        text: new_node_text,
        id: new_node_id
    }, position, false, false);
}

// Get all nodes on the jstree and send their data to textarea
function syncNodes() {
    $("#jstree-code").val("");
    var nodesArray = []
    $(
        $("#jstree").jstree("get_json", $("#jstree"), { flat: true })
    ).each(function(index, value) {
        var node = $("#jstree").jstree().get_node(this.id);
        var txt = node.text.trim();
        var lvl = node.parents.length;
        var idx = index;
        nodesArray += "text = " + txt + " // index = " + idx + " // level = " + lvl + "\n";
    });
    $("#jstree-code").val(nodesArray);
}

// ******************************

syncNodes();

function exec(op) {
    switch (op) {
        case "inclib":
            var lib = prompt("Library name:");
            createNode("#jstree", "#jstree", `${lib}`, `${lib}`, "last");
            syncNodes();
            break;
    }
}


texts:
I am new to programming and have been taking the time to learn C# by reading, doing some classes online for Unity, and using Youtube. I think you learn more from doing your own projects so I decided to write a program that asked the user to enter a movie they have not seen and then store the movie titles into a list and print out the movies they listed. I had problems getting it to take multiple movies but finally figured a way to do it but I believe there is a better way to write the program. So just asking general advice to improve upon what I have already written. Thank you.
 using System;
 using System.Collections.Generic;

 namespace MovieListProjectWithSwitch
 {
  internal class Program
  {
    private static void Main(string[] args)
    {
        Console.WriteLine("Enter a movie you want to see but have not seen it");
        var movieNotSeen = new List<string>();
        movieNotSeen.Add(Console.ReadLine());

        Console.WriteLine("Do you want to enter another movie? Y/N?");

        const string answerYes = "y";
        const string answerNo = "n";
        string userInput;

        while (true)
        {
            userInput = Console.ReadLine().ToLower();

            switch (userInput)
            {
                case answerYes:
                    {
                        Console.WriteLine("Enter your next movie you wish to add to the list");
                        movieNotSeen.Add(Console.ReadLine());
                        Console.WriteLine("Now the movies on your list are:");
                        Console.WriteLine();
                        foreach (var movie in movieNotSeen)
                            Console.WriteLine(movie);
                        Console.WriteLine();

                        Console.WriteLine("Enter another movie? Y/N?");
                        var userInput2 = Console.ReadLine().ToLower();
                        if (userInput2 == "y")
                        {
                            goto case answerYes;
                        }
                        else
                        {
                            goto case answerNo;
                        }
                    }

                case answerNo:
                    {
                        Console.WriteLine("Your movies in your list are:\n");
                        foreach (var movies in movieNotSeen)
                            Console.WriteLine(movies);
                        return;
                    }
            }
        }
    }
  }
 }


texts: Continually refresh game data using AJAX

texts:
I've been working with JavaScript and AJAX a lot in the past, and now I'm moving towards the backend and working with databases more. I want to update my game data in as close to real time as possible in JavaScript.

Here is what I have been doing to update the data as frequently as possible (I simplified it):

function updateData() {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.ontimeout = function (e) {
            // XMLHttpRequest timed out. Try sending another request
            updateData();
        };
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                // only keep the data after the leading { (in case errors are outputted) (SHOULD NOT HAPPEN)
                var data = this.responseText.slice(this.responseText.indexOf('{'));
                try {
                    data = JSON.parse(data); // we're expecting JSON data -- make this an object for us
                } catch (error) {
                    console.error("Error parsing data");
                }
                // handle data...
                // and repeat:
                updateData();
            }
        };
        xmlhttp.open("GET", "data_getter.php", true); // "?t=" + getTime() to endure that the data is not cached
        xmlhttp.send();
}
updateData();

I call the function updateData() once and then each time the previous request is received, the function gets ran again.

I am wondering, is there a better way to continually refresh data (or make the data on the game website as close to realtime as possible) than to send an AJAX request every time the previous one is received? This method means that there will be a delay of the time it takes for the server to load, but that isn't too much.

Is this the best practice? Or can you somehow open a connection to a PHP script that communicates with the server in realtime and not close the connection for the duration of the game?


texts:
For learning purposes, I made this little class which determines the Condorcet winner of a rank voting election (basically, a Condorcet winner is a candidate that would beat every other candidate in a head-to-head election).
This code does work, but I'd like to learn two-three things by posting it here:

Is this class written in a correct Pythonic way?
Do you see any ways to improve this code?
(bonus) If there are voting specialists among you, could you tell if that way of going through a Condorcet algorithm seems correct?

Condorcet.py:
import itertools

class Condorcet:
    """
    Gives Concorcet winner from a list of votes
    """
    def __init__(self, filename):
        self.candidates = set()
        self.scores = dict() # score for each permutation of two candidates
        self.results = dict() # winner of each pair of candidates
        self.winner = None # Condorcet winner of the election
        self.voters = list() # ranking of each voter
        self.filename = filename

    def process(self):
        self._get_data_from_file()
        self._build_dict()
        self._matches_candidates()
        self._elect_winner()
        return self.winner

    def _get_data_from_file(self):
        with open(self.filename, encoding='utf-8') as file:
            for lines in file:
                # currently hard-coding the number of candidates at 4
                # needs fixing but it's not my point here
                # (more a question for StackOverflow actually)
                (one, two, three, four) = lines.split(None, 4)
                self.voters.append((one, two, three, four))

    def _build_dict(self):
        """
        Builds a dictionary of scores
        for each permutation of two candidates
        """
        for voting in self.voters:
            for candidate in voting:
                self.candidates.add(candidate)
            for pair in list(itertools.permutations(voting, 2)):
                if pair not in self.scores:
                    self.scores[pair] = 0
                if voting.index(pair[0]) < voting.index(pair[1]):
                    self.scores[pair] += 1

    def _matches_candidates(self):
        """
        Analyses the dictionary of scores and
        gives the winner of every pair of candidates
        """
        for match in list(itertools.combinations(self.candidates, 2)):
            reverse = tuple(reversed(match))
            if self.scores[match] > self.scores[reverse]:
                self.results[match] = match[0]
            else:
                self.results[match] = match[1]

    def _elect_winner(self):
        """
        If a candidates is the winner against
        every other candidate, declares him the winner
        (Note: does not detect Condorcet cycles yet)
        """
        for candidate in self.candidates:
            candidate_score = 0
            for result in self.results:
                if candidate in result and self.results[result] == candidate:
                    candidate_score += 1
            if candidate_score == len(self.candidates) - 1:
                self.winner = candidate

execute_condorcet.py:
import Condorcet

condorcet = Condorcet.Condorcet('condorcet.txt')
winner = condorcet.process()
print(winner)

condorcet.txt:
# each line represents the ranking
# of candidates A, B, C and D
# by a unique voter

A B C D # this voter ranked A first, B second, C third, D fourth
C B D A
A B D C
C A D B
C B A D
C A B D

# and it goes on

and the winner could be C, beating :

A 4 votes to 2
B 4 votes to 2
D 5 votes to 1


texts:
My script pushes zeros to end of an int array. I'd like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.

def nonzero(a):
  ''' given an array of ints, push all zeros to the end '''
  zeros = [0 for i in range(a.count(0))]
  x = [ i for i in a if i != 0]
  x.extend(zeros)
  return(x)


texts: simple shared pointer implementation in single threaded environment

texts:
Update: The code below has some obvious problems, and it is not allowed to revise code in the original question, so I have to post a new question, the revised code is here.

std::shared_ptr has the potential problem that two pointer point to the same object but to different control blocks. And its atomic operation is pure overhead in a single threaded environment. So I wrote the following version to avoid these problems. This implementation also has the advantage that an empty pointer is the same size as a void *.

template <typename T>
struct ThreadUnsafeSharedPtr {

private:
    struct Pair {
        T data;
        size_t cnt;
        template <typename ... Args>
        Pair(Args && ... args): data(std::forward<Args>(args)...), cnt(1) {}
    };
    Pair *ptr;

public:
    template <typename ... Args>
    static ThreadUnsafeSharedPtr make(Args && ... args) {
        ThreadUnsafeSharedPtr p;
        p.ptr = new Pair(std::forward<Args>(args)...);
        return p;
    }

    ThreadUnsafeSharedPtr() : ptr(nullptr) {}

    ThreadUnsafeSharedPtr(const ThreadUnsafeSharedPtr & other) : ptr(other.ptr) {
        if (ptr && &other != this) {
            ++(ptr->cnt);
        }
    }
    ThreadUnsafeSharedPtr & operator=(const ThreadUnsafeSharedPtr & other) {
        ptr = other.ptr;
        if (ptr && &other != this) {
            ++(ptr->cnt);
        }
        return *this;
    }
    ThreadUnsafeSharedPtr(ThreadUnsafeSharedPtr && other) : ptr(other.ptr) {
        if (&other != this) {
            other.ptr = nullptr;
        }
    }
    ThreadUnsafeSharedPtr & operator=(ThreadUnsafeSharedPtr && other) {
        if (&other != this) {
            ptr = other.ptr;
            other.ptr = nullptr;
        }
        return *this;
    }

    ~ThreadUnsafeSharedPtr() {
        if (ptr) {
            if(--ptr->cnt == 0) {
                delete ptr;
            }
        }
    }
};


texts: Climbing the Leaderboard: HackerranK, Terminated due to timeout

texts:
I have implemented my solution and I thought it was pretty efficient and passes most of the cases but seems like it fails some of the test cases when the input size is very large. I basically push every item from the Alice's array to our array and sort it.I'd appreciate if somebody tell me how I could increase the efficiency get rid of the timeout error.

  Alice is playing an arcade game and wants to climb to the top of the leaderboard. Can you help her track her ranking as she beats each level? The game uses Dense Ranking, so its leaderboard works like this:

  The player with the highest score is ranked number 1 on the
  leaderboard. Players who have equal scores receive the same ranking
  number, and the next player(s) receive the immediately following
  ranking number. For example, four players have the scores 100, 90, 90,
  and 80. Those players will have ranks 1, 2, 2, and 3, respectively.

  When Alice starts playing, there are already n people on the
  leaderboard. The score of each player i is denoted by si. Alice plays
  for m levels, and we denote her total score after passing each level j
  as alicej. After completing each level, Alice wants to know her
  current rank.

  You are given an array, scores, of monotonically decreasing
  leaderboard scores, and another array, alice, of Alice's cumulative
  scores for each level of the game. You must print m integers. The jth
  integer should indicate the current rank of alice after passing the
  jth level.

To illustrate;

Score is :100 100 50 40 40 20 10

Alice is: 5 25 50 120

The output is going to be;

6,4,2,1

My implementation:

function ladder(arr1,arr2){
  while(arr2.length){
    let i=0
    let rank=1
    let score=arr2.shift()
    arr1.push(score)
    arr1.sort(function(a,b){
      return b-a
    })
    while(arr1[i]!==score){
      if(arr1[i]!==arr1[i+1]){
        rank++
      }

      i++
    }
    console.log(rank)
  }
}


texts:
https://leetcode.com/problems/sort-the-matrix-diagonally/

A matrix diagonal is a diagonal line of cells starting from some cell
in either the topmost row or leftmost column and going in the
bottom-right direction until reaching the matrix's end. For example,
the matrix diagonal starting from mat[2][0], where mat is a 6 x 3
matrix, includes cells mat[2][0], mat3, and mat[4][2].
Given an m x n matrix mat of integers, sort each matrix diagonal in
ascending order and return the resulting matrix.

my idea is to run as a BFS on the matrix. each cell visit top and right cells. to form a diagonal and sort it.
please review for performance. it took 30 mins to write the code. review this please as this is a coding interview.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace ArrayQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/sort-the-matrix-diagonally/
    /// </summary>
    [TestClass]
    public class MatrixDiagonalSortTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            int[][] input = { new[] { 3, 3, 1, 1 }, new[] { 2, 2, 1, 2 }, new[] { 1, 1, 1, 2 } };
            int[][] output = { new[] { 1, 1, 1, 1 }, new[] { 1, 2, 2, 2 }, new[] { 1, 2, 3, 3 } };
            var res = DiagonalSort(input);
            for (int r = 0; r < res.Length; r++)
            {
                CollectionAssert.AreEqual(output[r], res[r]);
            }

        }
        public int[][] DiagonalSort(int[][] mat)
        {
            Queue<Cell> Q = new Queue<Cell>();
            Q.Enqueue(new Cell(mat.Length-1, 0, mat[mat.Length-1][0]));
            while (Q.Count > 0)
            {
                List<Cell> tempList = new List<Cell>();
                int count = Q.Count;
                for (int i = 0; i < count; i++)
                {
                    var curr = Q.Dequeue();
                    tempList.Add(curr);
                    int newR = curr.r - 1;
                    int newC = curr.c;
                    if (newR >= 0)//go up
                    {
                        if (Q.FirstOrDefault(x => x.r == newR && x.c == newC) == null)
                        {
                            Q.Enqueue(new Cell(newR, newC, mat[newR][newC]));
                        }

                    }
                    newR = curr.r;
                    newC = curr.c + 1;
                    if (newC <= mat[0].Length - 1)//go right
                    {
                        if (Q.FirstOrDefault(x => x.r == newR && x.c == newC) == null)
                        {
                            Q.Enqueue(new Cell(newR, newC, mat[newR][newC]));
                        }
                    }
                }
                var listValues = new List<int>();
                foreach (var item in tempList)
                {
                    listValues.Add(item.v);
                }
                listValues.Sort();
                for (int i = 0; i < tempList.Count; i++)
                {
                    mat[tempList[i].r][tempList[i].c] = listValues[i];
                }
            }
            return mat;
        }
    }
    [DebuggerDisplay("r ={r}, c={c}, v={v}")]
    public class Cell
    {
        public Cell(int r1, int c1, int v1)
        {
            r = r1;
            c = c1;
            v = v1;

        }
        public int r { get; set; }
        public int c { get; set; }
        public int v { get; set; }
    }
}


texts: Checking if switch is checked and doing something with the data

texts:
How can I optimize this code?

for(var i = 0; i<people_to_save_parse.length;i++)
{
                if($(".ID-"+people[i].tdid).is(':checked')==true)
                {
                    people_to_save_parse[i].id = $(".ID-text-"+people[i].tdid).text();
                }else{
                    people_to_save_parse[i].id = "";
                }
                if($(".Name-"+people[i].tdid).is(':checked')==true)
                {
                    people_to_save_parse[i].firstname = $(".Name-text-"+people[i].tdid).text();
                }else{
                    people_to_save_parse[i].firstname = "";
                }
                if($(".Surname-"+people[i].tdid).is(':checked')==true)
                {
                    people_to_save_parse[i].lastname = $(".Surname-text-"+people[i].tdid).text();
                }else{
                    people_to_save_parse[i].lastname = "";
                }
}


texts:
In a moment of boredom, I decided to write two methods, one of which would create a query string, while the other would parse it, the constraint I imposed on myself being that each method could not exceed one statement. The result is by no means something I'd ever consider using at work or in my personal projects, for that matter; my reason for posting this question is that I'd like to know how, given the constraint I set for myself, the code could be improved on? Like, what's the best code you could write to solve the problem at hand - creating and parsing a query string - without having the two methods constitute more than 2 statements? I'm sure you could do it in a much more elegant manner, and I'm looking forward to any feedback coming my way!

const createQueryString = input => encodeURI(`?${Object.keys(input).map(name
=> `${name}=${input[name]}`).join('&')}`);

const queryString = createQueryString({
  name: 'Darrell',
  age: '3     2',
  nationality: 'Swedish'
});

console.log(queryString);

const parseQueryString = (input, obj = Object.create(null)) =>
decodeURI(input.slice(input.indexOf('?') + 1,
input.length)).split('&').map(entry => [
  [entry.split('=')[0]],
  [entry.split('=')[1]]
]).reduce((obj, query) => Object.assign(obj, {
  [query[0][0]]: query[1][0]
}), {});

const parsedQueryString = parseQueryString(queryString);

console.log(parsedQueryString);


texts:
In an attempt to clean out my picture collection I made a script to find all duplicate files

import datetime
import hashlib
import json
import typing
from collections import defaultdict
from pathlib import Path

def filesize(path: Path) -> int:
    """returns the filesize"""
    return path.stat().st_size

def hash_first(
    path: Path, hash_function=hashlib.md5, blocksize: int = 65536
) -> str:
    """returns the hash of the first block of the file"""
    with path.open("rb") as afile:
        return hash_function(afile.read(blocksize)).hexdigest()

def hash_all(path: Path, hash_function=hashlib.md5, blocksize=65536) -> str:
    """returns the hash of the whole file"""
    with path.open("rb") as afile:
        hasher = hash_function()
        buf = afile.read(blocksize)
        while buf:
            hasher.update(buf)
            buf = afile.read(blocksize)
    return hasher.hexdigest()

def compare_files(
    comparison: typing.Callable[[Path], typing.Hashable], duplicates: dict
) -> dict:
    """
    Subdivides each group along `comparison`
    discards subgroups with less than 2 items
    """
    results: defaultdict = defaultdict(list)
    for old_hash, files in duplicates.items():
        for file in files:
            results[(*old_hash, comparison(file))].append(file)

    return {
        filehash: files
        for filehash, files in results.items()
        if len(files) > 1
    }

def find_duplicates(
    rootdir: Path,
    comparisons: typing.Iterable[
        typing.Callable[[Path], typing.Hashable]
    ] = (),
):
    """
    Finds duplicate files in `rootdir` and its subdirectories

    Returns a list with subgroups of identical files

    Groups the files along the each of the comparisons in turn.
    Subgroups with less than 2 items are discarded.

    Each of the `comparisons` should be a callable that accepts a
    `pathlib.Path` as only argument, and returns a hashable value

    if `comparisons` is not defined, compares along:
        1. file size
        2. MD5 hash of the first block (65536 bytes)
        3. MD5 hash of the whole file
    """
    if not comparisons:
        comparisons = filesize, hash_first, hash_all

    duplicates = {(): filter(Path.is_file, rootdir.glob("**/*"))}
    for comparison in comparisons:
        duplicates = compare_files(comparison, duplicates)
    return [tuple(map(str, files)) for files in duplicates.values()]

if __name__ == "__main__":
    pic_dir = r"./testdata"
    results = find_duplicates(rootdir=Path(pic_dir))

    # print(json.dumps(results, indent=2))

    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    output_file = Path("./output") / f"{timestamp}.json"
    with output_file.open("w") as fh:
        json.dump(results, fh, indent=2)

Any remarks on this code?

The code is formatted with black (linelength 79), with mypy pylint and pylama as linters.

If I try to specify the dict as argument and return value to compare_files to typing.Dict[typing.Tuple[typing.Hashable, ...], typing.Iterable[Path]], mypy complains: Incompatible types in assignment (expression has type "Dict[Tuple[Hashable, ...], Iterable[Path]]", variable has type "Dict[Tuple[], Iterator[Path]]")


texts:
I've just started learning python and I tried making a tic tac toe game and would really appreciate it if I got some feedback. I know, my code isn't the best optimized but this is what I could come up with.

row1 = ['/','/','/']
row2 = ['/','/','/']
row3 = ['/','/','/']

def xsturn():
    row = input('X, which row?')
    place = input('X, which place?') - 1
    if row == 1:
        if row1[place] == '/':
            row1[place] = 'X'
        else:
            print 'Move not possible!'
            xsturn()
    elif row == 2:
        if row2[place] == '/':
            row2[place] = 'X'
        else:
            print 'Move not possible!'
            xsturn()
    elif row == 3:
        if row3[place] == '/':
            row3[place] = 'X'
        else:
            print 'Move not possible!'
            xsturn()

def osturn():
    row = input('O, which row?')
    place = input('O, which place?') - 1
    if row == 1:
        if row1[place] == '/':
            row1[place] = 'O'
        else:
            print 'Move not possible!'
            osturn()
    elif row == 2:
        if row2[place] == '/':
            row2[place] = 'O'
        else:
            print 'Move not possible!'
            osturn()
    elif row == 3:
        if row3[place] == '/':
            row3[place] = 'O'
        else:
            print 'Move not possible!'
            osturn()

def win():
    value = 0
    if row1[0] == row1[1] == row1[2]:
        if row1[0] != '/':
            value += 1
    elif row2[0] == row2[1] == row2[2]:
        if row2[0] != '/':
            value += 1
    elif row3[0] == row3[1] == row3[2]:
        if row3[0] != '/':
            value += 1
    elif row1[0] == row2[0] == row3[0]:
        if row1[0] != '/':
            value += 1
    elif row1[1] == row2[1] == row3[1]:
        if row1[1] != '/':
            value += 1
    elif row1[2] == row2[2] == row3[2]:
        if row1[2] != '/':
            value += 1
    elif row1[0] == row2[1] == row3[2]:
        if row1[0] != '/':
            value += 1
    elif row1[2] == row2[1] == row3[0]:
        if row1[2] != '/':
            value += 1
    return value

def printingrows():
    print row1
    print row2
    print row3

def game():
    while win() == 0:
        xsturn()
        printingrows()
        if win() == 1:
            print 'X won the game!'
            break
        else:
            osturn()
            printingrows()
            if win() == 1:
                print'O won the game!'
                break
game()


texts:
I recently took a self-assessment question to assess my Python ability for an online class. The problem was to return the frequency of a word occurring, as part of a tuple.

  Implement a function count_words() in Python that takes as input a
  string word_string and a number number_of_words, and returns the n most frequently-occurring words in word_string. The return value should be a list of tuples - the top n
  words paired with their respective counts [(, ), (,
  ), ...], sorted in descending count order.

  You can assume that all input will be in lowercase and that there will
  be no punctuations or other characters (only letters and single
  separating spaces). In case of a tie (equal count), order the tied
  words alphabetically.

  E.g.: print count_words("this is an example sentence with a repeated word example",3) Output: [('example', 2), ('a', 1), ('an', 1)]

def count_words(word_string, number_of_words):
  """
  take in a word string and return a tuple of the
  most frequently counted words

  word_string = "This is an example sentence with a repeated word example",
  number_of_words = 3
  return [('example', 2), ('This', 1), ('a', 1)]
  """
  word_array = word_string.split(' ')
  word_occurence_array = []
  for word in word_array:
    if word in word_string:
      occurence_count = word_array.count(word)
      word_occurence_array.append((word, occurence_count))
    else:
      # no occurences, count = 0
      word_occurence_array.append((word, 0))

  # dedupe
  word_occurence_array = list(set(word_occurence_array))

  # reorder
  # can also pass, reverse=True, but cannot apply `-` to string
  word_occurence_array.sort(key=lambda tup: (-tup[1], tup[0]))

  # only return the Nth number of pairs
  return word_occurence_array[:number_of_words]

You can then call this function:

count_words(word_string="this is an example sentence with a repeated word example", number_of_words=3)

which returns [('example', 2), ('a', 1), ('an', 1)]

I found the process of tuple sorting, quite tricky, and achieved it using word_occurence_array.sort(key=lambda tup: (-tup[1], tup[0])). I was wondering if there are any other improvements that I can make to my overall code.

I hope this is a reasonable question - I've tweaked the description and example so that I hope it's not too easily identifiable.