texts:
I have a small bit of code and I wonder if I can make it more readable. I would appreciate it if some people could take a look at it and give me some feedback. I especially wonder if there is a beter way of doing this:
cv::Mat image = loadImage(path.string());
if (image.data == NULL) { continue; }

This is the bigger code:
cv::Mat Watermarker::loadImage(const std::string& path)
{
    if (!validFile(path))
    {
        if (!std::filesystem::is_directory(path))
        {
            std::cout << path << " is invalid\n";
        }

        return cv::Mat{};
    }

    cv::Mat image = cv::imread(path, cv::IMREAD_UNCHANGED);
    if (image.data == NULL)
    {
        std::cout << "Not enough permissions to read file " << path << "\n";
        return cv::Mat{};
    }

    return image;
}

void Watermarker::mark(const std::string& targetDirectory, const std::string& watermarkPath)
{
    cv::Mat watermarkImage = loadImage(watermarkPath);
    if (watermarkImage.data == NULL) { return; }

    // Loop through all the files in the target directory
    for (const std::filesystem::path& path : std::filesystem::directory_iterator(targetDirectory))
    {
        cv::Mat image = loadImage(path.string());
        if (image.data == NULL) { continue; }

        cv::resize(watermarkImage, watermarkImage, image.size());

        // Give the images 4 channels
        cv::cvtColor(image, image, cv::COLOR_RGB2RGBA);
        cv::cvtColor(watermarkImage, watermarkImage, cv::COLOR_RGB2RGBA);

        // Add the watermark to the original image
        cv::addWeighted(watermarkImage, 0.3, image, 1, 0.0, image);

        saveImage(targetDirectory + "/watermarked_images/" + path.filename().string(), image);
    }
}


texts:
In the past few days i have started to learn python 3 in my spare time and i am really enjoying it so far.

I have attempted many simple programs such as a palindrome checker and reverse a string in an attempt to improve my skills.

I was hoping that someone would be able to provide some feedback on the following program which is a guessing game program. The user is able to choose the number of guesses and the max possible value.

From my own perspective i think that possibly i am relying too much on while loops and if/else statements. Also i am not sure if my comments are sufficient, do they lack detail?
Also i use parentheses around the conditionals in my if/else statements and in my while loops as i find it easier to read the condition this way. Is this a bad idea? Could it confuse people who are trying to read my code?

# In this program, the user must try to guess a random number generated by the computer
from random import randint

def guess_game():
    replay = 1
    #Replay allows a user to replay the game without having to call the function again.
    #The values are: 1 = Replay, any other character = End program
    while (replay == 1):
        #lives = Number of chances you have to correctly guess the answer before the program finishes
        lives = int( input("How many lives would you like? ") )
        #max_value = upper bound for the randomly generated number. Starts at 0
        max_value = int( input("Please choose the largest number that can be generated: ") )
        random = randint(0, max_value)  #Generates a random int between 0 and max_value
        num_of_guesses = 1  #keeps track of the number of guesses made by the user
        while (num_of_guesses <= lives):
            guess = int( input("Please enter your guess: ") )
            if (guess == random):
                print("Good guess, that is correct! You got the right answer on guess number", num_of_guesses, ", well done!\n")
                break  #if answer is correct this will exit the while loop
            else:
                print("Unlucky, that guess was incorrect. You have", (lives-num_of_guesses), "lives remaining.\n")
            num_of_guesses = num_of_guesses + 1
        if (num_of_guesses > lives):
            print("You have run out of guesses. The correct answer was:", random)
        replay = int( input("\nWould you like to play again? Enter 1 for yes, any other character for no: ") )
        if (replay != 1):
            print("Thank you for playing. See you next time")

guess_game()


texts:
I used this code in several projects. But I am not sure if it is stable. However on production it is working well, but I want to listen your advices:

/// <summary>
/// Standard abstract parent for Timer-powered classes. Has Start|Stop|Pulse events
/// </summary>
public abstract class TimerContainer : IDisposable
{
    protected Timer Timer { get; set; }
    protected TimeSpan Interval { get; set; }

    protected TimerContainer() : this(TimeSpan.FromSeconds(1)) { }

    protected TimerContainer(TimeSpan interval)
    {
        Status = TimerStatus.NotInitialized;
        Timer = new Timer(OnTick, null, Timeout.Infinite, Timeout.Infinite);
        Interval = interval;
    }

    protected abstract void OnTick(object sender);

    #region Standard Events
    public event EventHandler OnStart;
    public event EventHandler OnStop;
    public event EventHandler OnPulse;

    public TimerStatus Status { get; protected set; }

    public void Start()
    {
        Timer.Change(TimeSpan.Zero, Interval);
        Status = TimerStatus.Running;

        if (OnStart != null) {
            OnStart(this, new EventArgs());
        }
    }

    public void Stop()
    {
        Status = TimerStatus.Stopped;
        Timer.Change(Timeout.Infinite, Timeout.Infinite);

        if (OnStop != null) {
            OnStop(this, new EventArgs());
        }
    }

    protected void InvokePulse()
    {
        if (OnPulse != null) {
            OnPulse(this, new EventArgs());
        }
    }

    #region IDisposable Members

    protected bool disposed = false;
    ~TimerContainer()
    {
        Dispose(false);
    }
    public virtual void Dispose()
    {
        if (!disposed) {
            Dispose(true);
            GC.SuppressFinalize(this);
            disposed = true;
        }
    }
    protected virtual void Dispose(bool disposing)
    {
        if (disposing) {
            if (Status != TimerStatus.Stopped) {
                Stop();
            }

            if (Timer != null) {
                Timer.Dispose();
                Timer = null;
            }
        }
    }

    #endregion
    #endregion
}

/// <summary>
/// Timer status
/// </summary>
public enum TimerStatus
{
    NotInitialized = 0,
    Running = 1,
    Stopped = 2
}


texts:
I recently wrote a file path normalizing function, with normalizing a pure lexical process. This means the function is unaware of the filesystem, and would not for instance consider symbolic links or know the current directory.

Normalizing is defined as

Remove any . directory
Replace consecutive delimiters with a single one
Replace delimiters with the one passed in
Remove ordered pairs of names and .. separated by a delimiter recursively

#include<algorithm>
#include<string>
#include<stdexcept>

std::string normalize(const std::string& path, char delimiter = '/')
{
    static constexpr char delims[] = "/\\";
    static const auto error = std::logic_error("bad path");

    std::string norm;
    norm.reserve(path.size() / 2);  // random guess, should be benchmarked

    for(auto it = path.begin(); it != path.end(); it++)
    {
        if(std::any_of(std::begin(delims),
                        std::end(delims),
                        [it](auto c){ return c == *it; }))
        {
            if(norm.empty() || norm.back() != delimiter)
                norm.push_back(delimiter);
        }
        else if(*it == '.')
        {
            if(++it == path.end())
                break;
            if(std::any_of(std::begin(delims),
                        std::end(delims),
                        [it](auto c){ return c == *it; }))
            {
                continue;
            }
            if(*it != '.')
                throw error;
            if(norm.empty() || norm.back() != delimiter)
                throw error;

            norm.pop_back();
            while(!norm.empty())
            {
                norm.pop_back();
                if(norm.back() == delimiter)
                {
                    norm.pop_back();
                    break;
                }
            }
        }
        else
            norm.push_back(*it);
    }
    if(!norm.empty() && norm.back() != delimiter)
        norm.push_back(delimiter);
    return norm;
}

In particular, there are a few things that stood out

Seeing as the path may be relative and the function knows nothing about the current directory, the function cannot normalize (as defined) ../something, the function currently considers it an error.
The use of std::any_of makes it trivial to replace delims, but the if statement becomes less readable.
Repetitively checking edge cases (eg norm.empty()), which is a common theme in string manipulation, feels plain wrong.


texts: MS CA2202: Object can be disposed more then once

texts:
When running Code Analysis on my project I get the following warning:

  CA2202 : Microsoft.Usage : Object 'fs' can be disposed more than once in method

I don't see the problem, and the code compiles fine and produces the expected results in all test cases.
If I remove the fs.Dispose(); statement then Code Analysis instead produces this warning:

  object 'fs' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'fs' before all references to it are out of scope.

I am much grateful if you can review my code so that I can learn the proper way of disposing resources.

    private string ReadFileContent(string filename, Encoding encoding, string category, FileArchive archiveConfig)
    {
        FileStream fs = null;
        StreamReader sr = null;
        string fileContent = string.Empty;

        _logger.Debug("Reading file content of \"" + category + "\" file \"" + filename + "\"");

        try
        {
            fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 64 * 1024, FileOptions.SequentialScan);
            fs.Position = 0;
            sr = new StreamReader(fs, encoding, true);
            fileContent = sr.ReadToEnd();
        }
        catch (Exception)
        {
            ArchiveFile(filename, archiveConfig.ErrorFolder, category, _logger);
            throw;
        }
        finally
        {
            if (sr != null)
                sr.Dispose();
            if (fs != null)
                fs.Dispose();
        }

        return fileContent;
    }


texts:
I wrote a little function that monitors some directories. If a file gets created, it will check in the extension list for a match. Can you please tell me if I could make my function better in any way?

private void sysWatcher_Created(object sender, FileSystemEventArgs e) {

    try {

        if (File.Exists(e.FullPath)) {

            var fileName = Path.GetFileName(e.FullPath);
            var fullPath = e.FullPath;
            var changeType = e.ChangeType;
            var fileExtension = Path.GetExtension(e.FullPath);

            _extensionList.RemoveAll(r => string.IsNullOrEmpty(r.Trim()));
            _ignoreList.RemoveAll(r => string.IsNullOrEmpty(r.Trim()));

            // Checking for match in Extension List
            bool _extResult = _extensionList.Any(s => e.FullPath.Contains(s));

            if (_extResult) {

                // Checking for match in Ignore List
                bool _ignResult = _ignoreList.Any(s => e.FullPath.Contains(s));

                if (!_ignResult) {

                    if (!GeneralSettings.autoMode) {

                        App.Current.Dispatcher.Invoke(delegate {

                            if (File.Exists(e.FullPath)) {
                                var fileInfo = new FileInfo(e.FullPath);
                                var wFunc = new WarningItem(e.FullPath, e.Name, AppSettings.SizeSuffix(fileInfo.Length),
                                    fileInfo.CreationTime.ToString("g"), fileInfo.Extension);

                                var wWin = new WarningWin();
                                wWin.init(wFunc);
                                wWin.ShowDialog();

                                // Add to Warning List and List Box
                                _warningList.Add(new WarningItem {
                                    DirName = Path.GetDirectoryName(e.FullPath),
                                    CreationDate = DateTime.Now.ToString("g"),
                                    Extension = fileInfo.Extension,
                                    FullPath = e.FullPath,
                                    FileName = e.Name,
                                    FileSize = AppSettings.SizeSuffix(fileInfo.Length),
                                    StatusImage = new Uri("/Images/inWatch.Folder.png", UriKind.RelativeOrAbsolute)
                                });
                                lstWarning.ItemsSource = _warningList;
                                tabWarning.IsSelected = true;
                                cmdSearchWarnings.Visibility = Visibility.Visible;
                            }
                        });
                    }
                    else {

                        Scan.scanFile(e.FullPath);
                    }
                }
            }
        }
    }
    catch (Exception ex) {
        GeneralSettings.LogException(ex);
    }
}


texts: Save a dynamically created DAG in Airflow instead of registering it to the scheduler

texts:
I would like to save my dynamic DAGs and not have them autoscheduled by the Airflow scheduler and so I an not using the globals() utility. Is this the right way? I saw pickling_dag but doesn't seem apt. I want to simply see the DAG that was dynamically created and save it, instead of just auto-scheduling on Airflow. I am reading some Spark confs from a config yaml file. This is the code:

def create_dag(dag_id,
               schedule,
               dag_number,
               default_args,
               session=None):

    with open("/Users/conf.yaml") as stream:
        try:
            t3Params = yaml.safe_load(stream)
        except yaml.YAMLError as err:
            print(str(err))

    dag = DAG(
        dag_id,
        is_paused_upon_creation=False,
        default_args=default_args,
        description='A dynamic DAG generated from conf files',
        schedule_interval=schedule,
    )

    myt3Params = {
        'queue': t3Params['conf']['queue'],
        'exe_mem': t3Params['conf']['num_exe'],
        'exe_core': t3Params['conf']['exe_core']
    }

    t3Cmd = "ssh myCluster@127.10.10.1 bash /home/myCluser/test-runner.sh {{ params.queue }} {{ params.exe_mem }} {{ params.exe_core }}"

    task_id="xyz"
    with dag:
        t3 = BashOperator(task_id='test_spark_submit3', bash_command=t3Cmd, params=myt3Params, dag=dag)

    dag_pickle = DagPickle(t3)
    pickle.dump(dag, open("/Users/airflow/dags/pickled_dags", 'wb'))

    session.add(dag_pickle)
    session.commit()

    return dag

for n in range(1, 5):
    dag_id = 'saved_dynamic_conf_dags_{}'.format(str(n))

    default_args = {
        'owner': 'me',
        'depends_on_past': False,
        'start_date': datetime(2020, 9, 23, 21, 00),
        'email': ['airflow@example.com'],
        'email_on_failure': False,
        'email_on_retry': False,
        'retries': 1,
        'retry_delay': timedelta(minutes=1)
    }

    schedule = '35,36,37 * * * *'

    dag_number = n

    create_dag(dag_id,schedule,dag_number,default_args)

Am I using pickle correctly? Is there a better way to do this?


texts:
I have a Queue that needs to try to process when anything updates in it (add, remove or update).

However, I don't want any of the callers to wait while the processing is happening (either for the processing to happen or while the processing is happening).

This is what I came up with:

private static readonly SemaphoreSlim asyncLock = new SemaphoreSlim(1);
private async void ProcessQueue()
{
    // Lock this up so that one thread at a time can get through here.
    // Others will do an async await until it is their turn.
    await asyncLock.WaitAsync();
    try
    {
        // Offload this to a background thread (so that the UI is not affected)
        var queueProcessingTask = Task.Run( () =>
        {
            var processingStuck = false;
            while (myQueue.Count >= 1 && !processingStuck)
            {
                // Get the next item
                var queueItem = myQueue.Peek();
                // Try to process this one. (ie DoStuff)
                processingStuck = ProcessQueueItem(queueItem);
                // If we processed successfully, then we can dequeue the item
                if (!processingStuck)
                    myQueue.Dequeue();
            }
        });
        Task.WaitAll(queueProcessingTask);
    }
    finally
    {
        asyncLock.Release();
    }
}

Is my Thread and async handling going to ensure that only 1 queueItem at a time can ever be "in the works"?

And will this avoid using resources from the UI thread?


texts:
I am brand new to Rust and want to know if there are any convention violations in my code and ways how I can make it more readable:
use std::io;

fn main() {
    let mut vec: Vec<i32> = Vec::new();
    loop {
        println!("Enter any number, 0 to terminate");
        let mut num = String::new();
        io::stdin()
            .read_line(&mut num);
        if num.trim().parse::<i32>().unwrap() == 0 {break;}
        vec.push(num.trim().parse::<i32>().unwrap());
    }
    let sum: i32 = vec.iter().sum();
    println!("Sum: {}", sum);
    println!("Min: {}", vec.iter().min().unwrap());
    println!("Max: {}", vec.iter().max().unwrap());
    println!("Mean: {}", sum as f32 / vec.len() as f32);
}


texts: Store and manage a fixed amount of things generally

texts:
I have an enum let's say with four values. Let's call them A, B, C, D.

public enum Categories
{
    A,
    B,
    C,
    D
}

I then have a Thing which stores something and has one of the values from my enum.

public class Thing
{
    public final Categories category;
    public int var;

    public Thing (Categories category) {
        this.category = category;
    }
}

All good. Now I know I will have exactly four things. I can change which things, I can set them to null, but I will always have one of each. I will always have exactly one A,B, C and one D. No more no less. So I store them in my Container. Like this.

public class Container
{
    private final Map<Categories, Thing> things = new HashMap<>();

    public Container () {
        for (int i = 0; i < Categories.values().length; i++) {
            things.put(Categories.values()[i], null);
        }
    }

    public Thing getThing (Categories c) {
        return things.get(c);
    }

    public Thing setThing (Categories c, Thing t) {
        Thing returnThing = null;

        if (things.containsKey(c) && t.category == c) {
            if (things.get (c) != null) {
                returnThing = things.get (c);
            }
            things.put(c, t);
        }

        return returnThing;
    }

    public Thing removeThing (Categories c) {
        Thing returnThing = null;

        if (things.containsKey(c) && things.get(c) != null) {
            returnThing = things.get(c);
            things.put (c, null);
        }

        return returnThing;
    }
}

While this code works, it feels a bit clunky. As I know I will never add another key, nor remove one. Is there any pattern I lack the knowledge of that solves this issue? Or, doubt it, is this the way to accomplish a task such as this?

I would prefer to stay away from external dependencies such as Guava.


texts:
The idea is to read a file - "data" - and write the information to a new file - "output" - only if it meets the criteria  (if the resource usage is more than a configured threshold).

Content of the file "data":

Namespace:              env-demo
Resource                Used            Hard
--------                ----            ----
cpu                     14500m          16
memory                  16857746636800m 32Gi
persistentvolumeclaims  7               9
pods                    12              24
replicationcontrollers  31              36
resourcequotas          1               10
secrets                 12              18
services                17              24

********************
Name:                   2xlarge
Namespace:              env-stg
Resource                Used            Hard
--------                ----            ----
cpu                     12              16
memory                  28306127360     32Gi
persistentvolumeclaims  8               9
pods                    17              24
replicationcontrollers  34              40
resourcequotas          1               10
secrets                 13              18
services                20              24

********************

The program looks like this:

import groovy.transform.Field

//reading the data file
File result = new File("data")
//writes required information to a new file
def output = new File("output")
def line
@Field def Threshold = 0.8

resource_list = [
                      "cpu","memory", "persistentvolumeclaims", "pods", \
                      "replicationcontrollers", "resourcequotas", "secrets", "services"
                ]

//method to process the data and returns only if a resource usage is
//above threshold
def process_data(resource){
    //check if the resource is part of either cpu or memory
    if ( resource[0] in resource_list.take(2)){
       //check if above threshold
       if ( (resource[2].take(2).toInteger() * Threshold) <= (resource[1].take(2).toInteger())){
           return "${resource[0]} " + "utlization is above threshold with usage of " + "${resource[1]} \n"
       }
    }
    else if ( (resource[2].toInteger() * Threshold) <= (resource[1].toInteger()) ) {
        return "${resource[0]} " + "utlization is above threshold with usage of " + "${resource[1]} \n"
    }
}

result.withReader { reader ->
    while ((line = reader.readLine()) != null) {
        try {
            // find out the project name
            if ("Namespace" == "${line}".split(':')[0]){
                output.append "#################################### \n"
                output.append "${line}".split(':')[1].trim() + "\n"
                output.append "#################################### \n"
            }
            // doing minus do avoid NULL characters
            def resource = "${line}".split('\t').minus('')
            if (resource[0] in resource_list){
                def res = process_data(resource)
                output.append res.minus('null')
            }
        }
        catch (all){
        }

    }
}

The output is:

# cat output
####################################
env-demo
####################################
cpu utlization is above threshold with usage of 14500m
replicationcontrollers utlization is above threshold with usage of 31
####################################
env-stg
####################################
memory utlization is above threshold with usage of 28306127360
persistentvolumeclaims utlization is above threshold with usage of 8
replicationcontrollers utlization is above threshold with usage of 34
services utlization is above threshold with usage of 20

I have written this program by taking the inputs by googling.

Please let me know what improvements should be done in this program.


texts: Calculating IRR (Internal Rate of Return) in Ruby using recursion

texts:
Is there a way to improve this code? (specially how I built the recursion and the breaking out of the loops and conditionals)

# Returns sum of present value of a sequence of cash flows
# rate = interest rate (month)
# initial amount = balance at the beginning
# *amounts = sequence of cash flows (1 or more)

def present_value_of_series(rate, initial_amount, *amounts)
  present_value = initial_amount
  i = 0
  while i < amounts.length
    present_value += amounts[i] / ( (1+rate)**(i+1) )
    present_value
    i +=1
  end
  return present_value
end

# Returns the IRR (Internal Rate of Return) for a sequence of cash flows
#
# IRR definition: the IRR is the rate at which the present value of a sequence of cash flows equals zero (or close to zero). It is reached by trial and error, using the steps below:
#
# 1. Define lower limit and upper limit for the rate - this is the range that will be tested
# 2. Define the rate increment at each iteration
# 3. Calculate the present value of a sequence of cash flows starting at the lower limit and keep incrementing according to defined increment
# 4. When the present value found is below zero, it means that a new lower and upper limit have been found
# 5. Increase calculation precision using a recursive function, this time incrementing at 10x more finer increments.

def irr(lower_guess, higher_guess, increment, *amounts)
  rate = lower_guess
  precision_level = 1
  while rate <= higher_guess
    if present_value_of_series(rate, *amounts) < 0
      if present_value_of_series(rate, *amounts) >= -precision_level
        #debug puts "present value = #{present_value_of_series(rate, *amounts)}"
        puts "rate = #{rate}"
        puts "rate = #{(rate*100).round(2)}% (rounded)"
        # returns annual rate
        annual_rate = (1+rate)**12-1
        puts "annual rate = #{annual_rate}"
        puts "annual rate = #{(annual_rate*100).round(2)}% (rounded)"
        break
      else
        irr((rate-increment), rate, increment/10, *amounts)
        break
      end
    else
      rate += increment
    end
  end
end

# Usage Example:
# 30000 loan to be paid in 12 installments of different values
# lower_guess = 0.005 (0.5%)
# higher_guess = 0.5 (50%)
# increment = 0.01 (1%)

puts irr(0.005, 0.50, 0.01, -30000.00, 2986.55, 2954.11, 2921.68, 2889.25, 2856.82, 2824.38, 2791.94, 2759.51, 2727.07, 2694.65, 2662.21, 2629.77)


texts:
My homework was to organize semaphores into a pyramid. The task was accomplished, but I ended up with this long ugly conditional and was wondering if anyone can see a better way/algorithm to accomplish the same thing.

if (me==0) {
    wait_sem(semaphore[1]);
    wait_sem(semaphore[2]);
    signal_sem(semaphore[0]);

}

if (me==1) {
    wait_sem(semaphore[3]);
    wait_sem(semaphore[4]);

}
if (me==2) {
    wait_sem(semaphore[4]);
    wait_sem(semaphore[5]);

}

if (me==3) {
    wait_sem(semaphore[6]);
    wait_sem(semaphore[7]);

}
if (me==4) {
    wait_sem(semaphore[7]);
    wait_sem(semaphore[8]);

}
if (me==5) {
    wait_sem(semaphore[8]);
    wait_sem(semaphore[9]);

}
if (me==6) {
    wait_sem(semaphore[10]);
    wait_sem(semaphore[11]);

}
if (me==7) {
    wait_sem(semaphore[11]);
    wait_sem(semaphore[12]);

}
if (me==8) {
    wait_sem(semaphore[12]);
    wait_sem(semaphore[13]);

}

if (me==9) {
    wait_sem(semaphore[13]);
    wait_sem(semaphore[14]);

}


texts: Parsing string into hash-map with 2D coordinates as keys

texts:
I had never programmed in a functional programming language before. I think that this function has large nesting. Is there way to rewrite it better? I am most worried about the use of "flatten". Is there way to get rid of it? Also, is the indentation correct and does the function name correspond to Clojure naming style?

(defrecord Point [x y])
(def delimiter #" ")

(defn str->cells
  "Converts string with cells separated with
  delimiter and new lines to Points hash map"
  [^String s]
  {:pre [(re-matches #"^((?:^|\s)(?:.|\s)(?=\s|$))+$" s)]}
  (apply
    hash-map
    (flatten
      (map-indexed
        (fn [y line]
          (map-indexed
            (fn [x value] [(Point. x y) value])
            (str/split line delimiter)))
        (str/split-lines s)))))

;; Example of use:
(str->cells "1 2\n3")  ;; -> {#Point{:x 1, :y 0} "2", #Point{:x 0, :y 0} #Point{:x 0, :y 1} "3"}


texts:
I am trying to create max-heap for practice.

Are there any bugs?
Are there ways that I can improve the code quality?

public class MaxHeap <E extends Comparable<? super E>>{
  List<E> list;

  public MaxHeap(E[] array){
    this(Arrays.asList(array));
  }
  public MaxHeap(List<E> list){
    if(list == null)
      throw new IllegalArgumentException("list cannot be null");
    this.list = new ArrayList<E>(list);
    buildHeap();
  }

  public void buildHeap(){
    for(int i=lastParent(); i >= 0; i--)
      maxHeapify(i);
  }

  private void maxHeapify(int parent){
    if(isParent(parent)){
      //assume left child is bigger for now
      int biggerChild = 2 * parent + 1;
      int rightChild = biggerChild+1;
      if(rightChild < size() && compare(rightChild, biggerChild) > 0)
        biggerChild = rightChild;

      if(compare(biggerChild, parent) > 0){
        swap(biggerChild, parent);
        maxHeapify(biggerChild);
      }
    }
  }

  private int compare(int fir, int sec){
    return list.get(fir).compareTo(list.get(sec));
  }

  public boolean add(E item){
    if(item == null)
      return false;

    list.add(item);
    int child = last();
    int parent = getParent(child);

    while(isParent(parent)){
      if(compare(parent, child) < 0){
        swap(parent, child);
        child = parent;
        parent = getParent(parent);
      }
      else
        break;
    }
    return true;
  }

  private void swap(int left, int right){
    Collections.swap(list, left, right);
  }

  public int size(){
    return list.size();
  }

  public E remove(){
    if(isEmpty())
      return null;

    swap(0, last());
    E max = list.remove(last());
    maxHeapify(0);
    return max;
  }

  public boolean isEmpty(){
    return size() == 0;
  }

  private int last(){
    return size() - 1;
  }

  private int getParent(int child){
    if(index == 0)
      return -1;
    else
      return (child-1)/2;
  }

  private boolean isParent(int index){
    return index >= 0 && index <= lastParent();
  }

  private int lastParent(){
    return size()/2 - 1;
  }

  public String toString(){
    StringBuilder builder = new StringBuilder();
    int lineCounter = 0;
    int lineMax = 1;
    for(E item : list){
      builder.append(item);
      builder.append(" ");
      lineCounter++;
      if(lineCounter >= lineMax){
        builder.append("\n");
        lineCounter = 0;
        lineMax++;
      }
    }
    return builder.toString();
  }
}


texts: Create an object based on data from a text file

texts:
The following method reads specially formatted text (TOML) from a file and parses the input using a parser to get a few properties, which are then used to create an object.

The profiler tells me that this method is the bottleneck in my program. While parsing ~5000 files, this method eats up over 95% of the total running time. While in another method, I am able to write the data parsed from this method to a text file in under 4 seconds for more than 5000 files, this method takes around 15 seconds on an average to run.

/**
* Creates an appropriate instance of a Parsable implementation depending
* upon the header of the file.
*
* @param file the path of the file from which to create a Parsable.
* @return the created Parsable.
*/
private Parsable createParsable(Path file) {
    Toml toml = new Toml();
    try (BufferedReader br = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
        StringBuilder header = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null && !line.equals(HEADER_DELIMITER)) {
        header.append(line).append("\n");
        }
        toml.parse(header.toString());
        String title = toml.getString("title");
        author = toml.getString("author") != null ? toml.getString("author") : author;
        String date = toml.getString("date");
        String slug = toml.getString("slug");
        LocalDate publishDate = LocalDate.parse(date, DateTimeFormatter.ofPattern(config.getDateFormat()));
        String layout = toml.getString("layout");
        List<String> tag = toml.getList("tags");
        StringBuilder content = new StringBuilder();
        while ((line = br.readLine()) != null) {
            content.append(line).append("\n");
        }
        if (layout.equals("post")) {
            return new Post(title, author, publishDate, file, content.toString(), slug, layout, tag);
        }
        else {
            return new Page(title, author, file, content.toString(), slug, layout, tag);
        }
    }
    catch (IOException ex) {
            Logger.getLogger(DirectoryCrawler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

It is important to note that this method gets called over 5000 times in my test.
I have tried analyzing separate parts of the method for the performance problem, but haven't been able to identify any. How can I write this better?

The TOML library is from here : https://github.com/mwanji/toml4j

And the implementation of the constructors are like so:

/**
 * Creates a Post with the given paramenter.
 *
 * @param titl the post title
 * @param auth the post author
 * @param dat the post date
 * @param loc the post's Path
 * @param cont the post's content
 * @param slu the post slug
 * @param lay the layout
 * @param tag the list of tags
 */
public Post(String titl, String auth, LocalDate dat,
            Path loc, String cont, String slu, String lay, List<String> tag) {
    title = titl;
    author = auth;
    //TODO add summary option
    //this.summary = summ;
    date = dat;
    location = loc;
    content = cont;
    slug = slu;
    layout = lay;
    tags = tag;
}


texts:
This is only my second Python script, so let me have it!  If anything seems off in style or implementation, please nit pick away.  I want to learn.  I know it could've been done in less lines of code without making separate functions and whatnot, but I wanted to approach it like I would an actual project.

#!/bin/usr/python
from sys import exit

def print_help():
    print("")
    print("--------------------------------")
    print(" Command   |  Description")
    print("--------------------------------")
    print(" -h        |  Print help list")
    print(" -x        |  Exit program")
    print("--------------------------------")
    print("")

def is_valid_word(word):
    return word and word.isalpha()

def is_valid_string(string):
    for word in string.split(" "):
        if not is_valid_word(word):
            return False
    return True

def get_pig_latin(string):
    vowels = "aeiou"
    built = ""
    for word in string.split(" "):
        if len(word) < 2 or word[0] in vowels:
            built += word + "tay"
        else:
            temp = word
            while temp[0] not in (vowels + "y"):
                temp = temp[1:] + temp[0]
            built += temp + "ay"
        built += " "
    built = built[0].upper() + built[1:]
    return built

def print_title():
    print("")
    print("--------------------------------")
    print("----- PIG LATIN TRANSLATOR -----")
    print("--------------------------------")
    print("Type -h for help")
    print("")

def run():
    commands = { "-h" : print_help,
                 "-x" : exit }
    print_title()
    while True:
        input = raw_input(":: ").strip().lower()
        if input in commands:
            commands[input]()
        elif is_valid_string(input):
            print("-> " + get_pig_latin(input) + "\n")
        else:
            print("   Unrecognized word or command.\n")

if __name__ == "__main__":
    run()


texts: Schedule matches for a season or round robin tournament

texts:
The algorithm comes from wiki.

The output from the algorithm is correct but not something that a person could (easily) understand.  See the wiki link above.

Each team play every other team.  Optionally play every team twice and reverse home / away.

Assume an even number of teams.  I need to add a test for even.

Please review for style and any other advice.

public struct Match
{
    public int IDhome { get; }
    public int IDaway { get; }
    public int Week { get; }
    public override string ToString()
    {
        return $"week {Week}  IDhome {IDhome}  IDaway {IDaway}";
    }
    public Match(int idHome, int idAway, int week)
    {
        IDhome = idHome;
        IDaway = idAway;
        Week = week;
    }
}
public struct Season
{
    public int[,] ScheculeRaw { get; }
    int TeamCount { get; }
    public List<Match> Matches { get; }
    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        foreach (Match m in Matches)
        {
            sb.AppendLine(m.ToString());
        }
        return sb.ToString();
    }
    public Season(int teamCount, bool awayHome = false)
    {
        ScheculeRaw = RoundRobinRaw(teamCount);
        TeamCount = teamCount;
        Matches = new List<Match>();
        for (int w = 0; w < TeamCount - 1; w++)
        {
            for (int p = 0; p < TeamCount/2; p++)
            {
                Matches.Add(new Match(ScheculeRaw[w, p] + 1, ScheculeRaw[w, teamCount - 1 - p] + 1, w + 1));
            }
        }
        if (awayHome)
        {
            for (int w = 0; w < TeamCount - 1; w++)
            {
                for (int p = 0; p < TeamCount / 2; p++)
                {
                    Matches.Add(new Match(ScheculeRaw[w, teamCount - 1 - p] + 1, ScheculeRaw[w, p] + 1, w + teamCount));
                }
            }
        }
    }

    public static int[,] RoundRobinRaw(int count)
    {
        int[] rr = new int[count];
        for (int i = 0; i < count; i++)
        {
            rr[i] = i;
        }
        int[,] sch = new int[count - 1, count];
        for (int w = 0; w < count - 1; w++)
        {
            for (int i = 0; i < count; i++)
            {
                sch[w, i] = rr[i];
            }

            //Debug.WriteLine("");
            //Debug.WriteLine("ww1");
            //for (int p = 0; p < count; p += 2)
            //{
            //    Debug.Write(sch[w, p] + ", ");
            //}
            //Debug.WriteLine("");
            //Debug.WriteLine("ww2");
            //for (int p = count - 1; p > 0; p -= 2)
            //{
            //    Debug.Write(sch[w, p] + ", ");
            //}

            // rotate rr
            int temp = rr[count - 1];
            for (int r = count - 2; r > 0; r--)
            {
                rr[r + 1] = rr[r];
            }
            rr[1] = temp;

            //Debug.WriteLine("");
            //Debug.WriteLine("rr");
            //for (int r = 0; r < count; r++)
            //{
            //    Debug.Write(rr[r] + ", ");
            //}
            //Debug.WriteLine(".");
        }
        return sch;
    }
}


texts:
This is a very simple FFT, I am wondering what I can do to make this faster and more memory efficient from the programming side (better data types, and maybe some tricks like unrolling loops or using the preprocessor if that is useful here), and not by using a more efficient mathematical algorithm. Obviously I would appreciate advice on best practices as well.
#include <stdio.h>
#include <vector>
#include <iostream>
#include <complex>
#include <cmath>
#include <algorithm>

#define N 1048576
#define PI 3.14159265358979323846

/*
Creating the table of all N'th roots of unity.
We use notation omega_k = e^(-2 pi i / n).
*/
template<typename U>
std::vector< std::complex<U> > rootsOfUnityCalculator() {
    std::vector< std::complex<U> > table;

    for (size_t k = 0; k < N; k++) {
        std::complex<U> kthRootOfUnity(std::cos(-2.0 * PI * k / N), std::sin(-2.0 * PI * k / N));
        table.push_back(kthRootOfUnity);
    }

    return table;
}

/*
Fast Fourier transform, T is the precision level, so float or double.
table is a look up table of the roots of unity. Overwrites the input.
For now only works for N a power of 2.
*/
template<typename T>
void FFT(std::complex<T>* input, const std::vector< std::complex<T> >& table, size_t n) {

    if (n % 2 == 0) {
        // Split up the input in even and odd components
        std::complex<T>* evenComponents = new std::complex<T>[n/2];
        std::complex<T>* oddComponents = new std::complex<T>[n/2];

        for (size_t k = 0; k < n/2; k++) {
            evenComponents[k] = input[2 * k];
            oddComponents[k] = input[2 * k + 1];
        }

        // Transform the even and odd input
        FFT(evenComponents, table, n/2);
        FFT(oddComponents, table, n/2);

        // Use the algorithm from Danielson and Lanczos
        for (size_t k = 0; k < n/2; k++) {
            std::complex<T> plusMinus = table[N / n * k] * oddComponents[k]; // omega_n^k = (omega_N^(N/n))^k = omega_N^(Nk/n)
            input[k] = evenComponents[k] + plusMinus;
            input[k + n/2] = evenComponents[k] - plusMinus;
        }

        delete[] evenComponents;
        delete[] oddComponents;

    } else {
        // The Fourier transform on one element does not do anything, so
        // nothing needed here.
    }
}

int main() {
    std::complex<double>* input = new std::complex<double>[N];

    for (size_t k = 0; k < N; k++) {
        input[k] = k;
    }

    const std::vector< std::complex<double> > table = rootsOfUnityCalculator<double>();

    // Overwrites the input with its Fourier transform
    FFT<double>(input, table, N);

    delete[] input;

    return 0;
}


texts: Prints each letter of a string in different colors

texts:
I'm practicing for my Technical Interview and I'm worried my code does not meet the bar. What can I do to improve this answer?

Here is the question: https://www.careercup.com/question?id=5739126414901248

Given

colors = ["red", "blue", "green", "yellow"]; and a string

str = "Lorem ipsum dolor sit amet";

write a function that prints each letter of the string in different colors. ex. L is red, o is blue, r is green, e is yellow, m is red, after the space, i should be blue.

My answer:

static void TestPrintColors()
    {
        string[] colors = new string[4] {"red", "blue", "green", "yellow"};
        string str = "Lorem ipsum dolor sit amet";
        PrintColors(colors, str);
    }

    static void PrintColors(string[] colors, string str)
    {
        char log;
        ConsoleColor originalColor = Console.ForegroundColor;
        int colorIndex = 0;
        ConsoleColor currentColor = originalColor;
        for (int i = 0; i < str.Length; i++)
        {
            log = str[i];

            if (log == ' ')
            {
                Console.WriteLine(log);
                continue;
            }

            switch(colors[colorIndex])
            {
                case "red":
                currentColor = ConsoleColor.Red;
                break;

                case "blue":
                currentColor = ConsoleColor.Blue;
                break;

                case "green":
                currentColor = ConsoleColor.Green;
                break;

                case "yellow":
                currentColor = ConsoleColor.Yellow;
                break;

                default:
                currentColor = originalColor;
                break;
            }

            colorIndex++;

            if (colorIndex >= colors.Length)
            {
                colorIndex = 0;
            }

            Console.ForegroundColor = currentColor;

            Console.WriteLine(log);
        }

        Console.ForegroundColor = originalColor;
    }


texts: Calculating infix expression with no parenthesis

texts:
This is my Java implementation (\$O(n)\$) about how to calculate infix expression with no parenthesis.

For example, when we input "3 + 4 * 4 / 8", we will get a double type answer is 5.0. Here to make the algorithm simple, we don't consider any parenthesis in the expression.

I think my implementation is kind of tedious and long. Can anyone give me some advice on making it cleaner?

public double computeInfixExpr(String input) {
        String[] expr = input.split(" ");
        int i = 0;
        double operLeft = Integer.valueOf(expr[i++]);
        while (i < expr.length) {
            String operator = expr[i++];
            double operRight = Double.valueOf(expr[i++]);
            switch (operator) {
                case "*":
                    operLeft = operLeft * operRight;
                    break;
                case "/":
                    operLeft = operLeft / operRight;
                    break;
                case "+":
                    while (i < expr.length) {
                        String operator2 = expr[i++];
                        if (operator2.equals("+") || operator2.equals("-")) {
                            i--;
                            break;
                        }
                        if (operator2.equals("*")) {
                            operRight = operRight * Double.valueOf(expr[i++]);
                        }
                        if (operator2.equals("/")) {
                            operRight = operRight / Double.valueOf(expr[i++]);
                        }
                    }
                    operLeft = operLeft + operRight;
                    break;
                case "-":
                    while (i < expr.length) {
                        String operator2 = expr[i++];
                        if (operator2.equals("+") || operator2.equals("-")) {
                            i--;
                            break;
                        }
                        if (operator2.equals("*")) {
                            operRight = operRight * Double.valueOf(expr[i++]);
                        }
                        if (operator2.equals("/")) {
                            operRight = operRight / Double.valueOf(expr[i++]);
                        }
                    }
                    operLeft = operLeft - operRight;
                    break;
            }
        }
        return operLeft;
    }


texts: Script for fetching a list of "end-positions" from a MySQL database

texts:
This script fetches a list of "end-positions" from a MySQL database. The positions are array positions that are the same in both MySQL and R.

Next, the script takes the previous 34 elements for each metric and calculates their correlation with a query series.

The top X highest correlated (in total for each metric) and bottom X lowest correlated rows are saved.

Finally the initial MySQL list is trimmed to contain only those highly correlated points.

I am very new to R, and I am pretty sure that I did a very inefficient job of implementing this. I am looking for response times under 1 second in length.

#Executed during initialization:
library(RODBC)
library(stats)

channel<- odbcConnect("data")
c<-mat.or.vec(3000,5) #will hold correlations
n1<-seq(-33,0)

z <- sqlQuery(channel,"SELECT RPos,M1,M2,M3,M4 FROM `data`.`z` ") #Get whole series
al_string <- "select RPos,OpenTime FROM z JOIN actionlist on(OpenTime = pTime)"
trim_string<- "DELETE FROM ActionList WHERE OpenTime NOT IN (SELECT OpenTime FROM ReducedList)"

#This segment is called repeatedly. Each time actionlist contains different positions.
actionlist<- sqlQuery(channel,al_string)

#SIMULATION: (x will be filled by something else in reality)
x <- sqlQuery(channel,"SELECT z.pTime AS pTime,M1,M2,M3,M4 FROM z JOIN (SELECT pTime FROM z ORDER BY rand() limit 1) AS X ON (z.pTime<=X.pTime AND z.pTime> x.pTime-(300*34))")
i<-1

This is the part I am most interested in speeding up:

GetTopN<-function(n)
{
  for(i in 1:nrow(actionlist))
  {
              c[i,1]<-actionlist$OpenTime[i];
              for(j in 2:ncol(z)) c[i,j]<-cor(z[actionlist$RPos[i]+n1,j],x[,j]);
  }
  avc     <- (cbind(c[,1],rowSums(c[,2:5])));
  topx    <- c[order(avc[,2], decreasing=T),1][1:n];
  bottomx <- c[order(avc[,2], decreasing=F),1][1:n];
  DF<-as.data.frame(c(topx,bottomx),row.names=NULL);
  colnames(DF)[1]<-"OpenTime";

     sqlSave(channel,dat=DF,tablename="ReducedList",append=FALSE,rownames=FALSE,safer=FALSE);
  sqlQuery(channel,trim_string);
}


texts: Scale-able API development with macro definitions

texts:
In a couple of months I'll be part of a large(ish) project, and there's good chances my team will be a lot bigger, with at least 2 programmers (probably 3) and some 3-5, or more, consumers of the API we'll build (we're building a game, and they'll script high level logic using a scripting language we've yet to choose).

Now, last project I was in I used the below mentioned technique with "great" success when generating structures for use in mapping configuration files. Problem is, this will be a first timer for me in building an API with several developers and multiple consumers, and I have no idea how well it will scale.

tl;dr:

Is this system intuitive enough and scale-able enough for someone (you!), without pre-existent knowledge of the system, to pick it up and extend it without much issue?
If not, how should I go about building something that achieves the same but lets me skip all the repetitive cruft?
Can you spot any gotchas I've overlooked?

These examples uses python 2.7 and pybind11 (for binding structures to python). When properly linked against python they're buildable and runnable.

#include <pybind11/pybind11.h>

namespace py = pybind11;

#define PLUGIN PYBIND11_PLUGIN

#define PLUGIN_BEGIN(TYPE, NAME, DESCR)         \
    PLUGIN(TYPE)                                \
    {                                           \
        typedef TYPE Type;                      \
        py::module Module (NAME, DESCR);        \
        py::class_<Type> Binding(Module, #NAME);\

#define PLUGIN_END                              \
        return Module.ptr();                    \
    }                                           \

#define PLUGIN_MAP_FIELD(NAME)                \
    Binding.def_readwrite(#NAME, &Type::NAME);\

#define PLUGIN_MAP_PROPERTY(NAME)                                   \
    Binding.def_property(#NAME, &Type::get##NAME, &Type::set##NAME);\

And then you use it as so:

#include <string>

struct SPerson
{
    unsigned int Age;

    std::string getName( void ) { return m_Name; }
    void setName( const std::string name ) { m_Name = name; }

private:
    std::string m_Name;
};

PLUGIN_BEGIN(SPerson, "Person", "A person descriptor")
    PLUGIN_MAP_FIELD(Age)
    PLUGIN_MAP_PROPERTY(Name)
PLUGIN_END


texts: Clustering markers on Google map on zoom

texts:
I have a method that is getting called when someone zooms camera on the map (Google map).
I recalculate the positions of markers of map and the code is clunky and not effective. I iterate over arrays three times per method call and that is really slow. When I have 600 markers the performance is really lacking.

What could I improve to make it faster?

I use following local variables:

float lastZoomLevel_; // last zoom value on last zoom
BOOL forceRecalculateMap; // when new data arrives I use this to force repositioning
NSArray *pointsArrayV_; // Array of BankPoint instances, object that holds location and description of marker

- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position
{
    float currentZoomLevel = mapView.camera.zoom;
    float diff = fabs(currentZoomLevel - lastZoomLevel_);

    if (diff > 0.3 || self.forceRecalculateMap){

        self.forceRecalculateMap = NO;

        lastZoomLevel_ = currentZoomLevel;

        markersGroupArray_ = [[NSMutableArray alloc] init];

        for (BankPoint *bpoint in pointsArrayV_) {

            CLLocationCoordinate2D coord = bpoint.coordinates.coordinate;

            CGPoint currentPoint = [mapView.projection pointForCoordinate:coord];

            if ([markersGroupArray_ count] == 0){

                NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:bpoint, nil];

                [markersGroupArray_ addObject:array];

            }

            else {

                BOOL flag_groupadded = NO;

                int counter= 0;
                for (NSMutableArray *array in markersGroupArray_){

                    for (BankPoint *bbpoint in array){

                        CLLocationCoordinate2D mcoord = bbpoint.coordinates.coordinate;
                        CGPoint mpt = [mapView.projection pointForCoordinate:mcoord];

                        if ([self distance:mpt point:currentPoint] < 20){
                            flag_groupadded = YES;
                            break;
                        }
                    }
                    if (flag_groupadded){

                        break;
                    }
                    counter++;

                }

                if (flag_groupadded){

                    if ([markersGroupArray_ count] > counter){
                        NSMutableArray *groupArray = [markersGroupArray_ objectAtIndex:counter];
                        [groupArray insertObject:bpoint atIndex:0];
                        [markersGroupArray_ replaceObjectAtIndex:counter withObject:groupArray];
                    }
                }
                else if (!flag_groupadded){

                    NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:bpoint, nil];
                    [markersGroupArray_ addObject:array];
                }
            }
        }

        [mapView clear];

        for (NSArray *array in markersGroupArray_){

            BankPoint *item = [array objectAtIndex:0];

            CLLocationCoordinate2D coord = item.coordinates.coordinate;

            GMSMarker *marker = [[GMSMarker alloc] init];
            marker.position = coord;
            marker.map = mapView;
            marker.userData = item;
        }
    }
}

- (float)distance :(CGPoint)pointA point:(CGPoint) pointB
{
    return sqrt( (pow((pointA.x - pointB.x),2) + pow((pointA.y-pointB.y),2)));
}


texts:
Below is my code to detect cycle in an undirected graph. Could anyone please review and let me know if I have taken care of all the cases?

The basic idea is to use DFS (non-recursive using stack) and check if already visited vertices are found in the stack.

bool dfsDetectCycle(int vertex, int visited[10]) {
    stack<int> s;

    s.push(vertex);

    while (!s.empty()) {
        int np_vertex = s.top();
        s.pop();
        // visit while poping and check visited
        if (visited[np_vertex]) {
            // if already visited means there is a cycle
            return true;
        }
        visited[np_vertex] = 1;
        cout << np_vertex << "\t";

        // Graph with Adjacency Matrix
        if (!isAdjList) {
            for (int j = 0; j < v; ++j)
                // below !visited[j] is needed to exclude previously visited vertices as well as to exclude parent node of currently in progress vertex
                if (adjMatrix[np_vertex][j] && !visited[j]) {
                    s.push(j);
                }
        }
        // Graph with Adjacency List
        else {
            vector<int>::iterator it = adjList[np_vertex].begin();
            for (; it != adjList[np_vertex].end(); ++it)
                if (!visited[*it])
                    s.push(*it);
        }
    }
    return false;
}

bool hasCycle() {
    if (empty())
        return false;
    int visited[10] = {0};
    for (int i = 0; i < v; ++i) {
        if (!visited[i]) {
            if (dfsDetectCycle(i, visited))
                return true;
        }
    }
    return false;
}


texts:
I am currently using an iterator because I have to insert record in one table, get its primary key and add it to another table. But since it's a loop, it's very slow when data is very big.

OPEN ITERATOR
Fetch NEXT FROM ITERATOR
INTO @AccountNumber, @CardNumber, @ExpirationDate,
@CardHolderName, @CardToken, @CreatedDate, @Active, @CustomerId

While (@@FETCH_STATUS = 0)
BEGIN

INSERT into dev_NeoGateway_DTA.dbo.DTA_PaymentInstrument
VALUES(@CustomerId, @CardToken, @CardHolderName, 0, '', 1, 0, @CreatedDate, 0, '', NULL)
SET @newId = SCOPE_IDENTITY();
INSERT into dev_NeoGateway_DTA.dbo.DTA_CardInstrument
VALUES(@newId, @CardHolderName, @CardNumber, @ExpirationDate)

Fetch NEXT FROM ITERATOR
INTO @AccountNumber, @CardNumber, @ExpirationDate, @CardHolderName, @CardToken,
     @CreatedDate, @Active, @CustomerId

END


texts: VB.net SQL match against Excel data to datagridview

texts:
I am importing an Excel sheet where the first column will contain product numbers. I match those numbers to my SQL database and display the product number and description of the matching products to a datagridview.
The code works, but if there are a lot of products it can take a long time.  What I'd really like to do is have it read the Excel sheet and add the description directly into the Excel sheet after the last column with data. Or at very least optimize the code to run quicker.
    Dim v As New FormRec
    Dim x As New FormRec
    Dim MyConnection As OleDb.OleDbConnection
    Dim DtSet As DataSet
    Dim MyCommand As OleDb.OleDbDataAdapter
    MyConnection = New OleDb.OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", workbook))
    MyCommand = New OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
    MyCommand.TableMappings.Add("Table", "match")
    DtSet = New DataSet
    MyCommand.Fill(DtSet)
    v.dgv.DataSource = DtSet.Tables(0)
    MyConnection.Close()

    Dim col As New DataGridViewTextBoxColumn
    col.HeaderText = "Product Number"
    col.Name = "prodnmbr"
    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
    col.DefaultCellStyle.Font = New Font("Arial", 14)
    x.dgv.Columns.Add(col)

    Dim co2 As New DataGridViewTextBoxColumn
    co2.HeaderText = "Description"
    co2.Name = "descrip"
    co2.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
    co2.DefaultCellStyle.Font = New Font("Arial", 14)
    x.dgv.Columns.Add(co2)

    For index As Integer = 0 To v.dgv.RowCount - 1
        Using conn As New SqlConnection(myconnection)
            Dim commandText As String = "select productnmbr,descr from database where productnmbr = @prodnmbr"
            Using command As SqlCommand = New SqlCommand(commandText, conn)
                conn.Open()
                With command.Parameters
                    .AddWithValue("@prodnmbr", v.dgv.Rows(index).Cells(0).Value.ToString)
                End With
                Using sqlread As SqlDataReader = command.ExecuteReader
                    If sqlread.Read Then
                        Dim match As String = sqlread.GetString(0)
                        If match = v.dgv.Rows(index).Cells(0).Value Then
                            x.dgv.Rows.Add(v.dgv.Rows(index).Cells(0).Value.ToString, sqlread.GetString(1))
                            x.dgv.Rows(index).DefaultCellStyle.BackColor = Color.LightGreen
                        End If
                    Else
                        x.dgv.Rows.Add(v.dgv.Rows(index).Cells(0).Value.ToString, "N/A")
                        x.dgv.Rows(index).DefaultCellStyle.BackColor = Color.Red
                    End If
                End Using
            End Using
        End Using
    Next
    x.ShowDialog()


texts: Given an array of integers, return the smallest positive integer not in it

texts:
Write a function:

function solution(A);

  that, given an array A of N integers, returns the smallest positive
  integer (greater than 0) that does not occur in A.

  For example, given A = [1, 3, 6, 4, 1, 2], the function should return
  5.

  Given A = [1, 2, 3], the function should return 4.

  Given A = [−1, −3], the function should return 1.

  Assume that:

  N is an integer within the range [1..100,000]
  Each element of array A is an integer within the range [−1,000,000..1,000,000]

  Complexity:

  Expected worst-case time complexity is \$O(N)\$
  Expected worst-case space complexity is \$O(N)\$, beyond input storage (not counting the storage required for input arguments)

  Elements of input arrays can be modified.

Solution in \$O(n^2)\$:

function solution(A) {
  for (i = 1; i < 1000000; i++) {
    if(!A.includes(i)) return i;
  }
}


texts:
I need to get the distinct sums of naturals of a natural

What I came up with is:

type Sum = Stream[Int] //should maintain the invariant that
                       //* all Ints are positive
                       //* is non-strictly decreasing
                       //* is non-empty

def makesums(i: Int): Stream[Sum] = {

  /* Schmear will try to "schmear" a sum by decreasing the first number by one,
  and adding one again in the first position that won't violate the above invariants.
  This is possible when the stream is not all 1's, and the above invariants are met for
  the argument.

  returns an Option[Sum], which is Some(schmeared) if the above is possible,
  and None otherwise.
  */

  def schmear(sum: Sum): Option[Sum] = sum match {
    //if we can decrease the head and increase the next element while
    //staying ordered, do that
    case head #:: s #:: tail if (head - 1 >= s + 1) =>
      Some((head - 1) #:: (s + 1) #:: tail)

    //otherwise, if the head is only one larger than the second element, do the same,
    //but smear the tail, restoring the invariant
    case head #:: s #:: tail if head > s =>
      schmear((s + 1) #:: tail).map(nt => (head - 1) #:: nt)

    //otherwise, if there are at least two elements, just schmear the tail,
    //and keep the orignal head
    case head #:: s #:: tail =>
      schmear(s #:: tail).map(nt => head #:: nt)

    //otherwise, if the head is larger than 1, decrease by 1, and put a 1 at the end
    case head #:: tail if (head > 1) =>
      Some((head - 1) #:: tail  #::: Stream(1))

    //otherwise, it's not possible.
    case _ => None
  }

  def rec(sum: Sum): Stream[Sum] = {
    schmear(sum) match {
      case Some(schmeared) => sum #:: rec(schmeared)
      case None            => Stream(sum)
    }
  }

  //initiate the recursive algorithm with the sum of the identity
  rec(Stream(i))
}

Using this:

  println(makesums(5).map(_.toList).toList)

  List(List(5), List(4, 1), List(3, 2), List(2, 2, 1), List(2, 1, 1, 1), List(1, 1, 1, 1, 1))

Going through the algorithm:

Stream(5) takes case 4, yielding Stream(4, 1)
Stream(4, 1) takes case 1, yielding Stream(3, 2)
Stream(3, 2) takes case 2, starting with (3 - 1) = 2, and recurses with Stream(2 + 1) for the tail

Stream(3) takes case 4, yielding Stream(2, 1)

yielding Stream(2, 2, 1)
Stream(2, 2, 1) takes case 3, starting with 2, and recurses with Stream(2, 1)

Stream(2, 1) takes case 2, starting with (2 - 1) = 1, and recurses with Stream(2) for the tail
Stream(2) takes case 4, yielding Stream(1, 1)
yielding Stream(1, 1, 1)

yielding Stream(2, 1, 1, 1)
Stream(2, 1, 1, 1) takes case 2, taking 1 for the head, and recursing with Stream(2, 1, 1) for the tail

keep taking case 2 until you heave Stream(2)
Stream(2) takes case 4, yielding Stream(1, 1)

yielding Stream(1, 1, 1, 1, 1)

but if feels really complicated. In particular, having 5 different cases for the schmearing, which seems way more complicated than describing what you do.

What can I do to simplify this?


texts: Python implementation of a Morse code translator


texts:
I recently got interested in Go and wrote a database server which uses a binary tree for data storage for fun. As I have no prior experience in Go, I'd like to gather a bit feedback on my code and would like to know how I can improve/optimize it.

File: BinaryTree.go

package BinaryTree

//import "fmt"

type SearchTree struct {
    value *int
    left, right *SearchTree
}

func (r SearchTree) getNode(i int) *SearchTree {

    if r.value != nil && *r.value == i {
        return &r
    }

    if r.left != nil {
        ref := r.left.getNode(i)
        if ref != nil {
            return ref
        }
    }

    if r.right != nil {
        ref := r.right.getNode(i)
        if ref != nil {
            return ref
        }
    }

    return nil
}

func (r SearchTree) Contains(n int) bool {
    node := r.getNode(n)
    return node != nil
}

func (r *SearchTree) Add(n int) {
    pointer := r

    for {

        if pointer.value == nil {
            pointer.value = &n
            return
        }

        if *pointer.value == n {
            return
        } else if *pointer.value < n {
            if pointer.left != nil {
                pointer = pointer.left
            } else {
                pointer.left = &SearchTree{&n, nil, nil}
                return
            }
        } else {
            if pointer.right != nil {
                pointer = pointer.right
            } else {
                pointer.right = &SearchTree{&n, nil, nil}
                return
            }
        }

    }
}

File: server.go

package main

import (
    "fmt"
    "net"
    "log"
    "BinaryTree"
    "strconv"
)

var data BinaryTree.SearchTree

func generateAddr() *net.TCPAddr {
    addr, err := net.ResolveTCPAddr("tcp", "localhost:19800")

    if err != nil {
        log.Fatal(err)
    }

    return addr
}

func handleConnection(con net.Conn) {
    fmt.Println("handling connection")

    buffer := make([]byte, 256)
    for {
        numBytes, err := con.Read(buffer)

        if err != nil {
            con.Close()
            return
        }

        cmdTxt := string(buffer[:numBytes])

        n, err := strconv.Atoi(cmdTxt[1:numBytes])

        if err == nil {
            fmt.Println(n)
            switch (cmdTxt[0]) {
            case 'g':
                if data.Contains(n) {
                    con.Write([]byte{6})
                } else {
                    con.Write([]byte{25})
                }
            case 's':
                data.Add(n)
                con.Write([]byte{6})
            }

        }

    }
}

func startServer() {
    ln, err := net.ListenTCP("tcp", generateAddr())

    if err != nil {
        log.Fatal(err)
    }

    for {
        fmt.Println("wait for connection")

        conn, err := ln.Accept()
        if err == nil {
            go handleConnection(conn)
        }

    }
}

func main() {
    startServer()
}


texts:
Problem statement

The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the monsoon, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the monsoon. Its height is 1 meter. Can you find the height of the tree after \$N\$ growth cycles?

Input Format

The first line contains an integer, \$T\$, the number of test cases.
\$T\$ lines follow. Each line contains an integer, \$N\$, that denotes the number of cycles for that test case.

Constraints

1 <= T <= 10
0 <= N <= 60

Sample Input: #01:

2
3
4

Sample Output: #01:

6
7

Explanation: #01:

There are 2 testcases.

N = 3:

the height of the tree at the end of the 1st cycle = 2
the height of the tree at the end of the 2nd cycle = 3
the height of the tree at the end of the 3rd cycle = 6

N = 4:

the height of the tree at the end of the 4th cycle = 7

My solution:

   'use strict';

function processData(input) {
    var parse_fun = function (s) {
        return parseInt(s, 10);
    };

    var lines = input.split('\n');
    var T = parse_fun(lines.shift());

    var data = lines.splice(0, T).map(parse_fun);
    for (var i = 0; i < data.length; i++) {
        var value = 1;
        for (var j = 0; j < data[i]; j++) {
            if (j % 2 == 0)
                value *= 2;
            else value += 1;
        }
        process.stdout.write(value + '\n');
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
var _input = "";
process.stdin.on("data", function (input) {
    _input += input;
});
process.stdin.on("end", function () {
    processData(_input);
});

The running time is of \$O(n^2)\$.  Can anyone tell how to optimize this code to decrease runtime?


texts:
#include <iostream>

const bool DEBUG = false;

template <typename ... Args>
void debug(Args ... args);

template <typename ... Args>
void _debug(Args ... args) {
    std::cout << "[" << __FILE__ << ":" << __LINE__ << "] ";
    (std::cout << ... << args) << std::endl;
}

#define debug(args...) if (DEBUG) _debug(args);

Suppose you are running ACM or you are somewhere without a well-crafted development environment. You have written some code and wondering what is going wrong.

Goal here is to find out what cause the problem as quickly as possible by placing tracing prints and turn them off all together by preventing code generation for them. So you can  submit your code with DEBUG = false and it will not cause any performance issues done by calling debug(...).


texts: Improvement to Luhn-Checksum Algorithm in Java

texts:
I just made a small Luhn Checksum validator
Description of Luhn Checksum
Every number in the Integer gets added individually together, but every second digit gets instead doubled and added. If the doubled number is over ten each individual digit gets added.
It works, but is there a way to make it more elegant and maybe more efficient, while maintaining readability?
The while loop seems a bit ugly to me, and I'm not completely satisfied with the name getLuhn but I don't know how else to name it.
public class Luhn {
    public static void main(String[] args) {
        System.out.println(validate(1762483));
    }

    public static boolean validate(int id){
        int totalSum = 0;
        while(id>0){
            totalSum += id%10;
            id /= 10;
            if(id>0){
                totalSum += getLuhn(id%10);
                id /= 10;
            }
        }
        return (totalSum%10 == 0);
    }

    private static int getLuhn(int id){
        id *= 2;
        return id%10 + id/10;
    }
}

Every comment is appreciated <3
From cleaner code, over more idiomatic Java, to improvements in performance.


texts: Printing a binary tree in vertical strips

texts:
I'm trying to print a binary tree in vertical strips.

For instance, a tree like this:

       8
     /   \
    6     10
   / \   /  \
  4   7 9    12
 / \
3   5

Is printed out as:

3
4
6 5
8 7 9
10
12

Here's how I'm doing it:

Map<Integer,Set<Integer>>  printStripsVertically(TreeNode root, Map<Integer,Set<Integer>> countMap, int dist) {

        if( root == null )
                return countMap;

        Set<Integer> nodeSet = countMap.get(dist);// get list at current distance.

        if(nodeSet ==null) { // this dist  hasnt been inspected yet, so create new list here.
                nodeSet= new HashSet<Integer>();
        }

        nodeSet.add(root.data);// add current node to list.
        countMap.put(dist,nodeSet);// create mapping for current dist
        //recurse left and right.

        Map<Integer,Set<Integer>> leftMap = printStripsVertically(root.getLeft(),countMap,dist-1);
        Map<Integer,Set<Integer>> rightMap = printStripsVertically(root.getRight(),countMap,dist+1);
        Map<Integer,Set<Integer>> mergedMap= new HashMap<Integer,Set<Integer>>();
        Iterator<Integer> itLeft = leftMap.keySet().iterator();
        while(itLeft.hasNext()){
            mergedMap.put(itLeft.next(),leftMap.get(itLeft.next()));
        }
        Iterator<Integer> itRight = rightMap.keySet().iterator();
        while(itRight.hasNext()){
            mergedMap.put(itRight.next(),rightMap.get(itRight.next()));
        }

        return mergedMap;//iterate over the map to get results.
}

Edit :
TreeNode.java

public class TreeNode {

     int data;
    private TreeNode left;
    private TreeNode right;
    public TreeNode getLeft() {
        return left;
    }
    public void setLeft(TreeNode left) {
        this.left = left;
    }
    public TreeNode getRight() {
        return right;
    }
    public void setRight(TreeNode right) {
        this.right = right;
    }

    public TreeNode(int data)
    {
        this.data=data;
    }

}

Call to the method

 Map<Integer,Set<Integer>> verticalStrips = new HashMap<Integer,Set<Integer>>();
verticalStrips =printStripsVertically(root,verticalStrips,0);//where root is the root of the tree.

I've dry-tested the algorithm to work, but I'm not quite convinced that iterating over the leftMap and rightMap is the cleanest way to go about this, so I'm looking for any suggestions towards that in particular or the code in general.

Any thoughts on its correctness are appreciated. I'm also looking for any other approaches that might be more efficient in dealing with the problem.


texts: Dijkstra - shortest Path implementation - STL

texts:
I have implemented Dijkstra algorithm to perform Shortest Path problem.
Input:
Adjacency List(Directed Graph): Description is like that
{Source Node, {edge_1, .. , edge_N}}
Cost Matrix (Same format as Adjacency List)
Queue: Priority Queue
Input to "Shortest Path" method are Start Node, End Node; it returns -1 if
there is no path from Source Node to Target Node, else it returns the cost of the minimum path selected.
Code:
#include <algorithm>
#include <iostream>
#include <limits>
#include <queue>
#include <tuple>
#include <unordered_map>
#include <vector>

namespace {
constexpr int ZERO_DISTANCE_VALUE = 0;
constexpr int INFINITY_VALUE = std::numeric_limits<int>::max();
} // namespace

using NodeType = int;
using CostType = int;
using AdjacencyListType = std::vector<std::vector<NodeType>>;
using DistanceVector = std::vector<NodeType>;
using QueueType = std::queue<NodeType>;
using CostEdgeVector = std::vector<std::vector<CostType>>;
using CostNodeTuple = std::tuple<NodeType, CostType>;
using DistanceMatrixType = std::vector<CostType>;

class Graph {
public:
  explicit Graph(const AdjacencyListType &input_list,
                 const CostEdgeVector &input_cost_list)
      : adjancecy_list(input_list), cost_list(input_cost_list) {}

  struct QueueComparator {
    bool operator()(const CostNodeTuple &left, const CostNodeTuple &right) {
      return std::get<1>(left) < std::get<1>(right);
    }
  };

  int shortest_path(const int &source, const int &target) {
    int result = 0;
    if (source == target)
      return result;
    if (!is_valid_node(source))
      return -1;
    std::vector<int> distance_node(adjancecy_list.size(), INFINITY_VALUE);
    distance_node[source] = 0;
    queue.emplace(std::make_tuple(source, 0));
    while (!queue.empty()) {
      const auto &current_node = queue.top();
      queue.pop();
      const NodeType &current_node_index = std::get<0>(current_node);
      const auto &sub_node_vector = adjancecy_list.at(current_node_index);
      const auto &sub_node_cost = cost_list.at(current_node_index);
      const int &current_distance_cost = distance_node.at(current_node_index);
      for (NodeType index = 0; index < sub_node_vector.size(); ++index) {
        const auto &child_index = sub_node_vector.at(index);
        const int relaxation_value =
            current_distance_cost + sub_node_cost.at(index);

        if ((distance_node.at(child_index) > relaxation_value)) {
          distance_node[child_index] = relaxation_value;
          queue.emplace(std::make_tuple(child_index, relaxation_value));
        }
      }
    }
    try {
      const auto &target_distance = distance_node.at(target);
      result = target_distance == INFINITY_VALUE ? -1 : target_distance;
    } catch (...) {
      result = -1;
    }

    return result;
  }

private:
  bool is_valid_node(const NodeType &node) {
    return node < adjancecy_list.size();
  }

  std::priority_queue<std::tuple<NodeType, int>,
                      std::vector<std::tuple<NodeType, int>>, QueueComparator>
      queue;

  const CostEdgeVector &cost_list;
  const AdjacencyListType &adjancecy_list;
};

int main() {
  AdjacencyListType cost_vector;
  CostEdgeVector adjancecy_list;
  NodeType source_node = 0;
  NodeType target_node = 0;
  Graph graph(adjancecy_list, cost_vector);
  const auto result = graph.shortest_path(source_node, target_node);
  std::cout << "Shortest Path value: " << result << std::endl;
  return 0;
}


texts:
I'm trying to a write super simple task runner with asyncio.

Basically, my goal is to run 100 requests to google as tasks, whilst also being be able to handle tasks being added at a later time.

from abc import ABC, abstractmethod
import asyncio
import socket
import time

import aiohttp
import requests

class MyScheduler:
    def __init__(self, wait=2):
        self.work = []
        self.wait = wait

    def set_initial_callback(self, callback, **kwargs):
        self.initial_callback = callback
        self.initial_callback_args = kwargs

    async def add_task(self, callback, **kwargs):
        task = asyncio.create_task(callback(**kwargs))
        self.work.append(task)

    async def _run(self):
        while self.work:
            task = self.work.pop()
            await  task
            if len(self.work) == 0:
                await asyncio.sleep(self.wait)

    async def set_things_up(self, callback, **kwargs):
        task = asyncio.create_task(callback(**kwargs))
        self.work.append(task)
        await self._run()

    def go(self):
        asyncio.run(self.set_things_up(self.initial_callback, **self.initial_callback_args))

async def google(n):
    if n == 100:
        return None
    await s.add_task(google, n=n + 1)

    async with aiohttp.ClientSession() as session:
        async with session.get('http://h...content-available-to-author-only...n.org/get') as resp:
            print(resp.status)

t = time.time()
s = MyScheduler(wait=1)
s.set_initial_callback(google, n=1)
s.go()
print(time.time() - t)

I benchmarked this against sequentally running requests, and I did see a massive speed up. It's still super rough, but I'd love some pointers on how  I could improve my code in terms of readability/exploiting async stuff better.


texts: Compute a students grade based on weight of assignments

texts:
Hoping to get feedback on how this program could be written in the most pythonic way. Also welcome any criticisms of styling as I know this is not in accordance with pep-8

from collections import namedtuple
a = namedtuple('assignment', 'weight scores')
def average(scores:list):
    '''average a list of scores'''
    return sum(scores)/len(scores)
def get_grade(grades:list):
    '''compute final grade based on scores and their weights'''
    result = 0
    for a in grades:
        result += average(a.scores) * a.weight
    return result
def main():
   grades = [a(.30, [18/45, 11/55]),
             a(.20, [3/10, 7.5/10, 10/10]),
             a(.10, [9/10, 9/10, 10/10, 10/10, 8/10,
                6/10, 10/10, 10/10]),
             a(.40, [29/65]),
             a(.01, [1/1])]
   print(get_grade(grades))
main()


texts:
I had created hash function library (MD5, MD4, SHA256, SHA384, SHA512, RipeMD128, RipeMD160, CRC16, CRC32, CRC64), written in C++.
Everything working well and My library produces exactly the same output compared to the PHP output. (Except for CRC series)
The individual algorithmic abstraction layers consist of the chash::IAlgorithm interface and chash::IDigest. But I'd like to refine IDigest more elegantly. How can I do it?
https://github.com/whoamiho1006/chash
IAlgorithm.hpp
#pragma once
#include "Macros.hpp"

namespace chash {
    enum class EAlgorithm {
        Unknown     = 0x0000,
        CRC16       = 0x1000,       // --> IBM Poly-Nomial.
        CRC32       = 0x1001,       // --> IEEE 802.3
        CRC64       = 0x1002,       // --> ISO Poly-Nomial.
        SHA256      = 0x2000,
        SHA384      = 0x2001,
        SHA512      = 0x2002,
        MD5         = 0x3000,
        MD4         = 0x3001,
        RipeMD128   = 0x4000,
        RipeMD160   = 0x4001,
    };

    enum class EAlgorithmErrno {
        Succeed = 0,
        InvalidState,
        InvalidDigest
    };

    class IDigest;
    class IAlgorithm {
    public:
        IAlgorithm(EAlgorithm type)
            : _type(type), _errno(EAlgorithmErrno::Succeed)
        {
        }

        virtual ~IAlgorithm() { }

    private:
        EAlgorithm _type;
        EAlgorithmErrno _errno;

    protected:
        inline void setError(EAlgorithmErrno _errno) {
            this->_errno = _errno;
        }

    public:
        /* get algorithm type. */
        inline EAlgorithm type() const { return _type; }

        /* get algorithm state. */
        inline EAlgorithmErrno error() const { return _errno; }

        /* create a new digest. */
        virtual IDigest* create() const = 0;

        /* initiate the algorithm. */
        virtual bool init() = 0;

        /* update the algorithm state by given bytes. */
        virtual bool update(const uint8_t* inBytes, size_t inSize) = 0;

        /* finalize the algorithm. */
        virtual bool finalize(IDigest* outDigest) = 0;

        /* compute hash with digest. */
        virtual EAlgorithmErrno compute(IDigest* outDigest, const uint8_t* inBytes, size_t inSize) {
            if (init()) {
                update(inBytes, inSize);
                finalize(outDigest);
                return error();
            }

            return error();
        }
    };

}

IDigest.hpp
#pragma once
#include "Macros.hpp"
#include <string>

namespace chash {
    class IDigest {
    public:
        virtual ~IDigest() { }

    public:
        /* get bytes pointer. */
        virtual uint8_t* bytes() const = 0;

        /* get size in bytes. */
        virtual size_t size() const = 0;

    public:
        inline std::string toHex() {
            std::string outHex;

            uint8_t* bytes = this->bytes();
            size_t size = this->size();

            outHex.reserve(size << 1);
            for (size_t i = 0; i < size; ++i) {
                int32_t b = bytes[i];

                int32_t fr = b / 16;
                int32_t bk = b % 16;

                if (fr < 10) outHex.push_back('0' + fr);
                else outHex.push_back('a' + (fr - 10));

                if (bk < 10) outHex.push_back('0' + bk);
                else outHex.push_back('a' + (bk - 10));
            }

            return outHex;
        }
    };

    /* Digest in template. */
    template<size_t Size>
    class TDigest : public IDigest {
    public:
        TDigest() {
            for (size_t i = 0; i < Size; ++i)
                _bytes[i] = 0;
        }

    private:
        mutable uint8_t _bytes[Size];

    public:
        /* get bytes pointer. */
        virtual uint8_t* bytes() const { return _bytes; }

        /* get size in bytes. */
        virtual size_t size() const { return Size;  }
    };
}

I have a follow up questions based on the answer by G. Sliepen.


texts:
I have the following problem:

  The stepping number:

  A number is called a stepping number if every adjacent digits, except those separated by commas, differ by 1. A stepping number can't be a 1-digit number, it must be at least a 2-digit number. For example, 45 and 8,343,545 are stepping numbers.
  But, 890,098 is not. The difference between ‘9’ and ‘0’ should
  not be considered as 1.

  Given start number s and an end number e your function should list
  out all the stepping numbers in the range including both the numbers s
  & e.

My Attempt:

public void steppingNumber(int s, int e) {
    while(s <= e) {
        String str = String.valueOf(s);
        if(isSteppingNumber(str)) System.out.print(str + " ");
        s++;
    }
}

public boolean isSteppingNumber(String str) {
    if(str.length() == 1) return false; // 1-digit number can't be a stepping number

    List<String> numbers = new ArrayList<>();

    while(str.length() >= 3) { // get every 3-digit comma-separated number
        numbers.add(str.substring(str.length()-3));
        str = str.substring(0,str.length()-3);
    }
    numbers.add(str); // Also get the last number left

    for(String num : numbers) { // for every 3-digit comma-separated number, check if it's a stepping number
        for(int i = 1; i < num.length(); i++) {
            int previousDigit = Character.getNumericValue(num.charAt(i-1));
            int currentDigit = Character.getNumericValue(num.charAt(i));

            if(Math.abs(previousDigit - currentDigit) != 1) return false;
        }
    }

    return true;
}

If the question were only to check if a number was a stepping number, I think my solution would be fine. However, if I should list all stepping numbers within the range, say 1 to 10^15, then my solution will run linear time, leave alone the checking part. Can anyone give a better solution for the given problem?


texts:
This program generates prime numbers:

prime = int(raw_input("Prime seed:\n\t "))
stop = int(raw_input("Iterations: \n\t"))
for i in xrange(0,stop):
    prime = 2**prime - 1
print prime

These numbers grow incredibly quickly, and it takes a very long time for Python to generate the numbers. The part where it does the computation takes the longest, about a minute. Does anyone have any tips on speeding it up or increasing reliability?


texts: Managing millions of objects in a MMO game server

texts:
A litle context:

This game server is coded entirely on C-with-classes (plain C code using basic C++ features like classes, templates and such, to avoid any possible overhead). At startup the server allocates a big block of memory to hold an awful lot of objects (talking about millions of objects! the map is quite big). I've designed this Object class:

class Object {
    Object* NextObject; // Pointer to first item in our same container (tiles are Map Containers). Can be NULL.
    Object* Container;  // Cannot be NULL, except if we are a Map Container object.
    Object* Content;    // Pointer to our content, if we have, otherwise NULL.
    ObjectType* Type;   // A C array holds all the object types, this points to ours
    int32_t InstanceAttributes[20]; // Can be plain integers or some sort of reference to other object (i.e the Dynamic String Table).
    bool State;

};

Object::Object() {
    State = 0;
    ObjectTableFree.push_front();

}

I decided to use a chunked arrays to store my objects, this way:

#define TABLESIZE 64
#define CHUNKSIZE 32768

ObjectChunk* ObjectTable;
std::forward_list<Object *> ObjectTableFree(TABLESIZE * CHUNKSIZE);

struct ObjectChunk {
    Object Obj[CHUNKSIZE];
};

void InitMap() {
    ObjectTable = new ObjectChunk[TABLESIZE];

    // Here we also read the map from the hard disk, and
}

These tiny "Helpers" as I call them will happily carry out the Object logic. (Of course I will not include them all, these are just so you can get an idea).

Object* CreateObject() {
    if (ObjectTableFree.empty())
        ResizeObjectTable();

    Object* obj = ObjectTableFree.front();
    assert(obj);

    ObjectTableFree.pop_front();
    return obj;
}

Object* AppendObject(Object* Con, ObjectType* Type, bool AsContent) {
    assert(Con);

    Object* obj = CreateObject();
    obj->Container = Con;
    Object->setType(Type);

    if (AsContent) {
        if (Con->Content)
            obj->NextObject = Con->Content;

        Con->NextObject = obj;
        return obj;

    if (Con->NextObject)
        obj->NextObject = Con->NextObject;

    Con->NextObject = obj;
    return obj;

}

When my map loads I append the objects to the map containers and start manipulating them through pointers through the whole code. Please note that even though this is a C++ project, I can't use most of its features because of internal convention.

Is this all-pointer design a smart one?
How could this be redesigned to make it more efficient/faster?.
Is there any way to accomplish this without all those pointers?


texts:
I've always seen the IPrincipal and IIdentity interfaces separately, but I haven't seen any compelling reason for it, so I have my own interface that combines the two:

public interface IUser : System.Security.Principal.IIdentity, System.Security.Principal.IPrincipal {
    string Role { get; set; }
}

Then I implement the interface as:

public class User : IUser {
    public string Role { get; set; }

    public System.Security.Principal.IIdentity Identity {
        get { return this; }
    }

    public string AuthenticationType {
        get { throw new System.NotImplementedException(); }
    }

    public bool IsAuthenticated {
        get { throw new System.NotImplementedException(); }
    }

    public string Name {
        get { throw new System.NotImplementedException(); }
    }

    public bool IsInRole(string role) {
        throw new System.NotImplementedException();
    }
}

Does this smell?  Do I have a security issue here?


texts: One-dimensional convolution using Data.Vector

texts:
As part of some code I've written, I needed to perform a 1-D convolution. This convolution ends up happening quite often, so I wanted to optimise it (in some way other than using a FFT, though I could do this if necessary). I expect that my convolution kernels will be ~100, and the vector they are convolved with ~5k.

module Convolve (convolve) where

import qualified Data.Vector as V

convolve :: Num a => V.Vector a -> V.Vector a -> V.Vector a
convolve xs hs = V.map (V.sum . (V.zipWith (*) (V.reverse hs))) slices
    where
      slices = mkSlices (V.length hs) xs

mkSlices :: Num a => Int -> V.Vector a -> V.Vector (V.Vector a)
mkSlices size vec =
    V.map (paddedSlice size vec)
         (V.iterateN vecLength (+1) (-(size-1)))
    where vecLength = ((V.length vec)) - (-1 * (size -1))

paddedSlice size vec start
    | size == 0 = V.empty
    | start < 0 && (size+start>0) =
        (V.replicate (abs start) 0) V.++ (paddedSlice (size+start) vec 0)
    | start < 0 && (size+start<=0) = V.replicate size 0
    | start > vL = V.replicate size 0
    | (start+size) > vL =
        (V.slice start (vL-start) vec)
        V.++ (V.replicate (start+size-vL) 0)
    | otherwise = V.slice start size vec
    where vL = V.length vec

I don't (yet) have any experience optimising Haskell, and so I don't really know where to start. I asked in #haskell, which led to a few changes, but these did not have a drastic effect.

I was thinking to try Unboxed Vectors, but I don't think that U.Vector (U.Vector a) is possible. (If I'm wrong, it would be good to know!)

I was also thinking that parallelising might be a good idea. In general, is it better to parallelise "inwards" (e.g. call the outermost map as parallel) or "outwards"?


texts: Checking an array is sorted in either order efficiently

texts:
Here is my code, it works fine, just wondering if there any anything to make it even better.

   public static boolean isSorted(int[] arr)
   {
      int n = arr.length;
      int i = 0;
      while (arr[i] == arr[i + 1])  //  same elements at the beginning
         i++;

      if (arr[i] < arr[i + 1])      //  candidate for ascending, non-decreasing
      {
         i++;

         for (; i < n - 1; i++)
         {
            if (arr[i] > arr[i + 1])
               return false;
         }

         return true;
      }

      else                          //  candidate for descending, non-increasing
      {
         i++;

         for (; i < n - 1; i++)
         {
            if (arr[i] < arr[i + 1])
               return false;
         }

         return true;
      }
   }

It works fine, I have just avoided any class or other method.


texts:
This is my table model code style:

public class MyModel extends DefaultTableModel {

static Vector data = new Vector();
static Vector column = new Vector();
Connection conn;
Statement statement;
ResultSet result;

public MyModel() {
super(data, column);
try {
    conn = DriverManager.getConnection(...);
    statement = conn.createStatement();
    result = statement.executeQuery("Select * from table");

    int col = result.getMetaData().getColumnCount();
    for (int i = 1; i <= col; i++) {
        column.add(result.getMetaData().getColumnName(i));
    }

    while (result.next()) {
        Vector newRow = new Vector(col);
        for (int i = 1; i <= col; i++) {
            newRow.add(result.getString(i));
        }
        data.add(newRow);
    }

} catch (SQLException e) {
    e.printStackTrace();
}
}
// create methods for remove and add and edit a JTable selected row

}

//My GUI class that show jtable on own

Is this best way?

What is this way problems?

Any idea to be better?


texts: Ball Entity for a Entity/Component/System Soccer Game

texts:
Here is a code snippet of a class that I be interested to refactor. I was in doubt on how to proceed with the process of instantiation. The original ask was here. After think about it and heard some opinions I end up refactoring and splitting the instantiation in several constructors, one public and all others private. what do you think of this approach?

I take this opportunity to ask you to evaluate other aspects of the code.

public class BallEntity extends UserEntity {
    public static final float SCALE_FACTOR = 0.78f;
    public static final String BALL = "ball";
    private Body ballBody;
    private Camera camera;
    private Sprite ball;
    private Fixture ballFixture;

    public BallEntity(TextureAtlas atlas, RubeSceneHelper rubeSceneHelper, Camera camera) {
        this(ScaledSprite.createUsingHeight(new Sprite(atlas.findRegion(BALL)), SCALE_FACTOR), rubeSceneHelper);
        this.camera = camera;
    }

    private BallEntity(ScaledSprite scaledSprite, RubeSceneHelper rubeSceneHelper) {
        this(scaledSprite.getSprite(), rubeSceneHelper.getBody(BALL), rubeSceneHelper);
    }

    private BallEntity(Sprite sprite, Body ballBody, RubeSceneHelper rubeSceneHelper) {
        this(rubeSceneHelper.getFixture(ballBody, BALL));
        this.ball = sprite;
        this.ballBody = ballBody;
    }

    private BallEntity(Fixture ballFixture) {
        this.ballFixture = ballFixture;
    }

    @Override
    public Array<Component> getComponents() {
        Array<Component> components = new Array<Component>();
        components.add(PositionComponent.newInstance());
        components.add(CameraFollowerComponent.newInstance(camera));
        components.add(SpriteComponent.newInstance(ball));
        components.add(BodyComponent.newInstance(ballBody));
        components.add(BallContextComponent.newInstance());
        return components;
    }

    @Override
    public void init(Entity entity) {
        BodyComponent bodyComponent = entity.getComponent(BodyComponent.class);
        bodyComponent.setPosition(Vector2.Zero);
        ballFixture.setUserData(new FixtureUserData(FixtureType.BALL, entity));
    }
}

public abstract class UserEntity {

    private final Entity entity;
    private boolean wasBuilt = false;
    private Array<Class<? extends Component>> componentClasses;

    protected UserEntity() {
        this.entity = new Entity();
    }

    public final Entity getEntity() {
        if (!wasBuilt) {
            final Array<Component> components = getComponents();
            componentClasses = new Array<Class<? extends Component>>();
            for (Component c : components) {
                entity.add(c);
                componentClasses.add(c.getClass());
            }
            init(entity);
        }
        return entity;
    }

    protected abstract Array<Component> getComponents();

    public Class<? extends Component>[] getComponentClasses() {
        if (!wasBuilt) {
            throw new IllegalArgumentException("It needs to build entity before use it.");
        }
        return componentClasses.toArray();
    }

    /* Override when need to init some components */
    public void init(Entity entity) {

    }

    public void addToEngine (Engine engine){
        engine.addEntity(entity);
    }

}


texts:
This was the exercise:

  Exercise PSD

  Think about a number under 25. Write down the number. If the number is
  even, divide in to two en write down the result below. If the number
  isn’t even (the number is odd) multiply the number with 3 and add 1.
  Write down this number. Repeat until the answer is 1. Write the code
  for this problem.

  Example:

13    14
40    7
20    22
10    11
5     34
16    52
8     26
4     13
2     40
1     20
      10
      5
      16
      8
      4
      2
      1

How can I optimize this code? For example, is it possible to write it shorter or better performance?

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt();
        PSD(i);
    }

    public static void PSD(int x) {
        if(x == 1){
            System.out.println(x);
        }
            else if (x % 2 == 0) {
            System.out.println(x);
                PSD((x / 2));
            } else {
            System.out.println(x);
                PSD((x * 3)+1);
            }
        }
    }


texts:
I am needing to import a tab delimited text file that has 11 columns and an unknown number of rows (always minimum 3 rows).

I would like to import this text file as an array and be able to call data from it as needed, throughout my project. And then, to make things more difficult, I need to replace items in the array, and even add more rows to it as the project goes on (all at runtime).

Hopefully someone can suggest code corrections or useful methods. I'm hoping to use something like the array style sMyStrings(3,2), which I believe would be the easiest way to control my data.

Imports System.IO
Imports Microsoft.VisualBasic.FileIO

Public Class Main
    Dim strReadLine As String

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim sReader As IO.StreamReader = Nothing
    Dim sRawString As String = Nothing
    Dim sMyStrings() As String = Nothing
    Dim intCount As Integer = -1
    Dim intFullLoop As Integer = 0

    If IO.File.Exists("C:\MyProject\Hardware.txt") Then     ' Make sure the file exists
        sReader = New IO.StreamReader("C:\MyProject\Hardware.txt")
    Else
        MsgBox("File doesn't exist.", MsgBoxStyle.Critical, "Error")
        End
    End If

    Do While sReader.Peek >= 0  ' Make sure you can read beyond the current position
        sRawString = sReader.ReadLine()     ' Read the current line
        sMyStrings = sRawString.Split(New Char() {Chr(9)})      ' Separate values and store in a string array

        For Each s As String In sMyStrings      ' Loop through the string array
            intCount = intCount + 1             ' Increment
            If TextBox1.Text <> "" Then TextBox1.Text = TextBox1.Text & vbCrLf ' Add line feed
            TextBox1.Text = TextBox1.Text & s   ' Add line to debug textbox
            If intFullLoop > 14 And intCount > -1 And CBool((intCount - 0) / 11 Mod 0) Then
                cmbSelectHinge.Items.Add(sMyStrings(intCount))
            End If
        Next
        intCount = -1
        intFullLoop = intFullLoop + 1
    Loop
End Sub