texts:
I just started learning Racket as my first lisp dialect so after getting used to the syntax I implemented the Recamán's sequence.

Apart from the style, I'd also like to know if my code is a linear iteration or not. I kind of get the idea but I don't know how to be sure it is.

#lang racket

(define (recaman-seq size)
  (define (recaman-iter curr-seq n goal)
    (if (= n goal)
        (reverse curr-seq)
        (cond
          [(and (= n 0) (empty? curr-seq))
           (recaman-iter (list n) (+ n 1) goal)]
          [else
           (define a (- (car curr-seq) n))
           (define b (+ (car curr-seq) n))
           (define is-new (not (member a curr-seq)))
           (cond
             [(and (positive? a) is-new)
              (recaman-iter (list* a curr-seq) (+ n 1) goal)]
             [else
              (recaman-iter (list* b curr-seq) (+ n 1) goal)])])))
  (recaman-iter '() 0 (+ size 1)))

(recaman-seq 10)


texts: node.js Syslog server recording to MS-SQL database

texts:
This 43 line program is designed to listen for Syslog messages on port 514 and record the messages to an MS SQL Server database table.

I would appreciate feedback from experienced node.js developers.

I am just starting to learn node.js.  I'm average at JavaScript, still getting my head around closures.  I am really struggling to get my head around the node.js event driven programming paradigm.

If I try to access the SQL server connection outside of the sql.open callback function, I get the error that the database connection is closed.

So for this reason I had to place the receive message and save it in database logic inside the sql.open callback function, which seems messy and counter-intuitive, but that is probably due to my not quite fully understanding the event driven model?

Anyway the code works (amazingly!) and seems to be quite efficient, saving many dozens of syslog messages per second to the local MS SQL database with negligible CPU impact...

Are there any fundamental flaws in this code, and any changes that should be made to improve it?

I guess I am amazed that this can be done in just one page of code.  node.js is very cool...

var dgram = require("dgram");
var server = dgram.createSocket("udp4");
var sql = require('msnodesql');

var conn_str = "Driver={SQL Server Native Client 11.0}; Server=.; Database=SYSLOG; UID=xxxxxxx; PWD=xxxxxxxx;";

// open the database connection
sql.open(conn_str, function (err, conn) {
    if (err) {
        console.log("error", err);
        return;
    }
    //database connection succeeded, log a mesage into the syslog.incoming table
    conn.queryRaw("insert into Incoming(Source,Message) values('LOCAL','node.js syslog server started')");

    //create an event listener for when a syslog message is recieved
    server.on("message", function (msg, rinfo) {
      //sanitise the data by replacing single quotes with two single-quotes
      var message = msg.toString().replace(/'/g, "''")
      var src = rinfo.address.toString().replace(/'/g, "''")
      var s = "insert into Incoming(Source,Message) values('"+src+"','"+message+"')";

      //send the SQL to the database
      conn.queryRaw(s, function (err, results) {
        if (err) {
            console.log(s);
            console.log(err);
            return;
        }
      });
    }); // end of server.on("message") listener

    //create an event listener to tell us that the has successfully opened the syslog port and is listening for messages
    server.on("listening", function () {
      var address = server.address();
      console.log("server listening " + address.address + ":" + address.port);

    });

    //bind the server to port 514 (syslog)
    server.bind(514);

});// end of sql.open()


texts: Processing a large number of files in a folder

texts:
I have a folder which contains lots of files. I need to write C# code that will open and read and display the content of it. Is this efficient code or should something be changed?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Text;

using System.Collections;

class Program
{
    static void Main()
    {
        var sw = Stopwatch.StartNew();
        ProcessRead().Wait();
        Console.Write("Done ");

        Console.WriteLine("Elapsed Time" + sw.ElapsedMilliseconds+"and"+sw.ElapsedTicks);
        Console.ReadKey();
    }

    static async Task ProcessRead()
    {

        string folder = @"Directory";

        string[] fileEntries = Directory.GetFiles(folder);
        int count = 0;

        foreach (string fname in fileEntries)

        {

            if (File.Exists(fname) == false)
            {
                Console.WriteLine("file not found: " + fname);
            }
            else
            {
                try
                {
                    count++;
                    string text = await ReadTextAsync(fname);
                    Console.WriteLine(text);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        Console.WriteLine(count);
    }

    static async Task<string> ReadTextAsync(string filePath)
    {

        using (FileStream sourceStream = new FileStream(filePath,
            FileMode.Open, FileAccess.Read, FileShare.Read,
            bufferSize: 4096, useAsync: true))
        {
            StringBuilder sb = new StringBuilder();

            byte[] buffer = new byte[0x1000];
            int numRead;
            while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
            {
                string text = Encoding.UTF8.GetString(buffer, 0, numRead);
                sb.Append(text);
            }

            return sb.ToString();
        }
    }
}


texts: Adding, removing, and changing user names and passwords in .htpasswd with PHP

texts:
Here is some code I wrote to add, remove, and change user names and passwords in .htpasswd with PHP:
function adduser($user, $pass) {

    try {

        $htpasswd = '.htpasswd';

        //$hash = '{SHA}'.crypt($pass, base64_encode($pass));

        $hash = crypt_apr1_md5($pass); //APR1-MD5

        $contents = $user . ':' . $hash;

        $lines = explode(PHP_EOL, file_get_contents($htpasswd)); // get .htpasswd

        print('
input:

'.print_r(implode(PHP_EOL, $lines),true).'
');

        $exists = false;

        foreach($lines as $line){

            $existing_user = explode( ':', $line );

            if ($existing_user[0] == $user) { //checks if user exists

                $contents = str_replace($line, $contents, $lines); //changes password for user

                $contents = implode(PHP_EOL, $contents);

                $exists = true;

                if ($pass == '') { // removes user if password is empty

                    $contents = str_replace($line, '', $lines); //removes user

                    $contents = array_filter($contents); // cleans empty space in array

                    $contents = implode(PHP_EOL, $contents);

                    $exists = true;

                }

            }

        }

        if ($exists == false) {

            $contents = implode(PHP_EOL, $lines) . PHP_EOL . $contents;
        }

        file_put_contents($htpasswd, $contents);

        print('
output:

'.print_r($contents,true).'
');

    }catch(Exception $e) {

        echo '
fail:
' . $e->getMessage();

    }

}

if(isset($_GET['user'])){

    adduser($_GET['user'], $_GET['pass']);

    echo '
success
';

}else{

    $htpasswd = '.htpasswd';

    $lines = explode(PHP_EOL, file_get_contents($htpasswd)); // get .htpasswd

    print('
.htpasswd:

'.print_r(implode(PHP_EOL, $lines),true).'
');

    echo '
no user set
';
}

I would love to streamline it and clean it up.


texts:
The goal of my assignment is simple:

  Write a program that converts a given text to "Pig Latin".  Pig Latin
  consists of removing the first letter of each word in a sentence and
  placing that letter at the end of the word.  This is followed by
  appending the word with letters "ay".

  Example

  Input: THIS IS A TEST
  Output: HISTAY SIAY AAY ESTTAY

I want to know if there is any way to write this part of the code in a different/better way:

foreach (string word in engword.Split())

Here is my full code:

string engword = textBox1.Text; //english word
            string pig1 = ""; //pig latin
            string pig2 = ""; //first letter
            string space = " ";
            string extra = ""; //extra letters
            int pos = 0; //position

           foreach (string word in engword.Split())
           {
               if (pos != 0)
               {
                   pig1 = pig1 + space;
               }

               else
               {
                   pos = 1;
               }

               pig2 = word.Substring(0,1);
               extra = word.Substring(1, word.Length - 1);
               pig1 = pig1 + extra + pig2 + "ay";

            }

            MessageBox.Show(pig1.ToString());
        }
    }
}


texts: Hackerrank challenge - Dictionaries and Maps

texts:
This is a solution for the Day 8 hackerrank.com challenge.  The basic idea of the challenge is to create a mapping of names to phone numbers based on the the given input, and later look up the phone numbers for certain names. If the entry exists, print it and its number. If it doesn't, print out "Not found"

Here's my solution:

n = gets.strip.to_i
phonebook = Hash.new

n.times do
    name = gets.strip
    number = gets.strip
    phonebook[name] = number
end

n.times do
    check_name = gets.strip
    if phonebook.has_key?(check_name)
        print "#{check_name}=#{phonebook[check_name]}"
        puts ""
    else
        puts "Not found"
    end
end

I was wondering about more efficient and elegant Ruby solution.  I'm not sure how big sample input was for some of those test cases, but Testcase #1,2,3 take up to 0.4s which seems a little bit too high for me.


texts:
This code is very large and seems quite confusing. I tried to refactor it to make it more readable and make the code seem less...(scroll below). However, I am not sure if this can be refactored more.

 TableTypeDescriptor baseDecriptor = base.CustomTypeDescriptor as TableTypeDescriptor;

        if (this.IsObjectBeingValidated)
            return baseDecriptor;

        if (base.CustomTypeDescriptor != null)
        {
            if (baseDecriptor.OldTableDescriptor != null && this.IsNewInCorrection && !this.IsReadOnly)
            {
                return base.CustomTypeDescriptor;
            }
            else if (this.Locked)
            {
                return base.CustomTypeDescriptor;
            }
            else if (this.ImportedDataMD5 != null && !this.IsReadOnly)
            {
                return base.CustomTypeDescriptor;
            }
            else
            {
                if (baseDecriptor.OldTableDescriptor != null)
                {
                    return baseDecriptor.OldTableDescriptor;
                }
                else
                    return base.CustomTypeDescriptor;
            }
        }

        return base.CustomTypeDescriptor;

I then refactored it as follows. Is it possible to refactor it more?

TableTypeDescriptor baseDescriptor = base.CustomTypeDescriptor as TableTypeDescriptor;

                if (base.CustomTypeDescriptor != null || !this.IsObjectBeingValidated)
                {
                    if ( (!this.IsReadOnly && (this.IsNewInCorrection || this.ImportedDataMD5 != null))  ||
                         this.Locked
                       )
                        baseDescriptor = base.CustomTypeDescriptor;
                    else
                    {
                        if (baseDescriptor.OldTableDescriptor != null)
                            baseDescriptor = baseDecriptor.OldTableDescriptor;
                        else
                            baseDescriptor = base.CustomTypeDescriptor;
                    }
                }

                return baseDescriptor;


texts:
A interesting challenge was brought to my attention: to "flip" an array. I thought it might be more convenient if its bounds were symmetrical, say [-N..N] instead of [0 .. 2N + 1].

Now I'm curious about what could be done to make this Array more mature. Say, like a Boost component.

#include <cassert>
#include <iostream>
#include <algorithm>

template <typename T, int LoBound, int HiBound> class Array {
  T arr_[HiBound - LoBound + 1];
public:
  Array()
  {
    std::fill(arr_, arr_ + sizeof(arr_) / sizeof(arr_[0]), T{});
  }
  Array(const Array& other)
    :arr_(other.arr_)
  {}
  Array(std::initializer_list<T> initList)
  {
    std::copy(initList.begin(), initList.end(), arr_);
  }
  T& operator[](int ix)
  {
    assert(ix >= LoBound && ix <= HiBound);
    return arr_[ix - LoBound];
  }
  const T& operator[](int ix) const
  {
    assert(ix >= LoBound && ix <= HiBound);
    return arr_[ix - LoBound];
  }
};

int main()
{
  enum {LoBound = -2, HiBound = 2};
  using A1D = Array<int, LoBound, HiBound>;
  Array<A1D, LoBound, HiBound> arr =
   { A1D{ 1,  2,  3,  4,  5},
     A1D{ 6,  7,  8,  9, 10},
    A1D{11, 12, 13, 14, 15},
    A1D{16, 17, 18, 19, 20},
    A1D{21, 22, 23, 24, 25} };
  for (int i = LoBound; i <= HiBound; ++i) {
    for (int j = LoBound; j <= HiBound; ++j) {
      std::cout << arr[-i][-j] << " ";
    }
    std::cout << "\n";
  }
  return 0;
}


texts:
I have the code below, which works successfully, and is used to parse, clean log files (very large in size) and output into smaller sized files. This would take about 12-14 mins to process 1 GB worth of logs (on my laptop). Can this be made faster? Could Dask or parallelism or asyncio or another help speed this up?
I am new to python and pandas, and I have googled around, but am totally confused and cant seem to adopt any of the examples I saw.
import os
import pandas as pd

asciireg = "[^\x00-\x7F]+"
emailreg = "^\w+(?:[-+.']\w+)*@\w+(?:[-.]\w+)*\.\w+(?:[-.]\w+)*$"

for root, dirs, files in os.walk('.', topdown=True):
    for file in files:
        try:
            for df in pd.read_csv(file, sep='\n', header=None, engine='python', quoting=3, chunksize=1200000):
                df = df[0].str.strip(' \t"').str.split('[,|;: \t]+', 1, expand=True).rename(columns={0: 'email', 1: 'data'})

                mask = (df.email.str.contains(emailreg, regex=True, na=False)) & (~df.data.str.contains(asciireg, regex=True, na=False))
                df2 = df[~mask].copy()
                df = df[mask].copy()
                df2[['email', 'data']].to_csv("errorfile", sep=':', index=False, header=False, mode='a', compression='gzip')
                del df2
                del mask

            for x in "abcdefghijklmnopqrstuvwxyz0123456789":
                df2 = df[df.email.str.startswith(x)]
                if (df.email.size > 0):
                    df2[['email', 'data']].to_csv(x, sep=':', index=False, header=False, mode='a')
        except Exception as e:
            print ("Error: ", file)
            print(str(e))
        else:
            os.remove(file)

Sample log file
"email1@foo.com:datahere2
email2@foo.com:datahere2
email3@foo.com datahere2
email5@foo.com;dtat'ah'ere2
wrongemailfoo.com
email3@foo.com:datahere2

Expected Output

$ cat e

email1@foo.com:datahere2
email2@foo.com:datahere2
email3@foo.com:datahere2
email5@foo.com:dtat'ah'ere2
email3@foo.com:datahere2

$ cat errorfile

wrongemailfoo.com


texts: Singletons with eager and lazy instantiation

texts:
I've found more than one implementation of the Singleton Pattern in Java (more like 5-6). I want to know if both of the following snippets of code (written by me) are valid implementations of Singleton Pattern in Java.

//Eagerly intialization
public final class LoggerEagerSingleton {

private static final LoggerEagerSingleton logger = new LoggerEagerSingleton();

private LoggerEagerSingleton() {
}

public static LoggerEagerSingleton getInstance() {
    return logger;
}
}

//Lazy Initialization
public final class LoggerLazySingleton {

private LoggerLazySingleton() {
}

public static LoggerLazySingleton getInstance() {
    return LazyHelper.logger;
}

private static class LazyHelper {
    private static final LoggerLazySingleton logger = new LoggerLazySingleton();
}
}


texts:
I'm looking for any possible improvements in terms of memory usage and speed, but really any advice is welcome.

  Problem statement:

  John has discovered various rocks. Each rock is composed of various
  elements, and each element is represented by a lower-case Latin letter
  from 'a' to 'z'. An element can be present multiple times in a rock.
  An element is called a gem-element if it occurs at least once in each
  of the rocks.

  Given the list of  rocks with their compositions, display the number
  of gem-elements that exist in those rocks.

  Input Format

  The first line consists of an integer, , the number of rocks.  Each of
  the next  lines contains a rock's composition. Each composition
  consists of lower-case letters of English alphabet.

  Constraints    Each composition consists of only lower-case Latin letters ('a'-'z').   length of each composition

  Output Format

  Print the number of gem-elements that are common in these rocks. If
  there are none, print 0.

My code: Essentially I build N lists of True or False values (since the number of times the same element appears doesn't matter), and at the end just "and" them two by two using reduce to end up with a final list of True values for the elements that were True in each rock, and then just sum up the True values.

import sys
from functools import reduce

# this is just to get test cases input
N = int(input())
strings = []
for i in range(N):
    strings.append(input())

# actual implementation starts here
lists = [[False] * 26 for i in range(N)]

for i in range(N):
    for c in strings[i]:
        # ord() gives the ASCII value of a character
        lists[i][ord(c) - ord('a')] = True

final_list = reduce(lambda x, y: [x[i] and y[i] for i in range(26)], lists)

print(reduce(lambda x, y: x + y, final_list))


texts: Remove redundancies in similar properties

texts:
I have a lot of redundancy here, but I am not sure how could I make it look shorter.
namespace Notan
{
    public class EquipmentSystem : ScriptableObject
    {
        public UnityEvent onUpdate = new UnityEvent();

        [SerializeField] private Weapon weapon1;
        public Weapon Weapon1
        {
            get => weapon1;
            private set
            {
                weapon1 = value;
                onUpdate?.Invoke();
            }
        }

        [SerializeField] private Weapon weapon2;
        public Weapon Weapon2
        {
            get => weapon2;
            private set
            {
                weapon2 = value;
                onUpdate?.Invoke();
            }
        }

        [SerializeField] private Accessory accessory1;
        public Accessory Accessory1
        {
            get => accessory1;
            private set
            {
                accessory1 = value;
                onUpdate?.Invoke();
            }
        }

        [SerializeField] private Accessory accessory2;
        public Accessory Accessory2
        {
            get => accessory2;
            private set
            {
                accessory2 = value;
                onUpdate?.Invoke();
            }
        }

        [SerializeField] private Shield shield;
        public Shield Shield
        {
            get => shield;
            private set
            {
                shield = value;
                onUpdate?.Invoke();
            }
        }

        [SerializeField] private Armor armor;
        public Armor Armor
        {
            get => armor;
            private set
            {
                armor = value;
                onUpdate?.Invoke();
            }
        }

    }
}
```


texts: Reset files in Git which show as modified but have no changes according to “git diff”

texts:
This seems to be working but also is quite horrendously slow and seems a little hacky to me.

IFS=$'\n'

for currentFile in $(git status | grep "modified:" | cut -c 14-)
do
    gitDiff=$(git diff "$currentFile")
    gitDiffStr="[$gitDiff]"
    if [ "$gitDiffStr" == "[]" ]
    then
        echo match
        echo git checkout "$currentFile"
        git checkout "$currentFile"
    fi
done


texts:
I've recently been working on a screen-sharing/remote desktop project in C# .NET Framework 4.5. How it works is when the start button is pressed, the client will send a command to the server to begin sending screenshots until the screen-sharing bool is false (i.e the 'Stop' button is pressed).

All data is prefixed with a byte identifying what command it is, and the following 4 bytes are used to measure the length of the packet.

My question is, should I be using a Thread or a Task for this job? I need one or the other, otherwise the client's UI freezes.

Below I am using a Thread:

private void ProcessCommand(byte command)
{
    if (command == Commands.StartRemoteDesktop && !Globals.screensharing)
        {
            new Thread(StartSharing).Start();
        }
}

private void StartSharing()
    {
        Globals.screensharing = true;
        while (Globals.screensharing)
        {
            Methods.SendCapture();
        }
    }

And over here is how it looks with a Task:

private void ProcessCommand(byte command)
{
    if (command == Commands.StartRemoteDesktop && !Globals.screensharing)
    {
        Task.Run(() =>
        {
            while (Globals.screensharing)
            {
                Methods.SendCapture();
            }
        });
    }
}

I'm unsure what would be the better option here.


texts:
I'm attempting to implement various data structures and algorithms to better learn C.  I would appreciate comments on style, correctness of the implementation, memory management, etc.

One specific question is how to address an error case where either the table or key is null in the hash function.  In get or rm I can use an unsigned return of 0 or 1 representing a boolean value.

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

typedef struct HashTable {
  size_t size;
  char ** buckets;
} HashTable;

HashTable * create_table(size_t size);
int hash_code(char * key, HashTable * ht);
char * get_val(char * key, HashTable * ht);
unsigned int set_val(char * key, char * val, HashTable * ht);
unsigned int rm_val(char * key, HashTable * ht);

//Bernstein's function uses INITIAL_VALUE of 5381 and M of 33;
unsigned int INITIAL_VALUE = 5381;
unsigned int M             = 33;

/*
 * Function which allocates a Hash table and
 * bucket array of specified size
 * @param size the size of the bucket array
 *
 */
HashTable * create_table(size_t size)
{
  HashTable * ht = (HashTable*)malloc(sizeof(*ht));
  ht->size    = size;
  ht->buckets = (char **)malloc(sizeof(char*) * size);
  return ht;
}

/*
 * Function which returns multiplicative hash of key, which is used as bucket
 * @param key pointer to key
 * @param ht HashTable structure
 *
 */
int hash_code(char * key, HashTable * ht)
{
  if (ht == NULL || key == NULL)
    return -1;

  unsigned int hash = INITIAL_VALUE; //seed
  unsigned int i;
  for (i=0;i<strlen(key);i++)
    hash = M * hash + key[i];

  return hash % ht->size;
}

/*
 * Function which gets a value from the hashtable, computes hash of key
 * and queries the buckets at idx of hash
 * @param key pointer to key
 * @param ht HashTable structure
 *
 */
char * get_val(char * key, HashTable * ht)
{
  if (ht == NULL || key == NULL)
    return NULL;

  unsigned int hash = hash_code(key,ht);
  char * val = ht->buckets[hash];
  if (val != NULL)
    return val;
  return NULL;
}

/*
 * Function which sets a value in the hashtable, computes hash of key
 * and queries the buckets at idx of hash, if key is already set
 * it fails
 * @param key pointer to key
 * @param val pointer to val
 * @param ht HashTable structure
 *
 */
unsigned int set_val(char * key, char * val, HashTable * ht)
{
    if (ht == NULL || val == NULL || key == NULL)
      return 0;

  int hash = hash_code(key, ht);
  if (hash < 0)
    return 0;
  if (ht->buckets[hash] == NULL)
    {
      ht->buckets[hash] = val;
      return 1;
    } else
    {
      return 0;
    }
}

/*
 * Function which removes a value from the hash table
 * based upon key
 * @param key pointer to key
 * @param ht HashTable structure
 *
 */
unsigned int rm_val(char * key, HashTable * ht)
{
  if (ht == NULL || key == NULL)
    return 0;

  unsigned int hash = hash_code(key, ht);
  if (ht->buckets[hash] != NULL)
    {
      ht->buckets[hash] = NULL;
      return 1;
    } else
    {
      return 0;
    }
}

int main(void) {

    char * key = "foo";
    char * val = "bar";

    HashTable * ht = create_table(1000);
    unsigned int set = set_val(key, val, ht);
    if (set)
      {
    unsigned int rm = rm_val(key, ht);
    if (rm)
      {
        return 0;
      }
    }
    return 1;
}


texts: Decision tree node split by Gini coefficient (used in RandomFerns/RandomForest algorithm)

texts:
I am implementing the Random Ferns Algorithm for Classification. For simplicity, let's imagine a single decision tree with only a single node. As input we have a feature and the label of each dataset.

The function should work properly for any number of classes (length of set(labels)). The output is a feature threshold which leads to the best split. I plan to further implement other impurity measures such as misclassification rate or entropy.

For those interested in the topic, here is a link to a short introduction presentation in pdf format for the topic: classification trees and node split.

My current implementation works fine, yet I am sure there is plenty of place for improvement. If you have question regarding functionality, please ask. I gave some comments which explain what is to be done.

Example input:

test_features = [1,2,3,3,4]
test_labels = [0,0,1,1,1]

Example output:

3

Code as follows:

def best_split(feature_values, labels):
# training for each node/feature determining the threshold
impurity = []
possible_thresholds = sorted(list(set(feature_values)))

# the only relevant possibilities for a threshold are the feature values themselves

for threshold in possible_thresholds:
    # split node content based on threshold
    # to do here: what happens if len(right) or len(left) is zero
    right = [label for value, label in zip(feature_values, labels) if value >= threshold]
    left = [label for value, label in zip(feature_values, labels) if value < threshold]

    # compute distribution of labels for each split
    right_distribution = [len(list(group)) for key, group in groupby(right)]
    left_distribution = [len(list(group)) for key, group in groupby(left)]

    # compute impurity of split based on the distribution
    gini_right = 1 - np.sum((right_distribution / np.sum(right_distribution)) ** 2)
    gini_left = 1 - np.sum((left_distribution / np.sum(left_distribution)) ** 2)

    # compute weighted total impurity of the split
    gini_split = (len(right) * gini_right + len(left) * gini_left) / len(labels)

    impurity.append(gini_split)

# returns the threshold with the highest associated impurity value --> best split threshold
return possible_thresholds[impurity.index(min(impurity))]

This function is used for training of the Random Ferns class such as:

 def train(self, patches, labels):

        self.classes = list(set(labels))

        # here uniform distribution for each leaf is assumed
        # for each fern - for each feature combination - for each class - there is a posterior probability
        # these are all stored in a list of lists of lists named 'posterior'
        initial_distribution = [1 / len(self.classes)] * len(self.classes)
        self.posterior = [[initial_distribution] * (2 ** self.fernsize)] * self.number_of_ferns

        #determining the best threshold for each feature using best_split function
        all_thresholds = []

        for fern in self.ferns:
            fern_thresholds = []

            for feature_params in fern:
            # the function feature() extracts the feature values of a
            # specific feature (determined by feature_params) from each patch in patches
                feature_values = feature(patches, feature_params)

                fern_thresholds.append(best_split(feature_values, labels))

            all_thresholds.append(fern_thresholds)

        self.threshold = all_thresholds


texts: Refactoring different type of param to reduce duplicate code

texts:
So say I have a method that does a bunch of stuff, and I want to refactor this method to take a different type of parameter:

public object A(MyObject a)
{
    // does a bunch of crap with a

    // then calls another method
    this.B(a);
}

Now even method B() does a lot of crap with that same Object a. What if I want an endpoint that takes a SecondObject b. What I just did was basically duplicate all the methods and change the parameter type, but now I'm sitting with basically a bunch of duplicate code here. What's the best way to refactor this so that all my methods can take a different set (not just a different type) of parameters and reduce duplicity?

Thanks.

Edit:

Example,

private Chatham.Panda.WCF.DataContracts.IInstrument FillHistoricInstrumentRates(
            Chatham.Panda.WCF.DataContracts.IInstrument instrument,
            Chatham.Enumerations.BidMidAsk valuationPrice,
            DateTime rateCutoffDate,
            bool loadRates,
            FillInstrumentRates recursiveDelegate)
        {
            if (instrument == null)
            {
                throw new ArgumentNullException(
                    "instrument",
                    "RateAcqusitionService.SetInstrumentHistRates's 'instrument' argument is null");
            }

            // Compound Instruments
            Chatham.Panda.WCF.DataContracts.CompoundInterestRateInstrument compoundInstrument =
                instrument as Chatham.Panda.WCF.DataContracts.CompoundInterestRateInstrument;

            if (compoundInstrument != null)
            {
                foreach (Chatham.Panda.WCF.DataContracts.IInstrument i in compoundInstrument.ChildInstruments)
                {
                    recursiveDelegate(i);

                    return compoundInstrument;
                }
            }

            // Simple Instruments
            Chatham.Panda.WCF.DataContracts.SimpleInterestRateInstrument simpleInstrument =
                instrument as Chatham.Panda.WCF.DataContracts.SimpleInterestRateInstrument;

            if (simpleInstrument != null)
            {
                // Set Rates for each Component
                foreach (Chatham.Panda.WCF.DataContracts.Component component in simpleInstrument.Components)
                {
                    this.FillHistoricComponentRates(
                        component,
                        valuationPrice,
                        rateCutoffDate,
                        loadRates
                        );
                }

                return instrument;
            }

            throw
                new NotSupportedException(
                    string.Format(
                        "Instrument with type '{0}' currently not supported",
                        instrument.GetType().FullName)
                    );
        }

Now I want to change this method so that it takes a List<ScheduleRow> rows, as well as some other random properties including within the Chatham.Panda.WCF.DataContracts.IInstrument instrument, instead of passing the whole instrument across the wire, but if I just create another method with all this code in it and different parameters, it won't look TOO much different, and have plenty of duplicate code.

Then I'd also be doing things like calling:

this.FillHistoricComponentRates(
                            component,
                            valuationPrice,
                            rateCutoffDate,
                            loadRates
                            );

With a list of rows instead of the entire component, which leads to THAT method being changed in the same exact fashion, so on and so on...


texts: Dealing with resource closure when rethrowing an exception

texts:
I would like a review and recommendations for improvement of the code below.  I want to allow an exception to be handled by the caller, so I am rethrowing it.  But I have resources to close.  So I have the resource closing code duplicated in both the try and the catch blocks.  Is there a better way to do this?

const string HTTPopotamus::GET(void) {
  HINTERNET  hSession = NULL,
      hConnect = NULL,
      hRequest = NULL;
    try {
        hSession = this->open();
        hConnect = this->connect(hSession);
        hRequest = this->openRequest(hConnect);
        this->sendRequest(hRequest);
        this->receiveResponse(hRequest);
        string strData = this->readData(hRequest);
        /* Close any open resources. */
        if( hRequest ) WinHttpCloseHandle( hRequest );
        if( hConnect ) WinHttpCloseHandle( hConnect );
        if( hSession ) WinHttpCloseHandle( hSession );
        return strData;
    } catch (const ExceptionCyclOps& e) {
        /* Close any open resources. */
        if( hRequest ) WinHttpCloseHandle( hRequest );
        if( hConnect ) WinHttpCloseHandle( hConnect );
        if( hSession ) WinHttpCloseHandle( hSession );
        throw;
    }

}


texts: Printing 64-bit decimal numbers in freestanding environment

texts:
I need to print signed 64-bit numbers in decimal form. Program runs in freestanding environment (no C library available, libgcc may be unavailable too, or may not work correctly). So I can't use printf(3) function.

I'am trying to write function, which will be able to convert number from binary form (int64_t) to ascii. Simple solution is to divide number by 10, and use remainder as next digit (from left to right, iteratively).

Unfortunately, processor doesn't have 64 bit division, and I can't rely on libgcc in that (__udivdi3 function). So I invented other way to perform binary->decimal conversion, by using binary coded decimal (BCD) numbers. First I convert binary number to BCD form (bit by bit, need 64 iterations, and need to sum BCD numbers), then convert BCD to ASCII.

Source code is following:

/*static*/ void _print_dec(intmax_t num)
{
    char *p;
    char buf[24 /* > log10(2^64) */];
    uint_fast8_t r;
    uint64_t n = num < 0 ? -num : +num;

    uint_fast16_t result_h = 0, digit_h = 0;
    uint64_t result = 0, digit = 1;
    while (n != 0)
    {
        /* sum bcd numbers: r = a + b, where r should be L-value  */
        #define BCD_ADD(type, r, a, b) do { \
            type t1 = a + (type)(0x6666666666666666 & ((type)-1 >> 4)), t2 = t1 ^ b; \
            t1 += b, t2 = ~(t1 ^ t2) & (type)0x1111111111111110; r = t1 - (t2>>2 | t2>>3); \
        } while (0);

        /* this macro computes rh:rl = ah:al + bh:bl (sum of compound BCD number), rh:rl should be L-value */
        #define BCD_ADD_COMPOUND(type_h, type, rh, rl, ah, al, bh, bl) do { \
            uint_fast8_t c = 0; \
            type t1 = al, t2 = bl; \
            BCD_ADD(type, rl, al, bl); \
            c = rl >> (sizeof(type)*CHAR_BIT-4); \
            BCD_ADD(type_h, rh, ah, bh); \
            if (c >= 10 || (rl < t1 && rl < t2)) { \
                rl = (rl & ((type)-1 >> 4)) | ((c - 10ULL) << (sizeof(type)*CHAR_BIT-4)); \
                BCD_ADD(type_h, rh, rh, 1); \
            } \
        } while (0)

        if (n & 1)
            BCD_ADD_COMPOUND(uint_fast16_t, uint64_t, result_h, result, result_h, result, digit_h, digit);

        BCD_ADD_COMPOUND(uint_fast16_t, uint64_t, digit_h, digit, digit_h, digit, digit_h, digit);
        n >>= 1;
    }

    p = &buf[sizeof(buf) - 1];
    *p = 0;
    do {
        r = result & 0x0f;
        *--p = r + '0';
        result = (result >> 4) | ((uint64_t)(result_h & 0x0f) << (sizeof(uint64_t)*CHAR_BIT-4));
        result_h = result_h >> 4;

    } while (result_h != 0 || result != 0);

    if (num < 0) *--p = '-';
    print_cstr(p);
}
#define print_dec(num) DECL_FUNC(_print_dec, num)

I hope, that somebody suggests me some improvements...


texts: Convert a binary string, with each char separated by spaces, into a normal C string and print

texts:
This code is a purely for-fun project and it comes from this challenge at freeCodeCamp. This is simply an algorithm challenge which is usually meant for JavaScript, but I decided to perform in C. It will not be used for any production reasons. Please leave any feedback you see fit, with special attention to the loops and data types. I purposely used pointer arithmetic, while, and for loops to explore different approaches to the problems. I also left the printf about number of tokens in there if you'd like to play with it by uncommenting. Also note that I've provided 2 sample binary strings but only one is currently used by default.

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

char* binary_agent(char *bin_str);
char bit_string_decode(char *const str);
bool bit_string_is_valid(char *bit_string);
int main(void)
{
    char str[] = "01000001 01110010 01100101 01101110 00100111 01110100 00100000 "
                 "01100010 01101111 01101110 01100110 01101001 01110010 01100101 "
                 "01110011 00100000 01100110 01110101 01101110 00100001 00111111";
    char str2[] = "01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 "
                  "01100100 01100101 01000011 01100001 01101101 01110000 00100001";
    char *result = binary_agent(str);
    printf("%s\n", result);
    free(result);
    result = NULL;
    return 0;
}

// Purpose: Return an English translated sentence of the passed binary string
// "Chars" must be space-separated
// E.G. binary_agent("01000001 01110010 01100101");
char* binary_agent(char *bin_str)
{
    assert(bin_str);

    size_t count;
    char *token = NULL;
    char *delim = " ";
    count = 0;
    char *ptr = bin_str;

    while((ptr = strchr(ptr, ' ')) != NULL)
    {
        count++;
        ptr++;
    }

    ptr = NULL;
    //printf("Total number of tokens %lu\n", count);

    char *output_buffer = malloc(sizeof(char)*(count+1));
    assert(output_buffer);

    token = strtok(bin_str,delim); // token is null-terminated
    if(!token) return NULL;
    output_buffer[0] = bit_string_decode(token);
    size_t i;
    for(i = 1; token != NULL; ++i) //convert to for loop
    {
        token = strtok(NULL, delim);
        if(!token) break;
        output_buffer[i] = bit_string_decode(token);
    }
    return output_buffer;
}

//Parses groups of 8 1s or 0s into a char
char bit_string_decode(char *const str)
{
    assert(str && bit_string_is_valid(str));

    char output = 0;
    size_t i;

    //String needs to be valid for sure here
    for(i = 0; i < 8; ++i)
    {
        switch(str[i])
        {
            case '1':
                output |= 1 << 7-i;
                break;
            case '0':
                break;
        }
    }

    return output;
}
bool bit_string_is_valid(char *bit_string)
{
    assert(bit_string && (strlen(bit_string) == 8));

    while(bit_string && *bit_string != '\0')
    {
        if((*bit_string != '0') && (*bit_string != '1')) return false;
        bit_string++;
    }
    return true;
}


texts: Setting Sass environment variables in Grunt

texts:
I am into building functional prototypes, but also for outputting CSS and JS, which means we have 2 times we build out our code, once as a demo with HTML files (we are using assemble.io) and another, where we are building out the files to be uploaded to production (an Enterprise CMS).

Most things about the build are the same, but the main difference is certain paths within the CSS need to change. I have set up a sass variable, and when building, I change it and then change it back when I'm done (I do it in place, because other tasks are moving the sass files around.)

The problem is this method just feels really wonky, and not at all extensible.

We are using a gruntfile that is mostly the same as the one provided with the yeoman webapp generator, with some of our specific tasks added for good measure.

Here are excerpts of the relevant sections of my Gruntfile:

  grunt.initConfig({
    //...

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= config.app %>',
          dest: '<%= config.dist %>',
          src: [
            '*.{ico,png,txt}',
            'images/{,*/}*.webp',
            '{,*/}*.html',
            'fonts/{,*/}*.*',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          src: 'node_modules/apache-server-configs/dist/.htaccess',
          dest: '<%= config.dist %>/.htaccess'
        }, {
          expand: true,
          dot: true,
          cwd: '<%= config.app %>/components/bootstrap-sass-official/assets/fonts/bootstrap',
          src: '*',
          dest: '<%= config.dist %>/fonts'
        }, {
          expand: true,
          dot: true,
          cwd: '<%= config.app %>/components/font-awesome/fonts/',
          src: '*',
          dest: '<%= config.dist %>/fonts'
        }]
      },
      styles: {
        expand: true,
        dot: true,
        cwd: '<%= config.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up build process
    concurrent: {
      server: [
        'sass:server',
        'assemble'
      ],
      test: [
        'copy:styles'
      ],
      dist: [
        'sass',
        'copy:styles',
        'assemble',
        'imagemin',
        'svgmin'
      ]
    },
    replace: {
      prodSass: {
        src: ['<%= config.app %>/styles/utils/_variables.scss'],
        overwrite: true,
        replacements: [
          {
            from: '$site-root: $build-root',
            to: '$site-root: $prod-root'
          }
        ]
      },
      prodSassRevert: {
        src: ['<%= config.app %>/styles/utils/_variables.scss'],
        overwrite: true,
        replacements: [
          {
            from: '$site-root: $prod-root',
            to: '$site-root: $build-root'
          }
        ]
      }
    }
    //..
  });

  grunt.registerTask(
    'build',
    'Build out the codez! takes an optional `env` parameter so we can build in different ways',
    function(env){
      grunt.task.run(
        'clean:dist',
        'handlebars',
        'assemble',
        'wiredep'
      );

      // if 'prod' environment we need to do some variable modification
      // before the sass is compiled (which happens in 'concurrent')
      if (env === 'prod'){
        grunt.task.run('replace:prodSass');
      }

      grunt.task.run(
        'concurrent:dist',
        'preprocess:html',
        'useminPrepare',
        'autoprefixer',
        'concat',
        'cssmin',
        'pixrem:dist',
        'uglify',
        'copy:dist',
        'modernizr',
        'usemin'
      );

      if (env === 'prod'){
        grunt.task.run('replace:prodSassRevert');
      }
    }
  );


texts: Using LINQ to group social networking links for each user

texts:
I have a model named User. Each user can have some social links. Now I want to get all users with their social link as a single row in the result. Here are my models:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<SocialLink> SocialLinks { get; set; }
}

public class SocialLink
{
    public string Url { get; set; }
    public SocialType Type { get; set; }
    public User User { get; set; }
    public int UserId { get; set; }
}

public enum SocialType
{
    FaceBook    = 0,
    Twitter     = 1,
    Youtube     = 2,
    Linkedin    = 3,
    GooglePlus  = 4,
    Telegram    = 5,
    Instagram   = 6
}

public class UserViewModel
{
    public string Name { get; set; }
    public string Facebook { get; set; }
    public string Twitter { get; set; }
    public string Youtube { get; set; }
    public string Linkedin { get; set; }
    public string GooglePlus { get; set; }
    public string Telegram { get; set; }
    public string Instagram { get; set; }
}

I want my query to be like this in the result:

Name    | Facebook | Twitter  | Youtube | Linkedin | GooglePlus | Telegram | Instagram
======================================================================================
Someone | facebook | @someone | youtube | linkedin | google     | @tele    | @someins

I have written following query, It works as I expected but I wonder if there's a better way for doing this:

users.Select(p => new UserViewModel {
            Name = p.Name,
            Facebook = p.SocialLinks.FirstOrDefault(x => x.Type == SocialType.FaceBook).Url ?? "#",
            Twitter = p.SocialLinks.FirstOrDefault(x => x.Type == SocialType.Twitter).Url ?? "#",
            Youtube = p.SocialLinks.FirstOrDefault(x => x.Type == SocialType.Youtube).Url ?? "#",
            Linkedin = p.SocialLinks.FirstOrDefault(x => x.Type == SocialType.Linkedin).Url ?? "#",
            Telegram = p.SocialLinks.FirstOrDefault(x => x.Type == SocialType.Telegram).Url ?? "#",
            Instagram = p.SocialLinks.FirstOrDefault(x => x.Type == SocialType.Instagram).Url ?? "#",
}).ToList();


texts:
We have published a product today called MMMR.js this product is licensed under the MIT license and is built by Syed Mohammad Sannan.
The uniqueness of this product is that it is built with and for Javascript though there are many libraries out there such as NumPY, SciPY, and much much more but they are built for Python or another language and there isn't one for JavaScript that is where MMMR.js comes.
here.
This is the source code of MMMR.js:
// Mean - The average value.
// Median - The mid point value.
// Mode - The most common value.
// Range The smallest and the biggest value.

// This is Mean.
// Mean returns the average value from an array of numbers.
// To call/run this function we can type mean(Your array of numbers separated with commas ',');
const mean = (numbers) => {
  let total = 0,
    i;
  for (i = 0; i < numbers.length; i += 1) {
    total += numbers[i];
  }
  return total / numbers.length;
};

// This is Median.
// Median returns the middle point value from an array of numbers.
// To call/run this function we can type median(Your array of numbers separated with commas ',');
const median = (numbers) => {
  const sorted = numbers.slice().sort((a, b) => a - b);
  const middle = Math.floor(sorted.length / 2);

  if (sorted.length % 2 === 0) {
    return (sorted[middle - 1] + sorted[middle]) / 2;
  }

  return sorted[middle];
};

// This is Mode.
// Mode returns the most common/used value from an array of string, numbers, etc.
// To call/run this function we can type mode(your array of numbers);
const mode = (a) => {
  a.sort((x, y) => x - y);

  let bestStreak = 1;
  let bestElem = a[0];
  let currentStreak = 1;
  let currentElem = a[0];

  for (let i = 1; i < a.length; i++) {
    if (a[i - 1] !== a[i]) {
      if (currentStreak > bestStreak) {
        bestStreak = currentStreak;
        bestElem = currentElem;
      }

      currentStreak = 0;
      currentElem = a[i];
    }

    currentStreak++;
  }

  return currentStreak > bestStreak ? currentElem : bestElem;
};

// This is Range.
// Range is basically a function used to return the smallest and the biggest values from an array of numbers.
// To call/run this function we can type range(your array of numbers);
const range = (value) => {
  value.sort();
  return [value[0], value[value.length - 1]];
}

We just wanted you to review this code and tell us is this library user-friendly, maintainable and what improvements can we add to this.


texts: Stripping out all /* */ comments from a paragraph

texts:
I've written this code keeping the following cases in mind and I think I've covered them all. I'd really appreciate if someone could help me determine if I've covered all of them.

Cases I considered:

No comments at all
Text /* Text */ Text
Text /* Text */ Text /* Text */
Text /* /* Text */ */ Text
Text /* /* Text */ Text
Text /* Text
Text */ Text

private static String stripComments(final String input) {
    StringBuilder builder = new StringBuilder();
    boolean startSeen = false;

    for (int i = 0; i < input.length();) {
        int moveAheadBy = 1;

        if (startSeen) {
            if (input.charAt(i) == '*' && (i != input.length() - 1 && input.charAt(i + 1) == '/')) {
                startSeen = false;
                moveAheadBy = 2;
            }
        } else {
            if (input.charAt(i) == '/' && (i != input.length() - 1 && input.charAt(i + 1) == '*')) {
                startSeen = true;
                moveAheadBy = 2;
            } else {
                builder.append(input.charAt(i));
            }
        }
        i += moveAheadBy;
    }

    return builder.toString();
}


texts: Sort 3 numbers in Common Lisp with the minimum number of operations

texts:
I’m wondering is the following function returns a list of three numbers sorted in ascending order with the minimum possible number of operations, or if there is some more efficient or elegant method (a part from using the primitive function sort!)

(defun order (min mid max)
"sort three numbers in ascending order"
  (when (< mid min)
    (rotatef mid min))
  (if (< max min)
      (rotatef max mid min)
      (when (< max mid)
        (rotatef mid max)))
  (list min mid max))

With “minimum possible number of operations” I mean that the function should solve the problem with a number of tests and assignments (rotatef swaps two variables or rotates three or more variables) which is the minimum on the average on all the possible cases.


texts: Redirecting mobile devices to another page best practise

texts:
I am redirecting mobile devices from the root index.php to mobile.php file. I only allow access to mobile.php file only when that if statement is true.

This is how I do it:

Detect Devices and store them into variables
If a mobile device (see variables) accesses the web application redirect to mobile.php
In mobile.php check again the same thing and redirect back to index.php if the device is not a mobile device.

  Is this a good practice to redirect mobile devices to another file?

  Is there any tool to check my script from false positives?

index.php

    <?php #detecting mobile devices
    $iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
    $palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
    $berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
    $ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");
    $ipad = strpos($_SERVER['HTTP_USER_AGENT'],"iPad");

    if($iphone || $android || $palmpre || $ipod || $berry || $ipad == true)
{
 header('Location: mobile.php');
 exit;
}
    ?>

mobile.php

<?php #detecting mobile devices
$iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
$palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
$berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");
$ipad = strpos($_SERVER['HTTP_USER_AGENT'],"iPad");

if($iphone || $android || $palmpre || $ipod || $berry || $ipad == true)
{
//do nothing
}
else{ #device not one of the variables return to root file
header('Location: index.php');
exit;
}

 ?>


texts:
I have this regexp working, simple, but I feel like it may not be the best way to code it. Basically, I have a playlist separated by line breaks returned as tcp data like so:

file: http://192.168.100.214/Music/justchill.mp3
Artist: Brian G
Title: Just Chill
Track: 1
Date: 2014
Genre: Instrumental
Pos: 0
Id: 0
file: http://192.168.100.214/Music/justchill.mp3
Pos: 1
Id: 1
file: http://streaming.radionomy.com/ABC-Lounge
Pos: 2
Id: 2
OK

Now you can see the fields aren't always the same, but they always start with file and have the pos and id, always ending with id. I'm, parsing this data by line break to create an object, and then slicing it out of the string. Then I run the regexp on the new string, repeat while checking for Id: If it finds Id, I create a new object and start the whole process over.

It works fine, but I don't know, just feels like there may be a more efficient way to do it.

var parseplaylist = function(data)
{
    var pattern = /(.+): (.+)\n/;
    var result = pattern.exec(data);
    var playlistarray = [];
    if (result !== null)
    {
        var playlistobject = {};
        while (result !== null)
        {
            playlistobject[result[1]] = result[2];
            if (result[1] == "Id")
            {
                playlistarray[playlistobject.Pos] = playlistobject;
                playlistobject = {};
            }
            data = data.substr(result[0].length);
            result = pattern.exec(data);
        }
    }
    return playlistarray;
};


texts: Control DataTable to CSV toString() formatting

texts:
Following a question I asked and the advice on SO I implemented the following solution. Are there any downsides to such a solution? Is there a better way to make it changeable when I need to control formatting of other types like double and float where I have more than one occurrence of each in the dataLine[]?

    public void Save(DataTable newMyDataTable)
    {
        String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
        try
        {
            lock (writtingLock)
            {
                Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
                dataTable = newMyDataTable;
                fileId = dataTable.TableName;
                PathMaker path = new PathMaker(fileId);
                path.Make();
                // writing the table to a file
                using (StreamWriter swr =
                    new StreamWriter(File.Open(path.filePath, FileMode.Create), Encoding.Default, 1000000))
                // change buffer size and Encoding to your needs
                {
                    if (addHeader)
                    {
                        foreach (var dc in dataTable.Columns)
                        {
                            swr.Write(dc.ToString() + ",");
                        }
                        swr.WriteLine();
                    }
                    foreach (DataRow dr in dataTable.Rows)
                    {
                        Object[] dataLine = dr.ItemArray;
                        // extract date time and format it
                        var dateTime = dataLine.Where(o => o.GetType() == typeof(DateTime)).Select(t => (DateTime)t).Select(x => x.ToString(dateTimeFormat)).ToArray();
                        // collect data other than date time
                        var otherData = dataLine.Where(o => o.GetType() != typeof(DateTime)).ToArray();
                        // build your string
                        string dateTimeToWrite = string.Join(",", dateTime);
                        string otherDataToWrite = string.Join(",", otherData.Select(x => x.ToString().TrimEnd(null)).ToArray());
                        string lineToWrite = dateTimeToWrite + "," + otherDataToWrite;
                        swr.WriteLine(lineToWrite);
                    }
                }
            }
        }


texts: First steps in Scala: does this look idiomatic?

texts:
I an a newcomer in the Scala world, and I would like some advice from more experienced people to find out whether what I am writing goes in the direction of idiomatic code.

In particular, I have to write a simple algorithm that will do the following. We are given an integer number of, say, candies to be distributed, and a list of proportions, which are also integers. We should split the candies into groups, such that the proportions are respected as accurately as possible, given that a single candy cannot be broken up.

For instance, given 17 candies to distribute in proportions of (3, 2, 5) we should obtain (5, 4, 8).

Here is my code, including a quick ScalaCheck test.

import org.scalacheck.Prop._
import org.scalacheck.Gen

object Distribution {
    private class IntWithDivision(val self: Int) {
        def @/(other: Int): Float = self.toFloat / other
    }

    private implicit def divisibleInt(int: Int) = new IntWithDivision(int)

    def distribute(amount: Int, proportions: Seq[Int]): Seq[Int] = {
        val sum = proportions.sum
        val byDifect = proportions map { x => (amount * x @/ sum).toInt }
        val approximations = (byDifect, proportions).zipped map { (x, y) => x @/ y }
        val lowValuesIndices = (
            approximations.view.zipWithIndex
            sortBy { _._1 }
            take (amount - byDifect.sum)
            map { _._2 }
        ).force
        val remainders = (
            approximations.view.zipWithIndex
            map { x => if (lowValuesIndices contains x._2) 1 else 0 }
        ).force

        (byDifect, remainders).zipped map { _ + _ }
    }

    def main(args: Array[String]) {
        val pos = Gen.choose(1, 50000)
        val posList = Gen.containerOf[List, Int](pos)
        val propSum = forAll(pos, posList) { (amount: Int, proportions: List[Int]) =>
            (proportions.size > 0) ==> (amount == distribute(amount, proportions).sum)
        }
        propSum.check
    }
}

In particular, I would like advice on the following points:

The algorithm goes over the list of proportions and derived lists a few times. I would like to use more laziness, but using proportions.view at the beginning and then returning a force gives a type error.
The code is more convoluted than I would like. I think it may be simplified knowing the Collections API better.

Any help or suggestion is welcomed.


texts: Functional vs Object Oriented Approach for UI codes

texts:
I have the following snippets. which formats error messages based on a map. I can do it as a simple function call the function for transforming the error. or create a class and handle it in that way.

Functional doesn't require a an object instantiation and the message are exposed so that can imported in test to verify

Object Oriented will more structure but should be instantiated every time its accessed.

Functional

error_handler.js

export const messages = {
 500: 'Unexpected Error Occurred'
 400: 'Bad Request'
}

function transformError(error) {
 const message = messages[error.statusCode]
 return new Error(message)
}

error_handler.spec.js

it('should work for 400',() => {
  const error  = transformError({ statusCode :400 })
  expect(error.message).toEqual(messages[400]);
})

call().catch(transformError)

Object Oriented

class FormattedError {
 constructor(error){
   const messages = {
     500: 'Unexpected Error Occurred'
     400: 'Bad Request'
   }

   return new Error(messages[error.statusCode]);
 }
}

```

```
call().catch(e => new FormattedError(e))
```

```
it('should work for 400',() => {
  const error  = transformError({ statusCode :400 })
  expect(error.message).not.toBe(null)
})
```

What should be the ideal approach consider this is for UI


texts:
Jenkins DSL doesn't support collect and inject from what I can tell (I get missing method exceptions when I try), so I implemented my own map & reduce functions to use. I'm not sure if there's much to say about this small snippet of code, but I'd love to hear from some groovy or FP folks.

def map = { collection, f ->
  def result = []
  collection.each { element ->
    result.add(f(element))
  }
  result
}

def reduce = { collection, accumulator, f ->
  def result = accumulator
  collection.each { element ->
    result = f(result, element)
  }
  result
}


texts:
I'm learning about algorithms and have been recently experimenting with insertion sort via recursion in Python.

My code works fine, but I was wondering if there are any possible improvements that can be made. I am especially interested in ways to reduce the actual content of the code (i.e. make it shorter) or improve the speed.

def insertionsort(alist):
    i = len(alist)
    if i > 2:
        temp = alist[:i-1]
        insertionsort(temp)
        alist[:i-1] = temp[:i-1]

    k = len(alist) - 1
    m = len(alist)

    while k >= 1 and alist[k-1] > alist[k]:
        front = alist[k]
        back = alist[k - 1]
        alist[k] = back
        alist[k-1] = front

        k = k - 1

A = [4, 1, 6, 3, 9, 10]
insertionsort(A)

print(A)


texts: Project Euler 23 in Scala (non-abundant sums)

texts:
I recently overhauled my solution to Project Euler Problem 23 (which asks for the sum of all positive integers which cannot be written as the sum of two abundant numbers) to move it from an imperative style to a functional style and tried to increase its speed. However, the performance is still slow. I have clocked this solution at 58 seconds, and the older imperative solution at 64 seconds.

I am mainly hoping for feedback on how I could speed up the performance of this solution. The bottleneck appears to be at the notSumAbundant function. Is there a reliable way to reduce the number of values I need to check? Can this portion of notSumAbundant be made faster in any other way?

if(!abundantList.exists(x => abundantList.contains(num - x))) {
  notSumAbundant(num + 1, num :: currentList) }

I am also hoping for feedback if my code falls short of functional programming best practices.

val t0 = System.nanoTime()

//function to find factors
def factors(num: Int) = {
    val max = (num / 2) + 1
    val factors = for(i <- 1 to max if num % i == 0) yield { i }
    factors
}

//function to find sums
def sumList(numList: IndexedSeq[Int]) = {
  val sum = numList.reduceLeft( _ + _ )
  sum
}

//function to recursively form list of abundant numbers
def abundance(num: Int, currentList: List[Int]): List[Int] = {
  if(num <= 20161){
  val numFactors = factors(num)
  val factorSum = sumList(numFactors)

  //if the number is abundant, prepend it to the running list of abundant numbers in the function call
  if(factorSum > num) { abundance(num + 1, num :: currentList) }
  else { abundance(num + 1, currentList) }
  } else return currentList
}

//all abundant numbers
val abundant = abundance(3, List())

//function to create a list of numbers which cannot be formed as the sum of two abundant numbers
def notSumAbundant(num: Int, currentList: List[Int]): List[Int] = {
  val abundantList = abundant.filter(_ < num)
  if(num <= 20161) {
    //if it cannot be made as the sum of abundant numbers, prepend it to the current list when calling on the next number
    if(!abundantList.exists(x => abundantList.contains(num - x))) {
      notSumAbundant(num + 1, num :: currentList)
      } else { notSumAbundant(num + 1, currentList) }
 }  else return currentList
}

//store the values and then sum them
val answerList = notSumAbundant(1, List())
val answer = answerList.reduceLeft(_ + _)

val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0) / 1000000000 + " seconds")
println(answer)

Update:

Changing the nonAbundantSum function to use a Set instead of a List worked to get this down to 2 seconds, as t. fochtman suggested:

val abundant = abundance(3, List()).toSet
//function to create a list of numbers which cannot be formed as the sum of two abundant numbers
def notSumAbundant(num: Int, currentSet: Set[Int]): List[Int] = {
  val abundantList = abundant.filter(_ < num)
  if(num <= 20161) {
    //if it cannot be made as the sum of abundant numbers, prepend it to the current list when calling on the next number
    if(!abundantList.exists(x => abundantList.contains(num - x))) {
      val updatedSet = (num :: currentSet.toList).toSet
      notSumAbundant(num + 1, updatedSet)
      } else { notSumAbundant(num + 1, currentSet) }
 }  else return currentSet.toList
}

//store the values and then sum them
val answerList = notSumAbundant(1, Set())


texts: Faster output to Sheet from a collection of Dictionaries

texts:
My code is currently offloading parsed data into multiple spreadsheets, but it's pretty slow: about 110k rows and 35 columns in 3.5 minutes.
I was wondering if there were a more efficient way of looping through my collection of dictionaries.

Sub getData(Parsed As Object, company As String, a, wb)
        'Parsed contains a collection of dictionaries parsed from a JSON input'

        Dim oSheet As Variant
        Dim i As Long
        Dim j As Long
        For Each oSheet In ActiveWorkbook.Sheets
            'Identify the sheet containing the name of the company'
            Dim matchSheet As String
            If InStr(UCase(oSheet.Name), UCase(company)) Then
                matchSheet = oSheet.Name
            Else
                GoTo nextIteration
            End If
                'Create a 2d array of i number of dictionaries and j number of element in each dictionary'
                Dim Values As Variant
                ReDim Values(Parsed.Count, ArrayLen(a))

                Dim Value As Dictionary
                Dim key As Variant

                i = 1
                j = 0
                wb.Sheets(matchSheet).Select 'macro not working without selecting the sheet'
                wb.Sheets(matchSheet).Cells.Clear 'Clearing the data in the company Sheet'

                'For loops populating the Values array'
                For Each Value In Parsed
                    For Each key In a
                        Values(i, j) = Value(key)
                        j = j + 1
                    Next key
                    j = 0
                  i = i + 1
                Next Value

                'populating the needed sheet range with the parsed data'
                wb.Sheets(matchSheet).Range(Cells(1, 1), Cells(Parsed.Count, ArrayLen(a))) = Values
                'populationg the headers for that data'
                wb.Sheets(matchSheet).Range(Cells(1, 1), Cells(1, ArrayLen(a))).Value = a
                wb.Sheets(matchSheet).Range("D:D").NumberFormat = "General"
nextIteration:
        Next oSheet

End Sub

Here is an exemple of  what my API request returning 2 deals with 3 keys out of 37:

[
   {
      "DealNo": "11111",
      "DealDate": "2010-01-01",
      "Quantity": "1000"
   },
   {
      "DealNo": "11112",
      "DealDate": "2010-01-02",
      "Quantity": "2000"
   }
]

And here is the structure of the data after it has been parsed in excel:


texts: "Longest Palindromic Substring" challenge solution is inefficient

texts:
I am trying to solve the Longest Palindromic Substring problem on LeetCode, and I have come up with a DP solution pasted below:

public class Solution {
    String      string;
    boolean[][] visited;
    String[][]  results;

    private boolean isPalindrome(String s){
        String test = new StringBuilder(s).reverse().toString();
        if(test.equals(s)) return true; else return false;
    }

    private String maxLengthString(String... args){
        String result = new String();
        for(String arg:args){
            if(arg.length() > result.length()) result = arg;
        }
        return result;
    }

    private String findLongestPalindrome(int start,int end){
        if(start >= end) return new String();
        else if(start >= string.length() || start < 0) return new String();
        else if(end <= 0 || end > string.length()) return new String();
        else{
            if(visited[start][end-1] == true) return results[start][end-1];
            String result = new String();
            if(this.isPalindrome(string.substring(start,end)))
                result = maxLengthString(string.substring(start,end),
                                        findLongestPalindrome(start+1,end),
                                        findLongestPalindrome(start,end-1));
            else result = maxLengthString(findLongestPalindrome(start+1,end),
                                          findLongestPalindrome(start,end-1));
            visited[start][end-1] = true;
            results[start][end-1] = result;
            return result;
        }
    }

    public String longestPalindrome(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function

        string = s;
        visited = new boolean[s.length()][s.length()];
        results = new String[s.length()][s.length()];

        return findLongestPalindrome(0,s.length());
    }
}

The algorithm is quite straightforward, but the online judge complains about it not being efficient enough. I am just wondering if this algorithm is slow by nature (in which case I have to find another algorithm) or if it's something about my implementation.


texts: Converting List to a DataTable and/or DataSet Extension Methods

texts:
Can someone help me improve this code?  I and trying to have a couple extension methods to convert strongly-typed lists to a DataSet and DataTable respectively.

But... being so green to C#, I am not sure this is the most efficient way to do this.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;

namespace o7th.Class.Library.Data
{
/// <summary>
/// List to DataTable Converter
/// </summary>
public static class ListConverter
{

    /// <summary>
    /// Convert our List to a DataTable
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="data"></param>
    /// <returns>DataTable</returns>
    public static DataTable ToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        object[] values = new object[props.Count];
        using (DataTable table = new DataTable())
        {
            long _pCt = props.Count;
            for (int i = 0; i < _pCt; ++i)
            {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, prop.PropertyType);
            }
            foreach (T item in data)
            {
                long _vCt = values.Length;
                for (int i = 0; i < _vCt; ++i)
                {
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;
        }
    }

    /// <summary>
    /// Convert our List to a DataSet
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <returns>DataSet</returns>
    public static DataSet ToDataSet<T>(this IList<T> list)
    {
        Type elementType = typeof(T);
        using (DataSet ds = new DataSet())
        {
            using (DataTable t = new DataTable())
            {
                ds.Tables.Add(t);
                //add a column to table for each public property on T
                PropertyInfo[] _props = elementType.GetProperties();
                foreach (PropertyInfo propInfo in _props)
                {
                    Type _pi = propInfo.PropertyType;
                    Type ColType = Nullable.GetUnderlyingType(_pi) ?? _pi;
                    t.Columns.Add(propInfo.Name, ColType);
                }
                //go through each property on T and add each value to the table
                foreach (T item in list)
                {
                    DataRow row = t.NewRow();
                    foreach (PropertyInfo propInfo in _props)
                    {
                        row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
                    }
                    t.Rows.Add(row);
                }
            }
            return ds;
        }
    }

}
}


texts:
In my small application, I need to use a variety of visual themes.

The simplified structure of this class:

Theme
  |
  .__ menu
  |     |
  |     .__ screenBackground
  |     .__ itemsColor
  |     .__ getRandomItemAnimation()
  |
  .__ game
  |     |
  |     .__ screenBackground
  |     .__ gameBoardBackground
  |     .__ getRandomMoveSound()
  |
  .__ getRandomStartScreenImage()

I want to write code like this:

setBackground(theme.game.screenBackground)

instead of

setBackground(theme.game().screenBackground())

But in addition to that, I want to use inheritance. However, Java does not seem to allow to override public fields of the parent class in the descendant classes.

So I've decided to use the following implementation:

Basic classes:

// All constructors (in the next 3 classes) used to set final class-members by descendants

public abstract class Theme {
    public final MenuTheme menu;
    public final GameTheme game;

    public abstract Image getRandomStartScreenImage();

    public Theme(MenuTheme menuTheme, GameTheme gameTheme) {
        this.menuTheme = menuTheme;
        this.gameTheme = gameTheme;
    }
}

public abstract class MenuTheme {
    public final Image screenBackground;
    public final Color itemsColor;

    public abstract Animation getRandomItemAnimation();

    public MenuTheme(Image screenBackground, Color itemsColor) {
        this.screenBackground = screenBackground;
        this.itemsColor = itemsColor;
    }
}

public abstract class GameTheme {
    public final Image screenBackground;
    public final Image gameBoardBackground;

    public abstract Sound getRandomMoveSound();

    public GameTheme(Image screenBackground, Image gameBoardBackground) {
        this.screenBackground = screenBackground;
        this.gameBoardBackground = gameBoardBackground;
    }
}

Using:

public class Menu {
    public void setUp() {
        Theme theme = GameContext.getCurrentTheme();
        setBackground(theme.menu.screenBackground);
        setItemsColor(theme.menu.itemsColor);
    }

    public void onClickItem(Item clickedItem) {
        Theme theme = GameContext.getCurrentTheme();
        clickedItem.startAnimation(theme.menu.getRandomItemAnimation());
        // Action action = getActionByItem(clickedItem);
        // action.start();
    }
}

How to add theme:

public class DarkTheme extends Theme {
    private Image[] startScreenImages = getStartScreenImages();

    public Image getRandomStartScreenImage() {
        return startScreenImages[getRandomIndex()];
    }

    public DarkTheme() {
        super(new DarkMenuTheme(), new DarkGameTheme());
    }
}

public class DarkMenuTheme extends MenuTheme {
    private Animation[] itemAnimations = getItemAnimations();

    public Animation getRandomItemAnimation() {
        return itemAnimations[getRandomIndex()];
    }

    public DarkMenuTheme() {
        super(getDarkMenuScreenBackground(), getDarkMenuItemsColor());
    }
}

public class DarkGameTheme {
    private Sound[] moveSounds = getMoveSounds();

    public Sound getRandomMoveSound() {
        return moveSounds[randomIndex()];
    }

    public DarkGameTheme() {
        super(getDarkGameScreenBackground(), getDarkGameBoardBackground());
    }
}

What do you think about the structure of Theme?  Does it look like a good implementation?

The structure of Theme does not expect to be changed. There will only be the addition of new themes. Given this, what are the drawbacks and benefits of this code?  What improvement or other implementation can you recommend?


texts: ArrayBlockingQueue - blocking drainTo() method

texts:
This is a follow-up question to this question.

Is this a reasonable implementation for a blocking version of method ArrayBlockingQueue.drainTo(Collection)?

/**
 * This blocking method blends {@link #take()} with {@link #drainTo(Collection)}.
 * <br>
 * Chiefly, {@code take()} blocks and {@code drainTo(Collection)} does not block.
 */
public int drainAtLeastOneTo(Collection<? super E> c)
throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0) {
            notEmpty.await();
        }
        final int x = drainTo(c);
        return x;
    }
    finally {
        lock.unlock();
    }
}

To clarify: This code comes from the Sun JDK source code of ArrayBlockingQueue.  I simply blended the source from take() with drainTo(Collection).

I am considering adding it to a modified version of ArrayBlockingQueue.


texts: Defining routes and controllers relationship for given pages

texts:
I'm building a CMS app with the help of a custom framework. The back-office is composed of the following pages:

post list
page list
user list
post edit
page edit
user edit

Actually, my routes are defined as follows (I don't put regex here for clarity sake):

return array(
    '/post-list/' => array(
        'controller' => 'PostListController',
        'action'     => 'view'
    ),
    '/page-list/' => array(
        'controller' => 'PageListController',
        'action'     => 'view'
    ),
    '/user-list/' => array(
        'controller' => 'UserListController',
        'action'     => 'view'
    ),
    '/post-edit/(params)' => array(
        'controller' => 'PostEditController',
        'action'     => 'view'
    ),
    '/page-edit/(params)' => array(
        'controller' => 'PageEditController',
        'action'     => 'view'
    ),
    '/user-edit/(params)' => array(
        'controller' => 'UserEditController',
        'action'     => 'view'
    ),
);

With this approach, there are many little controllers that share almost the same lines of code (not DRY code). For example:

PostListController:

public function view()
{
    $postMapper = $this->repository->getMapper('PostMapper');
    $postSlugs  = $postMapper->fetchPostSlugs();
    $posts = array();

    foreach ($postSlugs as $postSlug) {
        $posts[] = $this->repository->getModel('PostModel', $postSlug);
    }

    if ($view = $this->repository->getView('PostListView')) {
        $models = array('posts' => $posts);
        $body   = $view->render($models);

        $this->response->setBody($body);
        $this->response->send();

        return;
    }
    // ...404 handling
}

... will be nearly identical to the PageListController, the only things that change are View and Model class names.

What would be the MVC best practice or which make more sense?

Keeping this approach: 1 controller for 1 page?
Making a controller that handles Lists having for action: posts(), pages(), users() and a controller handling Edit the same way?
Making a controller handling Post having for actions: edit() and list(), same for Page and User? (note that in this case I might still have some "unDRY" code).
Something else..?


texts: How can i simplify the following If code?

texts:
I have the following code in JS (using last ES2020), the current code check if the type is 'asporto' or 'takeaway' and adding to current date hours from a setup fo type 'takeaway' or 'asporto' and if another setup called limiteOreTakeaway/Asporto is !== '00:00:00' I have to check if the current time is greater than the limiteOreTakeaway/Asporto, so I'm splitting the string limiteOreTakeaway/Asporto to Hours and Minutes and making my checks if the current date is > that limiteOreTakeaway/Asporto I'm adding to curDate the hours from setup + 24hours.
My code looks like this:
const curDate = new Date();
    if (this.carrello.tipo === 'asporto') {
      if (this.negozioSetup.limiteOreAsporto !== '00:00:00') {
        // controllo se l'orario limite è impostato (orariolimite != 00:00)
        const ore = parseInt(
          this.negozioSetup.limiteOreAsporto.split(':')[0],
          10
        );
        const minuti = parseInt(
          this.negozioSetup.limiteOreAsporto.split(':')[1],
          10
        );
        // controllo se l'ora di adesso ha superato l'orario limite
        if (curDate.getHours() > ore) {
          curDate.setHours(
            curDate.getHours() + this.negozioSetup.oreMinimeAsporto + 24
          );
         // se l'ora corrente è uguale controllo se i minuti limite hanno superato il limite
        }else if (curDate.getHours() === ore && curDate.getMinutes() > minuti) {
            // se l'orario corrente è maggiore di quello limite aggiungo 24 ore alla data corrente
            curDate.setHours(
              curDate.getHours() + this.negozioSetup.oreMinimeAsporto + 24
            );
        }
      } else {
        // orario limite disabilitato proseguo con l'aggiunta delle ore minime tra gli ordini
        curDate.setHours(
          curDate.getHours() + this.negozioSetup.oreMinimeAsporto
        );
      }
    } else if (this.carrello.tipo === 'takeaway') {
      if (this.negozioSetup.limiteOreTakeaway !== '00:00:00') {
        const ore = parseInt(
          this.negozioSetup.limiteOreTakeaway.split(':')[0],
          10
        );
        const minuti = parseInt(
          this.negozioSetup.limiteOreTakeaway.split(':')[1],
          10
        );
        if (curDate.getHours() > ore) {
          curDate.setHours(
            curDate.getHours() + this.negozioSetup.oreMinimeTakeaway + 24
          );
        }else if (curDate.getHours() === ore && curDate.getMinutes() > minuti) {
          curDate.setHours(
            curDate.getHours() + this.negozioSetup.oreMinimeTakeaway + 24
          );
        }
      } else {
        curDate.setHours(
          curDate.getHours() + this.negozioSetup.oreMinimeTakeaway
        );
      }
    }

I would like to simplify it. If it's possible, optimize it by using the last ES2020 available tools.


texts: Socket chat room made with Tkinter Python

texts:
This is a real live chatroom that I have made with Tkinter

I posted a question before about making a chatroom but the problem that I had with that one was that only one user could connect to the server so I restarted and have made this one. I just want suggestions on how I can improve it.

All suggestions will be greatly appreciated

Thanks

Server.py

import socket, threading
host = socket.gethostname()
port = 4000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen()
clients = {}
addresses = {}
print(host)
print("Server is ready...")
serverRunning = True
def handle_client(conn):
    try:
        data = conn.recv(1024).decode('utf8')
        welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % data
        conn.send(bytes(welcome, "utf8"))
        msg = "%s has joined the chat" % data
        broadcast(bytes(msg, "utf8"))
        clients[conn] = data
        while True:
            found = False
            response = 'Number of People Online\n'
            msg1 = conn.recv(1024)

            if msg1 != bytes("{quit}", "utf8"):
                broadcast(msg1, data+": ")
            else:
                conn.send(bytes("{quit}", "utf8"))
                conn.close()
                del clients[conn]
                broadcast(bytes("%s has left the chat." % data, "utf8"))
                break
    except:
        print("%s has left the chat." % data)
def broadcast(msg, prefix=""):
    for sock in clients:
        sock.send(bytes(prefix, "utf8")+msg)

while True:
    conn,addr = s.accept()
    conn.send("Enter username: ".encode("utf8"))
    print("%s:%s has connected." % addr)
    addresses[conn] = addr
    threading.Thread(target = handle_client, args = (conn,)).start()

Client.py

import socket,threading,tkinter
host = input("Enter server name: ")
port = 4000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = (host,port)
def echo_data(sock):
   while True:
      try:
         msg = sock.recv(1024).decode('utf8')
         msg_list.insert(tkinter.END, msg)
      except OSError:
         break

def send(event=None):
   msg = my_msg.get()
   my_msg.set("")
   s.send(bytes(msg, "utf8"))
   if msg == "{quit}":
      s.close()
      top.quit()

def on_closing(event=None):
    my_msg.set("{quit}")
    send()

top = tkinter.Tk()
top.title("Chat Room")

messages_frame = tkinter.Frame(top)
my_msg = tkinter.StringVar()
my_msg.set("Type your messages here.")
scrollbar = tkinter.Scrollbar(messages_frame)
msg_list = tkinter.Listbox(messages_frame, height=15, width=100, yscrollcommand=scrollbar.set)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
msg_list.pack()
messages_frame.pack()

entry_field = tkinter.Entry(top, textvariable=my_msg)
entry_field.bind("<Return>", send)
entry_field.pack()
send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()

top.protocol("WM_DELETE_WINDOW", on_closing)

address = (host,port)
s.connect(address)

threading.Thread(target=echo_data, args = (s,)).start()

tkinter.mainloop()


texts: Putting rows of ascending digits and eliminate rows of other digits, leaving other symbols intact

texts:
For example, sequence "aasdf123456785fg87" will be transformed into "aasdf12345678fg", using getchar and putchar and then using strings.

With getchar and putchar:

char c = 0, c_ = 0;
char flag = 0;
while ((c = getchar()) != '.')
{
    if (isdigit(c))
    {
        if (!isdigit(c_))
        {
            flag = 0;
            c_ = c;
            while (true)
            {
                c = getchar();
                if (!isdigit(c))
                {
                    if (flag)(putchar(c_));
                    putchar(c);
                    break;
                }

                if (c - c_ == 1)
                {
                    flag = 1;
                    putchar(c_);
                }
                c_ = c;
            }
        }
    }
    else putchar(c);

    c_ = c;
}

and using strings:

char str[100] = { 0 }, outstr[100] = { 0 };
int i = 1;
char flag = 0;
int c = 0;
gets(str);
while (true)
{
    if (isdigit(str[i]))
    {
        if (isdigit(str[i - 1]))
        {
            if (str[i] - str[i - 1] == 1)
            {
                outstr[c++] = str[i - 1];
                flag = 1;
            }
            else
            {
                if (flag)outstr[c++] = str[i - 1];
                flag = 0;
            }
        }
    }
    else
    {
        if (flag)
        {
            outstr[c++] = str[i - 1];
            flag = 0;
        }
        if (str[i] == '.')break;
        outstr[c++] = str[i];
    }
    i++;
}
puts(outstr);

This code is not great, and I ask you to make it easier to understand and more effective. The thing is that I need to show these programs to my teacher, and he's going to see them done as easier and smarter as possible. I just don't know if it's okay.


texts: Adding values from DictReader to empty dictionary

texts:
I made a rock climbing simulator game for fun.  Below is a function from the program, which works. But I can't help but think it could be refactored or more pythonic.

Namely, I open the data with csv.DictReader and read through the data, which add to a blank dictionary called route_info.  Is this step necessary?

The function has a with-open block, which opens a .csv file, but a link to the data is here.

import csv
import time

routes_climbed = []
pitches_climbed = 0

def choose_route():
    """After deciding about the weather, you come here and choose a
    route to climb. Reads list of routes from .csv file with names,
    grades, and pitches."""

    global routes_climbed, pitches_climbed

    route_info = {}

    with open('seneca_routes.csv', 'r', encoding='utf-8-sig') as f:     #weird encoding from excel?
        reader = csv.DictReader(f, ('route_name', 'route_grade', 'pitches'))
        print("Choose a route to climb from the following list of classics.")
        print()

        for row in reader:
            print(row['route_name'],row['route_grade'])
            route_info[row['route_name']] = row['pitches']

    route_choice = input("Which route do you want to climb? : ")

    if route_choice in route_info.keys():
        routes_climbed.append(route_choice)
        pitches_climbed += int(route_info[route_choice])
        climb_route(route_choice)
    else:
        print("Incorrect route name")
        time.sleep(3)
        choose_route()

choose_route()


texts: PHP OOP - Does this database reading class make sense?

texts:
After a whole night of work I finally have my first useful class - for reading database.

It works like a charm, but if you got a moment, please take a glance and give me feedback. Harsh criticism welcome.

Please note that security is not addressed yet, as well as usual SQL clauses, but I'd like to know am I on the right way to writing better software.

Here it is:

class DatabaseRead {
protected $dbh;                 // Database handle connection
public $columns     = array();  // Columns to be read
public $table;                  // Table to be read from
public $resultSet   = array();  // Returned results

public function __construct( $dbh, $columns, $table ) {
    $this->dbh          = $dbh;
    $this->columns      = $columns;
    $this->column       = '';
    $this->table        = $table;
    $this->resultSet    = array();

    $read_database = $this->dbh->query('SELECT ' . implode(',' , $this->columns) . ' FROM ' . $this->table);
    while ($row = $read_database->fetch()) {
        foreach($this->columns as $this->column) {
            $this->resultSet[$this->column] = $row[$this->column];
        }
    }
    return $this->resultSet;
}

}

Have I wrote an actual class that makes sense, or just a glorified function?

Thanks.


texts: Four algorithms to find the Nth Fibonacci number

texts:
I'm implementing some basic algorithms in Go as an introductory exercise. Here are four different algorithms to find the Nth Fibonacci number.

I'm looking for general feedback, but I'm specially interested in the Go idiom. Are the algorithms implemented idiomatically? If not, how can I correctly use the Go idiom to implement them?

Any other feedback you can think of is also welcome.

// Algorithms to calculate the nth fibonacci number

package main

import (
    "fmt"
    "math"
)

func main() {
    for i := 0; i <= 20; i++ {
        fmt.Println(fibonacci(i))
        fmt.Println(fibonacciRecursive(i))
        fmt.Println(fibonacciTail(i))
        fmt.Println(fibonacciBinet(i))
        println()
    }
}

// Iterative
func fibonacci(n int) int {
    current, prev := 0, 1
    for i := 0; i < n; i++ {
        current, prev = current + prev, current
    }
    return current
}

// Recursive
func fibonacciRecursive(n int) int {
    if n < 2 {
        return n
    }
    return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2)
}

// Tail recursion
func fibonacciTail(n int) int {
    return tailHelper(n, 1, 0)
}
func tailHelper(term, val, prev int) int {
    if term == 0 {
        return prev
    }
    if term == 1 {
        return val
    }
    return tailHelper(term - 1, val + prev, val)
}

// Analytic (Binet's formula)
func fibonacciBinet(num int) int {
    var n float64 = float64(num);
    return int( ((math.Pow(((1 + math.Sqrt(5)) / 2), n) - math.Pow(1 - ((1 + math.Sqrt(5)) / 2), n)) / math.Sqrt(5)) + 0.5 )
}


texts:
This program takes a command line argument of how many times you would like to encrypt plain text. After you compile the program, input a message you would like to have coded.  I'm new to C and curious about how to make this program more efficient.

/*
*caesar.c
*
*
*
*Encrypts user supplied messages according to a user supplied   encryption key
*
*/

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

int main(int argc, string argv[])
{

  if (argc != '\0' && argc == 2 )
  {

    //converting string input to integers
    int f= atoi(argv[1]);

    //getting string command from user
    string a = GetString();

    for(int i = 0, j = strlen(a); i < j; i++)
    {

        if ( isalpha (a[i]))
        {
            if (isupper(a[i]))
            {
                //converting capitalized chars
                char acap = (a[i] - 65);
                int ccap = (acap+f)%26;
                //final capitalized chars loop
                char ecap = ccap + 65;
                printf("%c", ecap);
            }

            else if (islower(a[i]))
            {
                //converting small chars
                char asma = (a[i] - 97);
                int csma = (asma+f)%26;
                //final small chars loop
                char esma = csma + 97;
                printf("%c", esma);
            }

       }
       else
       {
           printf("%c", a[i]);
       }

    }            printf("%c", esma);
    return 0;
}
else
{
    return 1;
}
}


texts:
I have tried to Implement Shared_Ptr and learned a lot while Implementing it.
So guys please review my Implementation.
Any Suggestions,Feed backs are highly appreciated.
and Thanks in Advance.

Asad.

//author @asad_nitp
#pragma once
namespace Smart_Pointers
{
class ReferenceCountManager
{
public:
    ReferenceCountManager():
       m_ref_count(0)
    {}

    void incrementReferenceCount()
    {
        ++m_ref_count;
    }

    int decrementReferenceCount()
    {
        return --m_ref_count;
    }

    int getReferenceCount() const
    {
        return m_ref_count;
    }
private:
    int m_ref_count;
};

template<typename T>
class Shared_Ptr
{
public:
    Shared_Ptr():
        m_pData(nullptr),
        m_pReferenceCountManager(nullptr)
    {}

    ~Shared_Ptr() noexcept
    {
        if (m_pReferenceCountManager)
        {
            if (m_pReferenceCountManager->decrementReferenceCount() == 0)
            {
                delete m_pData;
                delete m_pReferenceCountManager;
                m_pData = nullptr;
                m_pReferenceCountManager = nullptr;
            }
        }
    }

    explicit Shared_Ptr(T* ptr):
        m_pData(ptr),
        m_pReferenceCountManager(nullptr)
    {
        m_pReferenceCountManager = new ReferenceCountManager();
        m_pReferenceCountManager->incrementReferenceCount();
    }

    Shared_Ptr(const Shared_Ptr<T>& ob) noexcept :
        m_pData(ob.m_pData),
        m_pReferenceCountManager(ob.m_pReferenceCountManager)
    {
        m_pReferenceCountManager->incrementReferenceCount();
    }

    Shared_Ptr<T>& operator = (const Shared_Ptr<T>& ob) noexcept
    {
        Shared_Ptr(ob).swap(*this);
        return *this;
    }

    Shared_Ptr(Shared_Ptr<T>&& ob) noexcept :
        m_pData(ob.m_pData),
        m_pReferenceCountManager(ob.m_pReferenceCountManager)
    {
        ob.m_pData = nullptr;
        ob.m_pReferenceCountManager = nullptr;
    }

    Shared_Ptr<T>& operator = (Shared_Ptr<T> &&ob) noexcept
    {
        Shared_Ptr(std::move(ob)).swap(*this);
        return *this;
    }

    T& operator* () const
    {
        return *m_pData;
    }

    T* operator-> () const noexcept
    {
        return m_pData;
    }

    T* get() const noexcept
    {
        return m_pData;
    }

    int use_count() const noexcept
    {
        if (m_pReferenceCountManager)
        {
            return m_pReferenceCountManager->getReferenceCount();
        }
        return 0;
    }

    bool unique() const noexcept
    {
        return (this->use_count() == 1);
    }

    explicit operator bool() const noexcept
    {
        return (m_pData != nullptr);
    }

    void reset() noexcept
    {
        Shared_Ptr().swap(*this);
    }

    void reset(T *ptr)
    {
        Shared_Ptr(ptr).swap(*this);
    }

    void swap(Shared_Ptr<T>& ob) noexcept
    {
        using std::swap;
        swap(m_pData, ob.m_pData);
        swap(m_pReferenceCountManager, ob.m_pReferenceCountManager);
    }

private:
    T* m_pData;
    ReferenceCountManager * m_pReferenceCountManager;
};

template<typename T1, typename T2>
bool operator == (const Shared_Ptr<T1>& ob1, const Shared_Ptr<T2>& ob2) noexcept
{
    return ob1.get() == ob2.get();
}

template<typename T1, typename T2>
bool operator != (const Shared_Ptr<T1>& ob1, const Shared_Ptr<T2>& ob2) noexcept
{
    return !(ob1 == ob2);
}

}


texts: Rails dynamically changing parts of view but using the same method in controller

texts:
I have this update method which decides whether to update or recreate(same as update but resets the approval_status and create_date) of the building_approval object. I have the on_progress? method on building_approval class to check whether it needs to be updated or recreated so no flags are being passed from the view, the problem is I use this on_progress? method on view to change some minor UI in the form, so it is being called twice (once in the view for UI and once in the update method in the controller for deciding whether to update or recreate). I have considered passing to_update param from view to the controller so I wouldn't have to run on_progress? method twice but it makes my code look ugly

tldr:

def update
    return render :edit unless @building_approval.update(param_building_approvals)

    if(@building_approval.on_progress?)
      @building_approval.reapply
      @building_approval.send_reapply_mail(current_member)
      notice = @building_approval.has_contract? ? 'messages.warning.building_approval_has_contract' : 'messages.info.approval_reapplied'
    else
      @building_approval.after_save_by_apply()
      @building_approval.send_apply_mail(current_member)
      notice = 'messages.info.updated'
    end
    redirect_to prospective_customer_building_approval_path(@customer.id, @building_approval.id),
                notice: t(notice, :name => BuildingApproval.model_name.human)
end

or

def update
    return render :edit unless @building_approval.update(param_building_approvals)

    if(params[:to_update] == "false")
      @building_approval.reapply
      @building_approval.send_reapply_mail(current_member)
      notice = @building_approval.has_contract? ? 'messages.warning.building_approval_has_contract' : 'messages.info.approval_reapplied'
    else
      @building_approval.after_save_by_apply()
      @building_approval.send_apply_mail(current_member)
      notice = 'messages.info.updated'
    end
    redirect_to prospective_customer_building_approval_path(@customer.id, @building_approval.id),
                notice: t(notice, :name => BuildingApproval.model_name.human)
end

which one is better ? the first one's cons is it uses on_progress? method twice(in view and in controller) , the cons in the second one is it uses on_progress? once but I need to pass hidden_field to_update params to controller and make ugly if statements