texts: Ruby exercise in writing and reading a file

texts:
I've been asked to improve the modular decomposition of the main by moving as many lines of code out of main as possible, but i have no idea how i should do this

# writes the number of lines then each line as a string.
def write_data_to_file(aFile)
   aFile.puts('5')
end

# reads in each line.
def read_data_from_file(aFile)
  puts aFile.gets
end

# writes data to a file then reads it in and prints each line as it reads
def main
  aFile = File.new("mydata.txt", "w") # open for writing
  if aFile  # if nil this test will be false
    write_data_to_file(aFile)
    aFile.close
  else
    puts "Unable to open file to write!"
  end

  aFile = File.new("mydata.txt", "r") # open for reading
  if aFile  # if nil this test will be false
    read_data_from_file(aFile)
    aFile.close
  else
    puts "Unable to open file to read!"
  end
end
```


texts: Converting entire table to JSON data. Is there a better way?

texts:
Building a 'card' database: I'm simply learning to take input data and store to database. Incorporating JSON, PDO, SQL, and enforcing my general coding skills through PHP, hopefully.

$query = $dbh->prepare("SELECT * FROM " . $table);
$query->execute();

$result = $query->fetchAll(PDO::FETCH_CLASS);

$temp = array();
$data = array();

foreach($result as $key => $val){
    foreach($val as $key2 => $val2){
        $temp[$key2] = $val2;
    }
    array_push($data, $temp);
}

echo json_encode($data);

Is there a better way to do what I am attempting?


texts: Simple Stateful LSTM example with arbitrary sequence length

texts:
I'm trying to make a simple example showing how to create a RNN with Keras that accepts as input a sequence of arbitrary length. In my example, the LSTM is trying to classify whether a sequence has started with a 1 or a not.

from keras.models import Sequential
from keras.layers import LSTM, Dense
import numpy as np

def gen_sig(num_samples, seq_len):
    one_indices = np.random.choice(a=num_samples, size=num_samples // 2, replace=False)

    x_val = np.zeros((num_samples, seq_len), dtype=np.bool)
    x_val[one_indices, 0] = 1

    y_val = np.zeros(num_samples, dtype=np.bool)
    y_val[one_indices] = 1

    return x_val, y_val

N_train = 100
N_test = 10
recall_len = 20

X_train, y_train = gen_sig(N_train, recall_len)

X_test, y_test = gen_sig(N_train, recall_len)

print('Build STATEFUL model...')
model = Sequential()
model.add(LSTM(10, batch_input_shape=(1, 1, 1), return_sequences=False, stateful=True))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

print('Train...')
for epoch in range(15):
    mean_tr_acc = []
    mean_tr_loss = []

    for seq_idx in range(X_train.shape[0]):
        start_val = X_train[seq_idx, 0]
        assert y_train[seq_idx] == start_val
        assert tuple(np.nonzero(X_train[seq_idx, :]))[0].shape[0] == start_val

        y_in = np.array([y_train[seq_idx]], dtype=np.bool)

        for j in range(np.random.choice(a=np.arange(5, recall_len+1))):
            x_in = np.array([[[X_train[seq_idx][j]]]])
            tr_loss, tr_acc = model.train_on_batch(x_in, y_in)

            mean_tr_acc.append(tr_acc)
            mean_tr_loss.append(tr_loss)

        model.reset_states()

    print('accuracy training = {}'.format(np.mean(mean_tr_acc)))
    print('loss training = {}'.format(np.mean(mean_tr_loss)))
    print('___________________________________')

    mean_te_acc = []
    mean_te_loss = []
    for seq_idx in range(X_test.shape[0]):
        start_val = X_test[seq_idx, 0]
        assert y_test[seq_idx] == start_val
        assert tuple(np.nonzero(X_test[seq_idx, :]))[0].shape[0] == start_val

        y_in = np.array([y_test[seq_idx]], dtype=np.bool)

        for j in range(np.random.choice(a=np.arange(5, recall_len+1))):
            te_loss, te_acc = model.test_on_batch(np.array([[[X_test[seq_idx][j]]]], dtype=np.bool), y_in)
            mean_te_acc.append(te_acc)
            mean_te_loss.append(te_loss)
        model.reset_states()

    print('accuracy testing = {}'.format(np.mean(mean_te_acc)))
    print('loss testing = {}'.format(np.mean(mean_te_loss)))
    print('___________________________________')

I personally feel this code could be prettier and more efficient. Additionally, the way I'm batching the learning together feels weird. Is there another way to accomplish the same thing?


texts:
I want to write a cleaner version of the code shown below. It's about two different rows consisting of numbers that have to be weaved.

It's for an assignment for a course i'm currently following. This is the assignment:

Traveler, if riches are to be achieved, the solution only has to be weaved.
5,4 4,5 8,7
Weave 6,3 3,2 9,6 4,3
Weave 7,6
Weave 9,8
Weave 5,5 7,8 6,5 6,4

I have to start with the coordinates on the first row, weave the coordinates of the second row through the first row, then weave the coordinates of the third row through the resulting row etc. Note, if two rows of unequal length have to be woven, the two rows are woven as far as possible. After the elements of the shortest row have been exhausted, the row is completed by adding the remaining elements of the longest row.

The input is this:

5,4 4,5 8,7=6,3 3,2 9,6 4,3=7,6=9,8=5,5 7,8 6,5 6,4

The output has to be like this:

6,4
6,5
10,8
8,8
8,6
7,5
7,3
7,4
5,5
4,2
9,7
10,6
5,3

My code is in three files.

Coordinaat.py

class Coordinaat:
    def __init__(self, x_coordinaat, y_coordinaat):
        self.x_coordinaat = x_coordinaat
        self.y_coordinaat = y_coordinaat

    def bereken_nieuw_coordinaat(self):
        self.x_coordinaat += 1
        self.y_coordinaat += 0
        return self.x_coordinaat, self.y_coordinaat

CoordinaatRij.py

class CoordinaatRij:
    def __init__(self, rij):
        self.rij = rij

    def voeg_toe(self,coordinaat):
        self.rij += [coordinaat]

    def breid_uit(self, rij):
        for coordinaat1 in rij:
            self.rij += [coordinaat1]

    def weave(self, weef_rij):
        resultaat = CoordinaatRij([])

        for i in range(len(self.rij)):
            if i < len(self.rij):
                resultaat.voeg_toe(self.rij[i])
            if i < len(weef_rij.rij):
                resultaat.voeg_toe(weef_rij.rij[i])
        if len(weef_rij.rij) > len(self.rij):
            resultaat.breid_uit(weef_rij.rij[len(self.rij):])
        return resultaat

Excerpt of the main code

file_input = file.read()
strip_file = file_input.strip()
invoer = strip_file.split("=")

from Coordinaat import Coordinaat
from CoordinaatRij import CoordinaatRij

def nieuwe_rijen(invoer):
    rijen = []
    for i in range(len(invoer)):
        rijen += [CoordinaatRij(invoer[i].split())]
    vorige_rij = rijen[0]

    for rij in rijen[1:]:
        vorige_rij = vorige_rij.weave(rij)
    return vorige_rij

def nieuwe_coordinaten(geweefde_rijen):
    for coordinaat1 in geweefde_rijen.rij:
        huidige_coordinaten = Coordinaat(int(coordinaat1[0]), int(coordinaat1[2]))
        nieuwe_coordinaten = huidige_coordinaten.bereken_nieuw_coordinaat()
        print '%d, %d' %(nieuwe_coordinaten[0], nieuwe_coordinaten[1])

geweefde_rijen = nieuwe_rijen(invoer)
nieuwe_coordinaten(geweefde_rijen)


texts:
I just started attempting SPOJ problems. And I'm aware of Java using more memory and time compared to most of the other languages. But even some of the solutions in Java have better results than my accepted code. And it hurts!

Here is my accepted code for FASHION with TIME: 0.41 and MEM: 4284M.The best solution in Java for the same question has TIME: 0.04 and MEM: 1398M.

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int i = 0;
        Scanner sc = new Scanner(System.in);
        int testCases = sc.nextInt();
        while (testCases > 0) {
            int modelsWithMe = sc.nextInt();
            int[] men = new int[modelsWithMe];
            int[] women = new int[modelsWithMe];
            int hotnessSum = 0;
            for (i = 0; i < modelsWithMe; i++) {
                men[i] = sc.nextInt();
            }
            for (i = 0; i < modelsWithMe; i++) {
                women[i] = sc.nextInt();
            }
            Arrays.sort(men);
            Arrays.sort(women);
            for (i = 0; i < modelsWithMe; i++) {
                hotnessSum = hotnessSum + men[i] * women[i];
            }
            System.out.println(hotnessSum);
            testCases--;
        }

    }
}

I did see a few questions on performance, such as this and this. I am doing a few of it and some are not applicable for this solution's point of view. Here, maybe, I can read the entire line at once and split the string instead of calling nextInt each time and reduce I/O operations. What else can I do to reach the level of efficiency and speed as that of top answers? Best practices may be?


texts:
I'm still learning C++ and also algorithms. So I'm expecting to do a lot of refactoring. Here's my code

#include <iostream>
#include <vector>
#include <iterator>

std::vector<int> mergesort(std::vector<int> &);
std::vector<int> merge(std::vector<int> &, std::vector<int> &);
std::vector<int>::iterator get_midpoint(std::vector<int> &);

int main()
{
  std::vector<int> vect;
  int num = 0;
  while(std::cin >> num)
  {
    vect.push_back(num);
  }
  std::vector<int> temp_vect = mergesort(vect);
  for(int num: temp_vect) {
    std::cout << num  << std::endl;
  }

}

std::vector<int> mergesort(std::vector<int> &unsorted_vector)
{
  std::vector<int>::iterator middle = unsorted_vector.begin();
  std::vector<int> sorted_vect, first_half, second_half, first_temp, second_temp;
  if(unsorted_vector.size() == 1) {
    return unsorted_vector;
  } else {
    middle = get_midpoint(unsorted_vector);
    first_temp.insert(first_temp.begin(), unsorted_vector.begin(), middle);
    second_temp.insert(second_temp.begin(), middle, unsorted_vector.end());
    first_half = mergesort(first_temp);
    second_half = mergesort(second_temp);
    sorted_vect = merge(first_half, second_half);
    return sorted_vect;
  }
}

std::vector<int> merge(std::vector<int> & first_vect, std::vector<int> & second_vect)
{
  std::vector<int> sorted_vect;
  auto first_it = first_vect.begin(),
        second_it = second_vect.begin();

  while(first_it != first_vect.end() && second_it != second_vect.end()) {
      if(*first_it < *second_it) {
        sorted_vect.push_back(*first_it);
        first_it++;
      } else {
        sorted_vect.push_back(*second_it);
        second_it++;
      }
  }

  sorted_vect.insert(sorted_vect.end(), first_it, first_vect.end());
  sorted_vect.insert(sorted_vect.end(), second_it, second_vect.end());

  return sorted_vect;
}

std::vector<int>::iterator get_midpoint(std::vector<int> &vect)
{
  std::vector<int>::iterator it = vect.begin();
  int middle = 0;
  if(vect.size() % 2 == 0) {
    middle =  vect.size() / 2;
  } else {
    middle = (vect.size() - 1) / 2;
  }
  std::advance(it, middle);
  return it;
}


texts: PHP: multilingual Time::since() static class

texts:
I didn't make the math myself since I'm an idiot. I did however try to make it more versatile and usable for my multilingual page, which involves making it simple to use for advanced plural forms such as Polish and Russian.

Is this code any good to use on a website? or is it overkill?
I'm using the laravel framework, but this code should work everywhere.

I use it like this :

Time::since($user->updated_at)

And here is the code:

class Time
{
public static function since($timestamp) {
    date_default_timezone_set('Europe/Rome');
    $time = strtotime($timestamp);
    $time = time() - $time;

    $tokens = array (
    31536000 => 'year',
    2592000 => 'month',
    604800 => 'week',
    86400 => 'day',
    3600 => 'hour',
    60 => 'minute',
    1 => 'second'
    );

    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        switch ($text)
        {
        case 'year':
        return sprintf(ngettext(
            "Last visit: %d year ago",
            "Last visit: %d years ago",
            $numberOfUnits), $numberOfUnits);
            break;
        case 'month':
            return sprintf(ngettext(
            "Last visit: %d month ago",
            "Last visit: %d months ago",
            $numberOfUnits), $numberOfUnits);
            break;
        case 'week':
            return sprintf(ngettext(
            "Last visit: %d week ago",
            "Last visit: %d weeks ago",
            $numberOfUnits), $numberOfUnits);
            break;
        case 'day':
            return sprintf(ngettext(
            "Last visit: %d day ago",
            "Last visit: %d days ago",
            $numberOfUnits), $numberOfUnits);
            break;
        case 'hour':
            return sprintf(ngettext(
            "Last visit: %d hour ago",
            "Last visit: %d hours ago",
            $numberOfUnits), $numberOfUnits);
            break;
            case 'minute':
            return sprintf(ngettext(
            "Last visit: %d minute ago",
            "Last visit: %d minutes ago",
            $numberOfUnits), $numberOfUnits);
            break;
            case 'second':
            return sprintf(ngettext(
            "Last visit: %d second ago",
            "Last visit: %d seconds ago",
            $numberOfUnits), $numberOfUnits);
            break;
            }
        }
    }
}


texts: Is this a good implementation of a simple "Size" value type

texts:
I have created the value type below to represent the desired size for an image. The Size.Default is used in situations where the image is required in the size it was supplied in, i.e. the image shouldn't be resized.

Is this a good implementation of a value type, especially regarding the IEquatable<T> implementation?

What are your thoughts on the use of the private constructor to create the Default instance?

using System;

public struct Size : IEquatable<Size>
{
    private readonly int _height;
    private readonly int _width;
    private readonly bool _default;

    public static readonly Size Default = new Size(true);

    public int Height
    {
        get { return _height; }
    }

    public int Width
    {
        get { return _width; }
    }

    public bool IsDefault
    {
        get { return _default; }
    }

    private Size(bool isDefault)
    {
        _height = 0;
        _width = 0;
        _default = isDefault;
    }

    public Size(int width, int height)
    {
        _height = height;
        _width = width;
        _default = false;
    }

    public override bool Equals(object obj)
    {
        return this.Equals((Size)obj);
    }

    public bool Equals(Size other)
    {
        if (this._default && other._default)
            return true;

        if (this._default && !other._default)
            return false;

        if (!this._default && other._default)
            return false;

        return this.Width == other.Width && this.Height == other.Height;
    }

    public static bool operator ==(Size left, Size right)
    {
        return left.Equals(right);
    }

    public static bool operator !=(Size left, Size right)
    {
        return !left.Equals(right);
    }

    public static Size Parse(string input)
    {
        var parts = input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length != 2)
            throw new FormatException("Input string was not in a correct format.");

        var x = int.Parse(parts[0]);
        var y = int.Parse(parts[1]);

        return new Size(y, x);
    }
}


texts:
I am fairly new to python, been coding in it for about a year or so. My company is switching from using SAS and a Netezza database for some of our data management. In order to access certain information, I have to load .dat.gz files now using Python3 in unix. In order to access similar information I used to access using basic SQL queries, I now have to import a list of files containing similar information and sort it using python. While this is not an issue for most of the data, there is an instance where I am running into performance issues. In order to access certain data I need, I must load over 300 files to python and try to append them together. This is an issue as the program takes a long time just to load the data. I am currently using pandas read_csv using usecols option to limit the data to the three columns I need. I first used df.append(df2), but it was slow. I then changed the dataframe to list, but that still did not seem to improve performance that much. All together the data contains over 50 Million rows. While I do not expect this program to run in seconds, I would like some help to improve performance where I can.

Just to note it is important to keep the integrity of the original .dat.gz files. The files I read in very in size from 2 rows to 50k rows or more. Any help would be greatly appreciated!

I have tried df.append(df2) and concatenating lists. I also tried appending the data to a new CSV in my working directory so the data would not all be stored while the program was running. That did not improve performance either.

import pandas as pd
import sys

#function to read in directories list from agrv[1]
def import_file_list(file_name):
    file_list = []
    with open(file_name) as f:
        for row in f:
            row = row.strip()
            file_list.append(row)
    return file_list

#main loop to read in all files and append the data
def import_data(list_of_files)
    for count, item in enumerate(list_of_files):
        exposure_data = pd.read_csv(item, sep='|', usecols=['A', 'B', 'C'], compression='gzip')
            if count == 0:
                    data_dict = exposure_data.to_dict('split')
                    values_list = list(data_dict['data'])
            else:
                    temp_dict = exposure_data.to_dict('split')
                    temp_list = list(temp_dict['data'])
                    values_list = values_list + temp_list

def main():
    import_data(import_file_list(sys.argv[1]))

if __name__ == '__main__':
    main()

Expected results would be to loop through all the files I need and combine them to one dataframe, list of lists, dictionary of all the data, or whatever object is most efficient with the three columns I need to do my calculations.


texts: Add functionality to object then remove those functions on export

texts:
Outline

I have a form that needs validation. The problem is that the software requires custom validation that depends on multiple parameters.

I decided to pass the object into a function which will dynamically give the object the functions it needs to be validated.
Then once the validation is completed, I remove those functions from the object.

I'm adding the functions so I can chain them together, which I believe will provide me with great composition.

Usage

This is how I add the functions to the object:

let q = this.validator.validate(this.question)

I can then chain the added functions like this:

q.validateString().cleanUp();

That way my functions are composable and reusable.

Implementation

Now for the actual code to be reviewed:

export class Validator {
    validate(question) {
        let q = Object.assign(
            {},
            question,
            validationOptions
        );

        return q;
    }
}

let validationOptions = {
    validateString,
    cleanUp
};

function validateString() {
    return this;
}

function cleanUp() {
    Object.keys(validationOptions).map((i) => delete this[i]);
    return this;
}

I'm forced to use the class because I need Aurelia Dependency Injection. I compose my functions outside of that class Validator because they only need to work with the this binding.

This code works perfectly, and it executes as expected; however, I do have a few concerns:

Is there a downside to the way I add these functions?
The way I remove these functions works well, but are there better options? I can't use Symbol because I return the q object to another class.


texts: Find maximum number in a nested array using recursion

texts:
Here is my code:

# Credit: https://www.linkedin.com/pulse/ask-recursion-during-coding-interviews-identify-good-talent-veteanu/
#
# Problem:
# Find the maximum number in a jagged array. Each element of the array can be a number or an array of
# other numbers on indefinite number of levels. For example, given an array = [1, [3, 9], 5],
# the maximum number is 9.

def max_number(array):
    if len(array) == 1 and not isinstance(array[0], list):
        return array[0]

    _array = isinstance(array[0], list) or array

    point = len(_array) // 2
    m1 = max_number(_array[:point])
    m2 = max_number(_array[point:])

    if m1 >= m2:
        print(f"m1 = {m1} larger > m2 {m2}")
        return m1
    else:
        print(f"m2 = {m2} larger > m1 {m1}")
        return m2

assert max_number([1,2,3]) == 3
assert max_number([3,2,1]) == 3
assert max_number([2,3,1]) == 3
assert max_number([1, [3, 9], 8]) == 9
assert (max_number(
     [2, 4, 10, [12, 4, [100, 99], 4], [3, 2, 99], 0]) == 100)

This is fine. The minor issue I have with is the additional isinstance check.

Originally when I worked on the solution on paper, I had forgotten
about slicing a Python array [x, [w, z] ] would produce [x], and [ [w, z] ] as opposed to [w, z] for the second recursive call.

The original code looks similar, but like this:

# The original code did not verify whether the "array" argument IS a list.
# It would be this simple:

def max_number(array):
    if len(array) == 1:
        return array[0]

    point = len(array) // 2
    m1 = max_number(array[:point])
    m2 = max_number(array[point:])

    if m1 >= m2:
        print(f"m1 = {m1} larger > m2 {m2}")
        return m1
    else:
        print(f"m2 = {m2} larger > m1 {m1}")
        return m2

Could I do any better than this? Anyway without the isinstance check but still elegant?


texts: Two inputs, two buttons to set variables to input - with .each();

texts:
What it does is simple: the user inputs a from- and a to-value in a field, sets it with ok. With the go-button, the user makes the program count from f to t and adds it to the site. With delete, the user clears the added markup.

I feel I could simplify the two set-functions into one, but I'm quite stuck.

$(document).ready(function(){

    var f, t

    $("#setfrom").click(function(){

        f = parseInt($("#from").val());

        if (isNaN(f)) {
            $("#test").append("
You said you needed numbers, right
");
        } else {$("#test").append("
" + f + "
");
        }
    });

    $("#setto").click(function(){

        t = parseInt($("#to").val());

        if (isNaN(t)) {
            $("#test").append("
You said you needed numbers, right
");
        } else {
            $("#test").append("
" + t + "
");
        }
   });

    $("#count").click(function(){

        $("#num").append("
Okay, here they come:
");

        for (i=f; i<=t; i++) {

            $("#num").append("
" + i + "</div)");
        }
    });

    $("#delnum").click(function(){
    $("#num").empty();
    $("#test").empty();
});

});

Hi, need numbers?

Yes, from

    <input type="text" id="from"></input>
    <button id="setfrom" class="button">OK</button>

to

    <input type="text" id="to"></input>
    <button id="setto" class="button">OK</button>

    <button id="count" class="button">go!</button>
    <button id="delnum" class="button">delete!</button>


texts: JS, TS, handle 3 consecutive ifs / ternaries

texts:
I need to compare a title for 3 strings

here what I'm doing

var textMessage = ""
props.screen == 'dd' ? textMessage = "Next, select the dd " : null
props.screen == 'ff' ? textMessage = "Next, select the ff " : null
props.screen == 'ss' ? textMessage = "Next, select the ss " : null


texts:
I have code that scans our multiple SANS and inserts each file into a mongoDB. The code also checks the database first and if the document exists it updates the document. These are huge file systems and the code does take ages to run so any effeciencies I can squeeze out would be great.

To find existing document and if not insert, is there a better way than:

if collection.find({'file_path': curpath}).count() > 0:
    # update document
elif collection.find({'file_path': curpath}).count() == 0:
    # insert document

Full code:

def scan_for_file(dir_path, storage_bucket):
    for file in os.listdir(dir_path):
        curpath = os.path.join(dir_path, file)
        if os.path.isfile(curpath):
            print('found file:', file)
            print('checking db for:', curpath)
            collection = db.file_collection
            if collection.find({'file_path': curpath}).count() > 0:
                print('found file in db', curpath)
                cursor = collection.find({'file_path': curpath})
                for document in cursor:
                    file_db_id = document['_id']
                    file_db_path = document['file_path']
                    file_accessed = datetime.datetime.fromtimestamp(os.path.getatime(file_db_path))
                    file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(file_db_path))
                    file_created = datetime.datetime.fromtimestamp(os.path.getctime(file_db_path))
                    file_size = os.stat(file_db_path).st_size
                    file_convert_size = convert_size(file_size)
                    utc_datetime = datetime.datetime.utcnow()
                    update_id = collection.update_one(
                {'_id': file_db_id},
                {
                    "$set": {
                        "file_size": file_convert_size,
                        "file_size_bytes": file_size,
                        "process_datestamp": utc_datetime.strftime("%Y-%m-%d %H:%M:%S"),
                        "file_created": file_created,
                        "file_accessed": file_accessed,
                        "file_modified": file_modified
                    },
                },
                upsert=True)
                    update_id
                    print('Updated ID:', file_db_id)

            elif collection.find({'file_path': curpath}).count() == 0:
                print('no file in db:', curpath)
                file_accessed = datetime.datetime.fromtimestamp(os.path.getatime(curpath))
                file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath))
                file_created = datetime.datetime.fromtimestamp(os.path.getctime(curpath))
                file_size = os.stat(curpath).st_size
                file_convert_size = convert_size(file_size)
                utc_datetime = datetime.datetime.utcnow()
                post = {"storage_bucket": storage_bucket,
                "dir_path": dir_path,
                "file_path": curpath,
                "file_name": file,
                "file_size": file_convert_size,
                "file_size_bytes": file_size,
                "process_datestamp": utc_datetime.strftime("%Y-%m-%d %H:%M:%S"),
                "file_created": file_created,
                "file_accessed": file_accessed,
                "file_modified": file_modified}
                posts = db.file_collection
                post_id = posts.insert_one(post).inserted_id
                post_id
                print('New posted ID:', post)
            else:
                print('error')


texts:
I have been trying to deal with this problem set, and I have figured out how to solve it as well. But there is one problem that is Timeout error for some hidden cases, but no wrong answers

PROBLEM STATEMENT

In this challenge, a string and a list of intervals are given. The string consists of English letters only and it can contain both lowercase and uppercase letters.

For two different letters, we say that the first letter is greater than the second letter when the first letter comes later in the alphabet than the second letter ignoring the case of the letters. For example, the letter 'Z' and 't' are greater than the letters 'b' and 'G', while the letters 'B' andd 'b' are equal as case is not considered.

The task is the following. For each given interval, you need to find the count of the greatest letter occurring in the string in that interval, ignoring the case of the letters, so occurrences of, for example, a and A are occurrences of the same letter.

Consider, for example, for the string "AbaBacD". In the interval, [0, 4], the greatest letter is 'b' with count 2.

Input Format

The first line contains integer N, denoting the length of the input string.

The second line contains string S.

The third line contains an integer Q, denoting the number of intervals. Each line of the  Q subsequent lines contains two space-separated integers xi and yi, denoting the beginning and the end of ith interval.

Output Format

For each interval, print the count of the greatest letter occurring in the string in that interval.

My Algorithm

1. To lowercase the string
2. Loop through the queries array
3. Get the string from start interval to end interval
4. Find greatest char in the string
5. Count the occurrence, and add it to the array
6. Return the array

My Code

def getMaxCharCount(s, queries):
    # queries is a n x 2 array where queries[i][0] and queries[i][1] represents x[i] and y[i] for the ith query.
    maxCount = []
    finalWord = s.lower()
    for interval in queries:
        if interval[0] == interval[1]:
            maxCount.append(1)
        else:
            string = finalWord[interval[0]:interval[1]+1]
            maxCount.append(string.count(max(string)))
    return maxCount

Any help would be appreciated


texts:
I was teaching some new people in office a bit of COBOL, so I threw together this exercise where they had to write a program that would generate the first 10 numbers of a Fibonacci suite and then test them against the rules of fizzbuzz.

I was hoping to get an honest review of this code to see how I could improve.

   IDENTIFICATION DIVISION.
   PROGRAM-ID. PROG6.
   AUTHOR.        SAGGING RUFUS.
   DATE-WRITTEN.  JUNE 5 2017.
   DATE-COMPILED.
   TITLE "FIZZBUZZONACCI"

   ENVIRONMENT DIVISION.
   CONFIGURATION SECTION.
   SOURCE-COMPUTER.   AMDAHL-580.
   OBJECT-COMPUTER.   AMDAHL-580.

   DATA DIVISION.
   WORKING-STORAGE SECTION.
   01  WS-STORAGE.
       05 WS-SUB PIC 9(8) COMP.
       05 WS-LIMIT PIC 9(4) VALUE 10.
       05 WS-F.
          10 WS-FX PIC 9(8) COMP.
          10 WS-F1 PIC 9(8) COMP VALUE 0.
          10 WS-F2 PIC 9(8) COMP VALUE 1.
       05 WS-F-ARRAY      PIC 9(8) COMP OCCURS 10 TIMES.
       05 WS-F-SUB        PIC 9(8) COMP VALUE 0.

   01  COUNTERS.
       05 CURRENT-NUM PIC 9(3) COMP.

   01  REMAINDERS.
       05 MOD-THREE PIC 99 COMP.
          88 FIZZ VALUE 0.
       05 MOD-FIVE PIC 99 COMP.
          88 BUZZ VALUE 0.

   PROCEDURE DIVISION.

   0000-MAINLINE.
       PERFORM VARYING WS-SUB
                  FROM 1 BY 1
                 UNTIL WS-SUB > WS-LIMIT
          COMPUTE
             WS-FX = WS-F1 + WS-F2
          END-COMPUTE

          ADD 1 TO WS-F-SUB

          MOVE WS-F2 TO WS-F1
          MOVE WS-FX TO WS-F2
          MOVE WS-FX TO WS-F-ARRAY(WS-F-SUB)
       END-PERFORM

       PERFORM VARYING WS-SUB
                  FROM 1 BY 1
                 UNTIL WS-SUB > WS-LIMIT
          MOVE WS-F-ARRAY(WS-SUB) TO CURRENT-NUM

          COMPUTE
             MOD-THREE = FUNCTION MOD(CURRENT-NUM 3)
          END-COMPUTE

          COMPUTE
             MOD-FIVE = FUNCTION MOD (CURRENT-NUM 5)
          END-COMPUTE

          EVALUATE TRUE
             WHEN FIZZ AND BUZZ
                DISPLAY "FIZZBUZZ"
             WHEN FIZZ
                DISPLAY "FIZZ"
             WHEN BUZZ
                DISPLAY "BUZZ"
             WHEN OTHER
                DISPLAY CURRENT-NUM
          END-EVALUATE
       END-PERFORM

       STOP RUN.


texts: A more efficient/cleaner way of scrolling a div's contents in HTML

texts:
My current code for scrolling an image contained within a div is:

This was designed some time ago, and I was thinking that there must be a better way of writing it now.

Since my project requires performance over looks, I want to have a high performing page, but still with little animations like this.

Is there a more efficient way of creating something like this?


texts:
I am programming a parallel tree algorithm where I have to send data to other processors. The amount of data is not constant. Therefore I have to work with dynamic arrays using malloc() and realloc(). Since I am new to C I wondered if I am doing it right. I do not get any error. But I think that is not proof enough, that it works all the time. How could I really test this code? Do I have memory leaks? Do I occupy to much memory with this method?

Here I have an array containing 10 double values. Then I want add 3 new double values to that array. Finally I want to delete the whole array.

Here is my code:

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

int main(){
    int n = 10;
    double *p;

    p = malloc(sizeof(*p)*n); // similar to int array[n]
    if(p==NULL){
        printf("Error! Memory not allocated.");
        return 1;
    }
    for(int i=0; i<n; i++)
        printf("%lf\n", p[i]);
    printf("\n");

    int add = 3;
    double *temp;
    temp = realloc(p,(n+add)*sizeof(*temp));
    if(temp != NULL){
        p = temp;
    }else{
        free(p);
        printf("Error! Memory not reallocated\n");
        return 1;
    }
    for(int i=0; i<n+add; i++)
        printf("%lf\n", p[i]);

    return 0;
    free(p);
}

I tried to check the size of the arrays before and after reallocation. But it seems to me that this is not possible in C.


texts: Creating a thread-safe list using a Lock object

texts:
Will this code qualify for a truly thread-safe list?  It is using the Lock object.

using System;
using System.Collections.Generic;
using System.Threading;

public class ThreadSafeListWithLock<T> : IList<T>
{
    private List<T> internalList;

    private readonly object lockList = new object();

    private ThreadSafeListWithLock()
    {
        internalList = new List<T>();
    }

    // Other Elements of IList implementation

    public IEnumerator<T> GetEnumerator()
    {
        return Clone().GetEnumerator();
    }

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

    public List<T> Clone()
    {
        ThreadLocal<List<T>> threadClonedList = new ThreadLocal<List<T>>();

        lock (lockList)
        {
           internalList.ForEach(element => { threadClonedList.Value.Add(element); });
        }

        return (threadClonedList.Value);
    }

    public void Add(T item)
    {
        lock (lockList)
        {
           internalList.Add(item);
        }
    }

    public bool Remove(T item)
    {
        bool isRemoved;

        lock (lockList)
        {
            isRemoved = internalList.Remove(item);
        }

        return (isRemoved);
    }

    public void Clear()
    {
        lock (lockList)
        {
            internalList.Clear();
        }
    }

    public bool Contains(T item)
    {
        bool containsItem;

        lock (lockList)
        {
            containsItem = internalList.Contains(item);
        }

        return (containsItem);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        lock (lockList)
        {
            internalList.CopyTo(array,arrayIndex);
        }
    }

    public int Count
    {
        get
        {
            int count;

            lock ((lockList))
            {
                count = internalList.Count;
            }

            return (count);
        }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }

    public int IndexOf(T item)
    {
        int itemIndex;

        lock ((lockList))
        {
            itemIndex = internalList.IndexOf(item);
        }

        return (itemIndex);
    }

    public void Insert(int index, T item)
    {
        lock ((lockList))
        {
            internalList.Insert(index,item);
        }
    }

    public void RemoveAt(int index)
    {
        lock ((lockList))
        {
            internalList.RemoveAt(index);
        }
    }

    public T this[int index]
    {
        get
        {
            lock ((lockList))
            {
                return internalList[index];
            }
        }
        set
        {
            lock ((lockList))
            {
                internalList[index] = value;
            }
        }
    }
}


texts:
Let a,b,c be a boolean value. I need to print all values of expression a && b && c. I'm writing the class

public class BooleanTriple{
    private boolean a,b,c;
    public BooleanTriple(boolean a, boolean b, boolean c){ this.a =a; this.b=b; this.c=c;}

    /**
    *Increments the value of triple with lexicographical ordering
    */
    public void incr(){
        if (!a) a=true;
        else if(!b){
            a= false;
            b= true;
        else if (!c){
            a= false;
            b= false;
            c=true;
        }
    }
    public boolean logProduct(){ return a && b && c;}
}

And Main class:

public class Main{
    BooleanTriple bTriple = new BooleanTriple(false,false,false);
    public static void main(String[] args){
        for (int i=0; i<8; i++){
            System.out.println(bTriple.logProduct());
            bTriple.incr();
        }
    }
}

But i think, that it's bad implementation. Can you correct me?


texts:
I've tried to do some BDD in Golang using Godog.

File Hello.feature:

Feature: Hello World

  Scenario: Hello World
    When running hello
    Then it prints:
    """
    Hello, world!

    """

File hello_test.go:

package main

import (
    "bytes"
    "fmt"
    "github.com/DATA-DOG/godog"
    "github.com/DATA-DOG/godog/gherkin"
)

var InterceptedStdout bytes.Buffer

func runningHello() error {
    hello(&InterceptedStdout)
    return nil
}

func itPrints(expectedDocString *gherkin.DocString) error {
    var actual = InterceptedStdout.String()
    var expected = expectedDocString.Content
    if expected != actual {
        return fmt.Errorf("expected: \"%s\", Actual: \"%s\"", expected, actual)
    }
    return nil
}

//noinspection GoUnusedExportedFunction
func FeatureContext(s *godog.Suite) {
    s.Step(`^it prints:$`, itPrints)
    s.Step(`^running hello$`, runningHello)
}

File main.go:

package main

import (
    "fmt"
    "io"
    "os"
)

func main() {
    hello(os.Stdout)
}

func hello(out io.Writer) {
    fmt.Fprintln(out, "Hello, world!")
}


texts: Finding the order of sorting of an array

texts:
I am finding the order of sorting of an array. The code works but can it be made better especially the return values of the function findSortOrder.

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

// Returns 0 for unsorted, 1 for sorted in increasing order, 2 for sorted in decreasing order
int findSortOrder(int array[], int len)
{
    // holds the sorting order of the subarray array[0...i]
    // 0 represents no information about sorting order
    // 1 represents sorting in increasing order
    // 2 represents sorting in decreasing order
    int order = 0;
    int i;
    for (i = 1; i < len; i++)
    {
        if (order == 0)
        {
            if (array[i] > array[i - 1])
            {
                order = 1;
            }
            else if (array[i] < array[i - 1])
            {
                order = 2;
            }
        }
        else if (order == 1)
        {
            if (array[i] < array[i - 1])
            {
                return 0;
            }
        }
        else
        {
            if (array[i] > array[i - 1])
            {
                return 0;
            }
        }
    }
    if (order == 0 || order == 1)
    {
        return 1;
    }
    else
    {
        return 2;
    }
}

int main()
{
    printf("Enter length of the array: ");
    int len;
    scanf("%d", &len);
    int* input = malloc(len * sizeof(*input));
    int i;
    for (i = 0; i < len; i++)
    {
        scanf("%d", &input[i]);
    }
    int order = findSortOrder(input, len);
    switch (order)
    {
        case 0:
            printf("Unsorted\n");
            break;
        case 1:
            printf("Sorted in increasing order\n");
            break;
        case 2:
            printf("Sorted in decreasing order\n");
            break;
    }
    free(input);
    return 0;
}

Edit:
I will be using this function to merge two sorted arrays in their sorting order. So I think if no. of elements is 1 or all are equal then sort order could be returned as increasing.


texts:
i'm a beginner and this is the second program that i have written by myself from scratch, i wrote a basic snake game with PYgame but i didn't do it by myself, so anyway, what do you guys think of this? i want honest opinions, no sugar-coating ! does it have any problems? is there any improvements that can be done?

import random
print "Guess my number!"
print " What's your name?"
user_name = raw_input()
print "Hello %s, i'm thinking of a number between 1 and 20." %(user_name)
def gameloop():
    random_number = random.randrange(1,21)
    print "Take a guess."
    vectory_message = "Well done %s, You beat me!" %(user_name)
    defeat_message = "Sorry %s, You lost!" %(user_name)
    attempts = 0
    maximum_attempts = 7
    user_number = int(raw_input())
    attempts += 1
    print "You have %s  lives left." %(maximum_attempts - attempts)
    while True:
        if user_number == random_number:
            print vectory_message
            attempts = 0
            second_chance()

        elif user_number > random_number:
            user_number  = int(raw_input("A bit lower ..."))
            attempts += 1
            if attempts == maximum_attempts:
                print defeat_message
                second_chance()
            print "You have %s  lives left." %(maximum_attempts - attempts)
            continue

        elif user_number < random_number:
            user_number = int(raw_input("Guess higher ..."))
            attempts += 1
            if attempts == maximum_attempts:
                print defeat_message
                second_chance()
            print "You have %s  lives left." %(maximum_attempts - attempts)
            continue

def second_chance():
    while True:
        choice = raw_input("wanna give it another shot?(y/n)")
        if choice == "y":
            gameloop()
        elif choice == "n":
            quit()
        else:
            print "That wasn't a (y) or (n)!, Try again."
            continue
gameloop()


texts: Convert integer to full text string duration

texts:
I have a function I have written in VB for use in SSRS 2012. It takes an integer and converts it to full text duration - for example 900 becomes "15 minutes", 9000 becomes "2 hours 30 minutes", and 7201 is "2 hours 1 second".

The code works, and is:

Public Function SecondsFullText(ByVal TotalSeconds As Integer) As String

    Dim hours As Integer = new Integer()
    Dim minutes As Integer = new Integer()
    Dim seconds As Integer = new Integer()

    Dim hourString as String = ""
    Dim minuteString as String = ""
    Dim secondString as String = ""

    hours = floor(TotalSeconds / 3600)
    minutes = floor((TotalSeconds mod 3600) / 60)
    seconds = (TotalSeconds mod 3600) mod 60

    If hours = 1 Then
        hourString = Cstr(hours) & " hour"
    Else If hours > 1 Then
        hourString = Cstr(hours) & " hours"
    End If

    If minutes = 1 Then
        minuteString = Cstr(minutes) & " minute"
    Else If minutes > 1 Then
        minuteString = Cstr(minutes) & " minutes"
    End If

    If seconds = 1 Then
        secondString = Cstr(seconds) & " second"
    Else If seconds > 1 Then
        secondString = Cstr(seconds) & " seconds"
    End If

    If hours > 0 and (minutes > 0 or seconds > 0) Then
        hourString = hourString & " "
    End If

    If minutes > 0 and seconds > 0 Then
        minuteString = minuteString & " "
    End If

    return hourString & minuteString & secondString
End Function

My question is: how do I make this better? It seems very clunky, with too many IFs to handle the different possibilities for single/plural, spaces, etc.  I feel that this can be better, but I'm not sure how.

This is called in Report Builder 3.0 / SSRS 2012 with this expression: =Code.SecondsFullText(Parameters!Integer.Value)


texts: Clockwise spiral traversal of 2D input matrix

texts:
I found this interview question online at Pramp:

  Given a 2D array (matrix) inputMatrix of integers, create a function spiralCopy that copies inputMatrix’s values into a 1D array in a spiral order, clockwise. Your function then should return that array. Analyze the time and space complexities of your solution.

  Example:

inputMatrix = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15],
    [16, 17, 18, 19, 20]
]

  output:

[1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12]

  Constraints:

  1 ≤ inputMatrix[0].length ≤ 100
  1 ≤ inputMatrix.length ≤ 100

My solution

def spiral_copy(inputMatrix):
    output = []

    top_row = 0
    bottom_row = len(inputMatrix) - 1
    left_col = 0
    right_col = len(inputMatrix[0]) - 1

    while top_row <= bottom_row and left_col <= right_col:

        for i in range(left_col, right_col + 1):
            output.append(inputMatrix[top_row][i])
        top_row += 1

        for i in range(top_row, bottom_row + 1):
            output.append(inputMatrix[i][right_col])
        right_col -= 1

        if top_row > bottom_row: break

        for i in range(right_col, left_col - 1, -1):
            output.append(inputMatrix[bottom_row][i])
        bottom_row -= 1

        if left_col > right_col: break

        for i in range(bottom_row, top_row - 1, -1):
            output.append(inputMatrix[i][left_col])
        left_col += 1

    return output

Passed these Test cases:

Input
[[1,2],[3,4]]
Expected Result
[1, 2, 4, 3]
Input
[[1,2],[3,4]
Expected Result
[1, 2, 4, 3]

Input
[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Expected Result
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

input
[[1,2],[3,4]
Expected Result
[1, 2, 3, 4, 5, 6, 12, 18, 17, 16, 15, 14, 13, 7, 8, 9, 10, 11]

Input
[[1,0],[0,1]]
Expected Result
[1, 0, 1, 0]

Input
[[1,2,3],[4,5,6],[7,8,9]]
Expected Result
[1, 2, 3, 6, 9, 8, 7, 4, 5]


texts: Angularjs alertservice and alertscontroller

texts:
I'm a .net programmer with littler experience in AngularJs and Javascript.

I have implemented an AlertService, AlertsController and Alerts view for alerts/notifications in my system. PaymentService is a service that uses the alert service to notify user of things.

Could you please give me any comments about my code?
Am I following best practises in AngularJs and Javascript?
Should I handle errors in my services?

Here is my code:

alertService.js

'use strict';

app.service('AlertService', function () {

    var handlers = [];

    this.subscribe = function (handler) {
        handlers.push(handler);
    }

    this.success = function (message) {
        pushAlert({ type: 'success', message: message });
    };

    this.info = function (message) {
        pushAlert({ type: 'info', message: message });
    };

    this.warning = function (message) {
        pushAlert({ type: 'warning', message: message });
    };

    this.danger = function (message) {
        pushAlert({ type: 'danger', message: message });
    };

    function pushAlert(alert) {
        handlers.forEach(function (handler) {
            handler(alert);
        });
    }
});

alertsController.js

'use strict';

app.controller('AlertsController', ['$scope', 'AlertService', function ($scope, alertService) {

    $scope.alerts = [];

    alertService.subscribe(function (alert) {
        $scope.alerts.push(alert);
    });

    $scope.closeAlert = function(index) {
         $scope.alerts.splice(index, 1);
    };

}]);

alerts.html

<div ng-controller="AlertsController">
    <uib-alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.message}}</uib-alert>
</div>

paymentService.js

'use strict';

app.service('PaymentService', ['$http', 'AlertService',
    function ($http, alertService) {
        this.pay = function (id, paymentMethod, numberOfInstallments, creditCard, pin) {
            return $http.post('/api/payment',
                {
                    id: id,
                    paymentMethod: paymentMethod,
                    numberofInstallments: numberOfInstallments,
                    creditCard: creditCard,
                    pin: pin
                })
                .then(success, error);

            function success() {
                alertService.success('Payment confirmed.');
            }

            function error(response) {
                alertService.success(response.data);
            }
        };
    }
]);


texts: Concatenate strings (originally binary) in 8-character chunks, 2 per row

texts:
Here is the code I would like reviewed:

int lines = 4; //Example
string input = "81111111822222228333333384444444" //Example

//Use a StringBuilder to make it easier when producing the formatted code
var stringBuilder = new StringBuilder();

//Loop through the ASM Hex code and extract every 8 character and put them in 2 by 2 rows
//Also add a NOP as needed depending if it's Odd or Even
for (int i = 0; i < lines; i++)
{
    string tempString = input.Substring(i * 8, 8);

    if (i % 2 == 1)
        stringBuilder.AppendLine(tempString);
    else
        stringBuilder.Append(tempString + " ");
}

//End Code with "000000" or "60000000 00000000" if empty line, needed for Gecko
if (lines % 2 == 1)
    stringBuilder.Append("00000000").AppendLine();
else
    stringBuilder.Append("60000000 00000000").AppendLine(); //This would be True in this Example (4 = Equal number)

    //Return the result
    return stringBuilder.ToString();

//stringBuilder.ToString() =
//           "81111111 82222222
//            83333333 84444444
//            60000000 00000000"

What I am doing is basically what the comments says. What might be worth knowing is that originally the string that I want to format is read from a file as hex.

//"hex" is "input" in the first part.
var ba = File.ReadAllBytes($"temp{i}.o");

string hex = BitConverter.ToString(ba).Replace("-", "");
hex = hex.Substring(104, lines * 8); //Remove Garbage data and read only what we want (8 in length * rows of ASM)

I'm not sure if there is a more efficient way of handling the data more directly via that.

I don't think my approach now is bad, but it feels a bit "overkill". It feels like I could probably just read the data I want directly and split up the bytes or something. Sadly, I don't have the skills to know if that is something one should be doing in this case.

lines is an integer which contains the rows from a text. It's simply used for the formatting as one line = 8 characters of the wanted text (hex).

An example of hex text would be something like:

81111111822222228333333384444444855555558666666687777777

It's simplified so it's easier to tell (each Code starts with 8 in this example).

What I want it to turn into in this case would be:

81111111 82222222
83333333 84444444
85555555 86666666
87777777 00000000

And if (8xxxxxxx) actually took up both 2 lines in the row, I would add:

60000000 00000000

The original code is of no interested as it's completely different (Assembly). The only useful part is the rows of code because one row of Assembly = 8 hex characters.


texts: Expression tree creation from postfix expression

texts:
Given a postfix expression, construct an expression tree. Looking code code review, optimizations and best practices.

public class ExpressionTree {

    private final String postfix;
    private TreeNode root;

    /**
     * Takes in a valid postfix expression and later its used to construct the expression tree.
     * The posfix expression, if invalid, leads to invalid results
     *
     * @param postfix   the postfix expression.
     */
    public ExpressionTree(String postfix) {
        if (postfix == null) { throw new NullPointerException("The posfix should not be null"); }
        if (postfix.length() == 0)  { throw new IllegalArgumentException("The postfix should not be empty"); }
        this.postfix = postfix;
    }

    private static class TreeNode {
        TreeNode left;
        char ch;
        TreeNode right;

        TreeNode(TreeNode left, char ch, TreeNode right) {
            this.left = left;
            this.ch = ch;
            this.right = right;
        }
    }

    private boolean isOperator(char c) {
        return c == '+' || c == '-' || c == '*' || c == '/';
    }

    /**
     * Constructs an expression tree, using the postfix expression
     */
    public void createExpressionTree() {
        final Stack<TreeNode> nodes = new Stack<TreeNode>();
        for (int i = 0; i < postfix.length(); i++) {
            char ch  = postfix.charAt(i);
            if (isOperator(ch)) {
               TreeNode rightNode = nodes.pop();
               TreeNode leftNode = nodes.pop();
               nodes.push(new TreeNode(leftNode, ch, rightNode));
            } else {
                nodes.add(new TreeNode(null, ch, null));
            }
        }
        root = nodes.pop();
    }

    /**
     * Returns the prefix notation
     *
     * @return the prefix notation
     */
    public String prefix() {
        if (root == null) {
            throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
        }

        final StringBuilder prefix = new StringBuilder();
        preOrder(root, prefix);
        return prefix.toString();
    }

    private void preOrder(TreeNode node, StringBuilder prefix) {
        if (node != null) {
            prefix.append(node.ch);
            preOrder(node.left, prefix);
            preOrder(node.right, prefix);
        }
    }

    /**
     * Returns the infix expression
     *
     * @return  the string of infix.
     */
    public String infix() {
        if (root == null) {
            throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
        }
        final StringBuilder infix = new StringBuilder();
        inOrder(root, infix);
        return infix.toString();
    }

    private void inOrder(TreeNode node, StringBuilder infix) {
        if (node != null) {
            inOrder(node.left, infix);
            infix.append(node.ch);
            inOrder(node.right, infix);
        }
    }

    public static void main(String[] args) {
        ExpressionTree expressionTree1 = new ExpressionTree("AB*CD/+");
        expressionTree1.createExpressionTree();
        assertEquals("+*AB/CD", expressionTree1.prefix());
        assertEquals("A*B+C/D", expressionTree1.infix());

        ExpressionTree expressionTree2 = new ExpressionTree("ABC+*D/");
        expressionTree2.createExpressionTree();
        assertEquals("/*A+BCD", expressionTree2.prefix());
        assertEquals("A*B+C/D", expressionTree2.infix());

        ExpressionTree expressionTree3 = new ExpressionTree("ABCD/+*");
        expressionTree3.createExpressionTree();
        assertEquals("*A+B/CD", expressionTree3.prefix());
        assertEquals("A*B+C/D", expressionTree3.infix());
    }
}


texts: Parsing very simple CSS into selector and declarations (as as single piece)

texts:
The last part of my HTML genrator requries a few styles. Because all styles are inline and the styling is for emails there won't be any fancy selectors, just by element, id or class.

The most complex css might look like this:

var css = @"
h1 {
    font-family: Sans-Serif; color: green; font-weight: normal; margin-top: 1.5em;
}
h2 {
    font-family: Sans-Serif; color: green; font-weight: normal; margin-top: 1.5em;
}
#foo, p {
    font-family: Sans-Serif; color: green;
}
hr, .foo {
    border: 0; border-bottom: 1px solid #ccc; background: #ccc;
}";

I read it into a dictionary that the StyleVisitor will consume and applay.

static class Css
{
    public static IDictionary<string, string> Parse(string css)
    {
        return
            Regex
                // Match "selector { declarations }"
                .Matches(css.Minify(), @"(?<selectors>[a-z0-9_\-\.,\s#]+)\s*{(?<declarations>.+?)}", RegexOptions.IgnoreCase)
                .Cast<Match>()
                .Select(m => Regex
                    // Split selectors separated by ",".
                    .Split(m.Groups["selectors"].Value, @",")
                    // Skip empty results.
                    .Where(s => !string.IsNullOrEmpty(s))
                    .Select(selector => new KeyValuePair<string, string>(
                        key: selector.Trim().ToLowerInvariant(),
                        value: m.Groups["declarations"].Value.Trim())))
                .SelectMany(x => x)
                .ToDictionary(x => x.Key, x => x.Value);
    }

    private static string Minify(this string css) => Regex.Replace(css, @"(\r\n|\r|\n)", string.Empty);
}

I'm assuming the css does not require any vaidation because it's been created and validated with an editor like jsfiddle etc.

The result of Css.Parse(css) is

h1    font-family: Sans-Serif; color: green; font-weight: normal; margin-top: 1.5em;
h2    font-family: Sans-Serif; color: green; font-weight: normal; margin-top: 1.5em;
#foo  font-family: Sans-Serif; color: green;
p     font-family: Sans-Serif; color: green;
hr    border: 0; border-bottom: 1px solid #ccc; background: #ccc
.foo  border: 0; border-bottom: 1px solid #ccc; background: #ccc


texts: Take all underlined words, put in Excel column

texts:
I have a 100+ page Word document, that I would like to extract all of the underlined words from.  I am very familiar with VBA and Excel, but relatively new to Word. I was wondering if this is the best way to do what I'm trying.

I will run this from my Word document:

Sub extractUnderlinedWords()
Dim thisDoc As Word.Document
Application.ScreenUpdating = False
Dim appExcel As Object, oxlWbk As Object
Dim FN      As String
Dim aRange  As Range
Dim intRowCount As Integer
intRowCount = 1

Set thisDoc = ActiveDocument
Set aRange = thisDoc.Range

Set appExcel = CreateObject("Excel.application")
FN = "C:\Users\[blah]\UnderlinedWords.xlsx"

If FileExists(FN) Then
    Set oxlWbk = appExcel.workbooks.Open(fileName:=FN).Sheets("Sheet1")
End If

With aRange.Find
    Do
        .Font.Underline = True
        .Execute
        If .Found Then
            '   aRange.Expand Unit:=wdSentence
            '      aRange.Select
            If Len(aRange) > 1 Then
                If Not aRange.InRange(thisDoc.TablesOfContents(1).Range) Then
                    aRange.MoveEndWhile cset:=Chr(13), Count:=wdBackward
                    '    aRange.Copy
                    oxlWbk.Cells(intRowCount, 1).Value = aRange.Text
                    aRange.Collapse wdCollapseEnd
                    Debug.Print "Page: " & aRange.Information(wdActiveEndAdjustedPageNumber)
                    '    aRange.Select
                    If oxlWbk Is Nothing Then
                        intRowCount = 1
                    End If
                    'oxlWbk.Cells(intRowCount, 1).Value = aRange.Text
                    ' oxlWbk.Paste
                    intRowCount = intRowCount + 1
                End If
            End If
        End If
    Loop While .Found
End With
If Not oxlWbk Is Nothing Then
    appExcel.workbooks(1).Close True
    appExcel.Quit
    Set oxlWbk = Nothing
    Set appExcel = Nothing
End If
Set aRange = Nothing
Application.ScreenUpdating = True
MsgBox ("Done!")
End Sub

This does work, but after about page 14, it hangs up and "freezes" on me.

Should I instead, add all found words to an Array, then after it's done scanning the Word document, focus on Excel and outputting the parts of array row by row?  I think perhaps what's causing the freeze is the jumping back and forth from Word to Excel.  (Or, could it be that I'm using a Do/While loop?)

Again, the idea is to take all underlined words and put in an Excel sheet for reviewing.


texts:
I've implemented a stack using a queue.

Time complexity:

\$O(n)\$ - push(), where n is the number of elements in the queue

\$O(1)\$ - pop()

Space complexity:

\$O(n)\$ - n is the number of elements in the queue.

I'm looking for optimizations, code review and best practices.

public class StackUsingQueue<T> {

    private Queue<T> queue1;
    private Queue<T> queue2;

    public StackUsingQueue() {
        queue1 = new LinkedList<T>();
        queue2 = new LinkedList<T>();
    }

    public synchronized void push(T x) {
        queue2.add(x);
        queue2.addAll(queue1);
        // swapping references rather than copying from q2 into q1.
        queue1 = queue2;
        queue2 = new LinkedList<T>();
    }

    public synchronized T pop() {
        return queue1.poll();
    }

    public static void main(String[] args) {
        StackUsingQueue<Integer> isuq = new StackUsingQueue<Integer>();
        isuq.push(10);
        isuq.push(20);
        isuq.push(30);

        System.out.println(isuq.pop());
        System.out.println(isuq.pop());
        System.out.println(isuq.pop());
    }
}


texts:
Is this okay?

public class BaseRepository<T> where T : class
{
    private readonly DbContext _dbContext;

    public BaseRepository(DbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public T Get(Func<T, bool> predicate)
    {
        return GetAll(predicate).FirstOrDefault();
    }

    public IEnumerable<T> GetAll(Func<T, bool> predicate = null)
    {
        IEnumerable<T> result = _dbContext.Set<T>().AsEnumerable();
        return (predicate == null) ? result : result.Where<T>(predicate);
    }

    public void Add(T entity)
    {
        _dbContext.Entry(entity).State = EntityState.Added;
    }

    public void Delete(Func<T, bool> predicate)
    {
        IEnumerable<T> entities = GetAll(predicate);
        foreach (T entity in entities)
            _dbContext.Entry(entity).State = EntityState.Deleted;
    }

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

    public void Update(T entity)
    {
        _dbContext.Entry(entity).State = EntityState.Modified;
    }

    public async void Save()
    {
        await _dbContext.SaveChangesAsync();
    }

    public void Dispose()
    {
        if (_dbContext != null)
            _dbContext.Dispose();
    }
}


texts: Iterator-Pattern for an iterator that returns one objects that changes

texts:
I wrote an algorithm that returns all k-sized subgraphs of another given graph. Because I don't want to make the runtime of the next() call of the iterator depended on k, I don't want to return a new object every time. Instead I have one fixed instance-variable subG in the iterator that is changed between the calls und always represents the current subgraph that was calculated. It acts as a view that can be copied if needed if you want to use it further.
This method works fine and this is not my problem.

If I want to use hasNext(), I'd need to calculate the next subgraph, which would change the view subG as a side-effect. This is not wanted. Currently I'm using my own interface for this iterator:

/**
 * Interface for all iterators that always return the same object, but change it in order to return the next value.
 * Therefore, the object should not be changed unintentionally, because that would result in unwanted side-effects.
 * This prevents the use of "hasNext()" as this would have to calculate the next value for the object, but this method
 * is not expected to have side-effects. The only method that changes the object is generateNext(), which also is
 * its only purpose.
 *
 * The standard pattern for using this interface would be:
 * while (iter.hasCurrent()) {
 *     doSomethingWith(iter.getCurrent());
 *     iter.generateNext();
 * }
 */
public interface BlindIterator<T> {

    /**
     * @return True iff the current element is a valid return.
     */
    boolean hasCurrent();

    /**
     * @return Returns the current element, but does NOT generate the next element. This method can be called
     * as often as wanted, without any side-effects.
     */
    T getCurrent();

    /**Generates the next element, which can then be retrieved with getCurrent(). This method thus only provides
     * this side-effect. If it is called while the current element is invalid, it may produce and exception,
     * depending on the implementation on the iterator.
     */
    void generateNext();
}

I've never written something like this. Is there a better pattern for this, if any?


texts: Optimization of BFS for finding minimum distances between elements of a grid

texts:
This is from HackerRank - Travel Diaries.

  Given a grid of 0s,1s and 2s we need to find minimum distance of each 1 from 2 going through 1s only. (See 1 as land, 0 as ocean, 2 as food, need to find closest food for each tile of land where boats don't exists).

class Queue:
    def __init__(self):
        self.items = []
    def empty(self):
        return self.items == []
    def enqueue(self, item):
        self.items.insert(0,item)
    def dequeue(self):
        try:
            return self.items.pop()
        except: return False
    def size(self):
        return len(self.items)

def readline(): return map(int,input().split(' '))

n,m = readline()

grid = list()
distances = list()
tocheck = Queue()

for i in range(n):
    grid.append(list(readline()))
    toapp = []
    for j in range(m):
        c = grid[i][j]
        if c == 2:
            toapp.append(0)
            tocheck.enqueue((i,j))
        else: toapp.append(m*n + (c-1)*m*n-1)
    distances.append(toapp)

c = tocheck.dequeue()
while c:
    x,y = c
    for i,j in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
        if 0 <= i < n:
            if 0 <= j < m:
                if grid[i][j] == 1:
                    if distances[x][y]+1 < distances[i][j]:
                        distances[i][j] = distances[x][y] + 1
                        grid[i][j] = 2
                        tocheck.enqueue((i,j))
    c = tocheck.dequeue()

maxi = max([max(i) for i in distances])
if maxi == m*n-1: maxi = -1
print(maxi)

Explanation:

Firstly, a pretty standard class implementing queues (Can't use builtin module for some reason). n,m = #rows, #cols

Next, a grid containing values and a grid containing distances is created. If the value is 2, then distance matrix contains 0. If value is 1, then distance is m*n-1 (larger than maximum possible distance). If value is 0, then distance is -1 (not possible). Also, every location containing 2 is also stored separately in a queue

Main BFS part: Dequeue a location. Check if all Neighbours all valid entries in matrix containing 1. If the distance of this neighobour is strictly greater than the current locations distance + 1, then update the neighbour's value to 2, distance to current distance + 1 and queue it. Repeat till queue is empty.

Any suggestions for optimization? (I realize my code has 0 comments but then again I didn't know I'd spend over 4 hours on this)

For a 1000 x 1000 grid this takes way over 5 seconds which is the required time limit. For a 100 X 100 grid it takes about 0.23 seconds on i3-4005U 1.7 Ghz.


texts: Single Page App - Browser Storage API Design

texts:
I'm working on building a Browser storage handler for my single page application.  The idea is that you make an API call and the API calls the storage handler which either returns the local/session storage or if it doesn't exist it calls the actual web service.  The StorageHandler uses a Proxy to first check if the browser has local and session storage enabled.  The "callback" is really just an Axios instance with a base url and some headers attached.  TBH I'm not sure this is even remotely a good idea or if it should just be handled in the actual API since I've read wrapping a Promise with another Promise is a bad idea and I don't have much experience with proxies.

const StorageHandler = {
    TestedStorage: false,
    StorageEnabled: false,
    TestStorage() {
        this.TestedStorage = true;
        this.StorageEnabled = this.TestLocal();
        return this.StorageEnabled;
    },
    TestLocal() {
        if (typeof window.localStorage !== 'undefined') {
            try {
                const test = 'TEST';
                window.localStorage.setItem(test, test);
                window.localStorage.removeItem(test);
                return true;
            } catch (e) {
                return false;
            }
        }
        return false;
    },
    ClearLocal() {
        window.localStorage.clear();
    },
    UpdateLocalWithObj(url, obj) {
        window.localStorage.setItem(url, JSON.stringify(obj));
    },
    // Gets from local storage or calls api, burst refers to cache bursting
    GetOrSetLocal(url, callback, burst = false) {
        return new Promise((resolve, reject) => {
            let result;
            if (this.StorageEnabled && burst === false) {
                result = window.localStorage.getItem(url);

                if (result !== null && result !== 'null') {
                    resolve(JSON.parse(result));
                }
            }

            callback.get(url)
            .then((response) => {
                result = response.data;
                if (this.StorageEnabled) {
                    window.localStorage.setItem(url, JSON.stringify(result));
                }
                resolve(result);
            })
            .catch((error) => { reject(error); });
        });
    },
    ....
};

const ProxyHandler = {
    get(target, key) {
        if (target.TestedStorage === false) {
            target.TestStorage();
        }
        return target[key];
    },
};

const proxy = new Proxy(StorageHandler, ProxyHandler);

export default proxy;


texts: shared_ptr alternative with no dependencies

texts:
An alternative to shared_ptr to minimize compile time. Intrusive. Reference count changes are not thread safe.

(#include<memory> pulls in 17k lines of code)

This satisfies my needs, but I'm curious how it could be improved (without adding any dependencies).

It's not particularly good at handling incomplete types (ref<T>::get cannot be used on an incomplete type). Is it possible to improve that?

// Derive from this to be refcounted.
struct refcount {
  int rc = 0;
  virtual ~refcount() { }
};

void queued_delete(refcount*);

template<class T>
class ref {

public:

  ref() { }

  ref(T* obj) : obj(obj) {
    if(obj) {
      obj->rc++;
    }
  }

  ~ref() {
    if(obj) {
      if(--(obj->rc) == 0) {
        queued_delete(obj);
      }
    }
  }

  ref(const ref& r) {
    if(r.obj) {
      obj = r.obj;
      obj->rc++;
    }
  }

  template<class T2>
  ref(const ref<T2>& r) {
    if(r.get()) {
      obj = r.get();
      obj->rc++;
    }
  }

  ref& operator=(const ref& r) {
    ref(r).swap(*this);
    return *this;
  }

  template<class T2>
  ref& operator=(const ref<T2>& r) {
    ref(r).swap(*this);
    return *this;
  }

  T* operator->() { return static_cast<T*>(obj); }
  const T* operator->() const { return static_cast<const T*>(obj); }
  T& operator*() { return *get(); }
  T& operator*() const { return *get(); }

  T* get() const { return static_cast<T*>(obj); }

  unsigned long id() const { return (unsigned long) obj; }

  void swap(ref& p) {
    auto tmp = obj;
    obj = p.obj;
    p.obj = tmp;
  }

  explicit operator bool() const {
    return obj;
  }

  bool operator==(const ref& other) const {
    return obj == other.obj;
  }

  bool operator!=(const ref& other) const {
    return obj != other.obj;
  }

  template<class T2>
  ref<T2> cast() {
    return ref<T2>(dynamic_cast<T2*>(obj));
  }

private:
  refcount *obj = nullptr;
};

Optional deletion which can handle deep nesting (can also do this with shared_ptr using a custom deleter):

// Ensure deeply nested data structures can
// be deleted without running out of stack.
void queued_delete(refcount* p) {

  static bool deleting = false;
  static std::vector<refcount*> stack;

  stack.push_back(p);

  if(!deleting) {
    deleting = true;
    while(stack.size()) {
      auto top = stack.back();
      stack.pop_back();
      delete top;
    }
    deleting = false;
  }
}


texts:
I have implemented a code to resolve following interview question. Please advice how it can be improved folks. Thanks in advance.

Given an array of time intervals (start, end) for classroom lectures
(possibly overlapping), find the minimum number of rooms required.
For example, given [(30, 75), (0, 50), (60, 150)], you should return
2.

I have just printed output value without proper self checking method due to my time limitation for this task. coll_max, coll_min are used to define time range of fully occupied rooms at each loop, thus requiring new room. Again, pardon my English here xD.
Code:
#include <stdio.h>
#include <limits.h>

int get_max(int arr[])
{
    if (!arr)
        return -1;
    if (arr[0] > arr[1])
        return arr[0];
    else
        return arr[1];
}

int get_min(int arr[])
{
    if (!arr)
        return -1;
    if (arr[0] < arr[1])
        return arr[0];
    else
        return arr[1];
}

unsigned int get_room_number(int arr[][2], unsigned int subjNo)
{
    /* colliding range, each time class time collide with those values,
    we increase neccRoom counter */
    int coll_max = INT_MAX;
    int coll_min = INT_MIN;

    int min;
    int max;
    unsigned int neccRoom = 0;  //neccarry rooms

    for (int i = 0; i < subjNo; i++)
    {
        min = get_min(arr[i]);
        max = get_max(arr[i]);

        if (min < 0 || max < 0) {
            return -1;
        }

        if (min <= coll_max && max >= coll_min)
        {
            neccRoom++;
            if (min > coll_min) {
                coll_max = min;
            }
            if (max < coll_max) {
                coll_max = min;
            }
        }
    }

    return neccRoom;
}

int main(void)
{
    int list[][2] = {
            { 30, 75 },
        { 0, 50 },
        { 60, 150 }
    };

    int answer = get_room_number(list, 3);

    if (answer > 0)
        printf("neccessary rooms: %u\n", answer);
    else
        printf("input array ERROR\n");

}


texts:
This code writes to Excel using the COM interface. The general issue is that any exception handling has to handle the "Excel is busy" exception. This occurs if information is sent to Excel quicker than it can handle it - eg. latency when a workbook is loaded/created, or the user is playing with the scrollbars (there are good reasons for letting this happen).

This is probably the only example I know of which is simpler and cleaner in VB6 than in C#! In VB6 an ON ERROR would be used. The error handler would then create an error for most cases. But if the error code is a "busy" then it will sleep a short period of time (typically half a second) and then try again with a "RESUME". Don't get me wrong, ON ERROR is generally messier than C#'s try...catch and it is easier to produce awful code; however, this is one example where the VB6 ON ERROR works better. A long sequence of Excel calls can be trapped with one handler. The "RESUME" will then send control back to the line where the 'busy' occurred - this avoids duplicate calls or skipped calls.

The solution I have in C# is to create a while loop with a flag. The flag indicates a repeat of the loop is required due to a 'busy' return from Excel. See the code below.

Is there a simpler, more elegant way of doing this?  The main problem is that this requires a method for each type of Excel call. To avoid too many duplicate Excel calls in the busy scenario, the contents of each method is atomic or close to atomic - eg. "write this formatted value"; "apply this formatting to this row". This results in lots of methods. And/or methods with lots of parameters (the example below is a short one with just one format option, but there could be more - colors, decimal points, etc).

private void WriteDoubleValue(Excel.Worksheet sh, int x, int y, double lfval, bool bBold)
{
    bool bNotSuccess = true;
    while (bNotSuccess)
    {
        try
        {
            ((Excel.Range)sh.Cells[y,x]).set_Value(Missing.Value, lfval);
            ((Excel.Range)sh.Cells[y, x]).Font.Bold = bBold;
            bNotSuccess = false;
        }

        catch (System.Runtime.InteropServices.COMException e)
        {
            if ((e.ErrorCode & 0xFFFF) == 0xC472)
            {   // Excel is busy
                Thread.Sleep(500); // Wait, and...
                bNotSuccess = true;  // ...try again
            }
            else
            {   // Re-throw!
                throw e;
            }
        }
    }
}


texts: Pagination implementation for a blog system

texts:
Last night I was working on a project that I've embarked upon as a learning exercise. I decided to add a pagination feature to my blog system. I made an attempt at it and got close... but I decided to undo my changes and I searched online for other 'better' solutions. I found this example which uses PagedList.Mvc NuGet and this example from asp.net which uses the same package.

Long story short, I decided that before I install another package I would make one more attempt at my own implementation and I was successful... so, on to my question.

Have I missed something important in my implementation that should make me want to reconsider my approach?

Here's my relevant Action in my HomeController.cs:

public ActionResult Index(int num = 0)
{
    var postsPerPage = 3;
    ViewBag.startNum = num;

    using (UnitOfWork uwork = new UnitOfWork())
    {
        IEnumerable<Post> posts = uwork.PostRepository.GetAll().ToList();

        int totalPosts = posts.Count();
        ViewBag.pages = totalPosts / postsPerPage;
        int skip = num * postsPerPage;

        return View(posts.Skip(skip).Take(postsPerPage));
    }
}

and this is the relevant code from my Index.cshtml:

@Html.ActionLink("Home", "Index", "Home", new { num = 0 }, null)

    @for (var i = 1; i < ViewBag.pages + 1; i++)
    {
        var cur = i.ToString();
        var name = i + 1;

@Html.ActionLink(name.ToString(), "Index", "Home", new { num = cur }, null)

        if (i >= 10) { break; }

    }

Note: I know there's going to be a bit more logic required in order to account for the remainder of pages after they are divided. But that's not my biggest concern as of yet.


texts:
Perfect numbers are strictly positive whole numbers of which the sum of their positive divisors equals a multiple of the number itself. An example of a 3-perfect number is 120. The sum of all divisors of 120, namely 1+2+3+4+5+6+8+10+12+15+20+24+30+40+60+120 = 360 equals three times 120.

My code does work, but it's not really efficient (if you have 2 very large number, it will take a very long time). Is there a more elegant way to solve this problem?

public class Main {

    public static void main(String[] args) {
        int number1 = 10;
        int number2 = 50;
        boolean found = false;
        int perfectNumber = 0;
        int multiplier = 0;
        for(int i = number1; i<=number2 && !found;i++){
            if(i%2==0){
                int somDivisors = lookSomeDivisors(i);
                if(somDivisors%i==0){
                    perfectNumber = i;
                    multiplier = somDivisors/i;
                    found=true;
                }
            }
        }
        System.out.println("Number1: " + number1 + " Number2: " + number2);
        System.out.println("PerfectNumber: " + perfectNumber + " Multiplier: " + multiplier);
    }

    private static int lookSomeDivisors(int number) {
        int som = 0;
        for(int i=1;i<=number;i++){
            if(number%i==0){
                som+= i;
            }
        }return som;
    }
}


texts:
Given any binary tree, what is the maximum number of turns possible in any path from root to any leaf?

A turn is when the path involves moving from left branch to right or vice-versa; i.e. the number of angels in a path. A straight line path has no turns.

The best I could get is the code below and it works with good performance, looking for better implementation

public class Tree
{
    public int x;
    public Tree l;
    public Tree r;
}

private int leftTurns(Tree T, int turns)
{
    if (T == null)
        return 0;

    return turns += Math.Max(
            leftTurns(T.l, 0),
            rightTurns(T.r, 1));
}

private int rightTurns(Tree T, int turns)
{
    if (T == null)
        return 0;

    return turns += Math.Max(
            leftTurns(T.l, 1),
            rightTurns(T.r, 0));
}

public int solution(Tree T)
{
    // write your code in C# 6.0 with .NET 4.5 (Mono)
    return Math.Max(
            leftTurns(T.l, 0),
            rightTurns(T.r, 0));
}

My concerns:

The semi-duplicate functions leftTurns() & rightTurns()
The readability of the algorithm
Is recursion necessary?


texts:
I've written the following unsafe C# method to convert a byte array to Base64 encoding.  It works, but it runs at a significantly slower rate than the built-in Convert.ToBase64String method.

public static unsafe string From(byte[] data)
    {
        int div = data.Length / 3;
        int mod = data.Length % 3;
        int length = data.Length;
        int b64Length = div * 4 + (mod == 0 ? 0 : 4);

        int c = 0;
        char[] r = new char[b64Length];
        fixed (char* tblPointer = base64Table)
        fixed (char* rPointer = r)
        fixed (byte* dPointer = data)
        {
            for (int i = 0; i < div * 3; i += 3)
            {
                rPointer[c] = tblPointer[(dPointer[i] & 0xfc) >> 2];
                rPointer[c + 1] = tblPointer[((dPointer[i] & 0x03) << 4) | ((dPointer[i + 1] & 0xf0) >> 4)];
                rPointer[c + 2] = tblPointer[((dPointer[i + 1] & 0x0f) << 2) | ((dPointer[i + 2] & 0xc0) >> 6)];
                rPointer[c + 3] = tblPointer[((dPointer[i + 2]) & 0x3f)];
                c += 4;
            }
            switch (mod)
            {
                case 1:
                    rPointer[c] = tblPointer[(dPointer[length - 1] & 0xfc) >> 2];
                    rPointer[c + 1] = tblPointer[((dPointer[length - 1] & 0x03) << 4)];
                    rPointer[c + 2] = '=';
                    rPointer[c + 3] = '=';
                    c += 4;
                    break;
                case 2:
                    rPointer[c] = tblPointer[(dPointer[length - 2] & 0xfc) >> 2];
                    rPointer[c + 1] = tblPointer[((dPointer[length - 2] & 0x03) << 4) | ((dPointer[length - 1] & 0xf0) >> 4)];
                    rPointer[c + 2] = tblPointer[((dPointer[length - 1] & 0x0f) << 2)];
                    rPointer[c + 3] = '=';
                    c += 4;
                    break;
            }
        }
        return new string(r);
    }

I looked at the Reference Source for the .NET method and found that my code is very very similar already.  Is there something I'm missing or is there some sort of optimization to the built in method I don't know about?

The variable base64Table in the code is simply a char[] with the relevant base64 characters.

The results being 31 Ticks for the built in method and 2230 Ticks for my method, measured with the System.Diagnostics.Stopwatch class.


texts:
I've recently started building an API that allows a consumer to create and manipulate musical entities such as notes, intervals, scales and chords.

The first step is to create a a foundation of base structures that are later used by the musical entities.
One such structure is a Ring.

A ring in modular arithmic

A Ring is an integer's representation clamped between 0 and the ring size. Its Value is the integer it represents.  Its Size is the group size. Its Class is the congruent value clamped in the specified range. Its Group determines the number of ranges it's away from the reference group 0.

A ring from the perspective of Music Theory

  The way I'm using a ring is to define a musical note. A note consists
  of a pitch and a degree. The pitch is a number that represents the
  frequency of a note. A ring with size 12 is used to represent all
  semi-tones within a single octave. Each octave is a ring group.
  Another ring with size 7 is used to define the degree of the note.
  Common representations of degrees are {C, D, E, F, G, A, B} or
  do-re-mi-fa-sol-la-ti. The note C on the 5th octave is considered
  the reference note with pitch 0 and degree 0.

I want to be able to change a ring's properties.
The example below shows how the pitch of a note could be represented by a ring.

val pitch = Ring(0, 12)   // the pitch of note 'C5'
pitch.Group = 1           // the pitch one octave higher 'C6'
pitch.Class = 2           // the pitch class changed to that of note 'D6'
println(pitch)            // Ring(Value=14, Size=12)

The example below shows how the degree of a note could be represented by a ring.

val degree = Ring(0, 7)   // the degree of note 'C5'
degree.Group = 1          // the degree one octave higher 'C6'
degree.Class = 1          // the degree class changed to that of note 'D6'
println(degree)           // Ring(Value=8, Size=7)

This means the note D6 can be represented by pitch Ring(Value=14, Size=12) and degree Ring(Value=8, Size=7).

I have opted to use a mutable class and data class.
I want a mutable class because I require a lot of manipulations to be chained.
And I desire a data class because of its nature of hiding boiler-plate code and providing interesting methods such as copy.

val ring = someOtherRing.copy().setClass(2).setGroup(1)

I did read that data classes should be immutable.

  So my questions are:

Is it allowed to use the data class as mutable class?
Does it make sense that I combine mutable and data class for the Ring class?
Are there better alternatives to create an API class?

Any additional feedback on Kotlin guidelines, general guidelines, fluent-ish methods and varia is welcome as well.

Ring code:

import kotlin.math.*

data class Ring(var Value: Int, val Size: Int) {

    var Class: Int
        get() = modulo(Value)
        set(value) {
            Value = Group * Size + modulo(value)
        }

    var Group: Int
        get() = Value / Size
        set(value) {
            Value = value * Size + Class
        }

    fun setValue(value: Int): Ring {
        Value = value
        return this
    }

    fun setClass(clazz: Int): Ring {
        Class = clazz
        return this
    }

    fun setGroup(group: Int): Ring {
        Group = group
        return this
    }

    private fun modulo(x: Int): Int {
        return (x % Size + Size) % Size
    }
}


texts:
I need to classify each line as "announce, whisper or chat" once I have that sorted out I need to extract certain values to be processed.

Right now my regex is as follow:

var regex = new Regex(@"^\[(\d{2}:\d{2}:\d{2})\]\s*(?:(\[System Message\])?\s*<([^>]*)>|((.+) Whisper You :))\s*(.*)$");

Group 0 is the entire message.
Group 1 is the hour time of when the message was sent.
Group 2 is wether it was an announce or chat.
Group 3 is who sent the announce.
Group 4 is if it was a whisper or not.
Group 5 is who sent the whisper.
Group 6 is the sent message by the user or system.

Classify each line:

if 4 matches
 means it is a whisper
   else if 2 matches
     means it is an announce
       else
         normal chat

Should I change anything to my regex to make it more precise/accurate on the matches ?

Sample data:

[02:33:03] John Whisper You :  Heya
[02:33:03] John Whisper You :  How is it going
[02:33:12] <John> [02:33:16] [System Message] bla bla
[02:33:39] <John> heya
[02:33:40] <John> hello :S
[02:33:57] <John> hi
[02:33:57] [System Message] <John> has left the room
[02:33:57] [System Message] <John> has entered the room


texts:
I'm a java programmer by trade and starting to learn C/C++. I'd appreciate any pointers on glaring issues with my code style which is acceptable in java but not in C. I feel like open_files is probably bad in C I'm used to that sort of thing in java to make code easier to scan ( setting *src_file on one line and testing the next)

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

void get_paths(char *src, char *dest, int buf_size) {
    fprintf(stdout, "Please enter src path:\n");
    fgets(src, buf_size, stdin);
    src[strcspn(src, "\r\n")] = 0;
    fprintf(stdout, "\nPlease enter dest path:\n");
    fgets(dest, buf_size, stdin);
    dest[strcspn(dest, "\r\n")] = 0;
}

int open_files(char *src, char *dest, FILE **src_file, FILE **dest_file) {
    *src_file = fopen(src, "r");
    if(!*src_file) {
        fprintf(stderr, "\n%s is not a valid file or permission denied\n", src);
        return 0;
    }

    *dest_file = fopen(dest, "w");
    if(!*dest_file) {
        fprintf(stderr, "\ncould not open %s for writing, check path exists and you have write permissions\n", dest);
        fclose(*src_file);
        return 0;
    }
    return 1;
}

int cpy(char *cpy_buf, FILE *src_file, FILE *dest_file) {
    size_t num_elements;
    while((num_elements = fread(cpy_buf, sizeof(char), sizeof(cpy_buf), src_file)) > 0) {
        if(fwrite(cpy_buf, sizeof(char), num_elements, dest_file) != num_elements) {
            fprintf(stderr, "\nError while writing to destination \nAborting...");
            return 0;
        }

    }
    return 1;
}

int main() {
    const int buf_size = 256;
    const int cpy_buf_siz = 64;
    char src[buf_size];
    char dest[buf_size];
    char cpy_buf[cpy_buf_siz];
    FILE *src_file;
    FILE *dest_file;

    get_paths(src, dest, buf_size);
    fprintf(stdout, "\nAttempting to copy from %s to %s...\n", src, dest);

    if(!open_files(src, dest, &src_file, &dest_file))
        return -1;

    fprintf(stdout, "\nStarting copy from %s to %s...\n", src, dest);
    int success = cpy(cpy_buf, src_file, dest_file);
    fclose(src_file);
    fclose(dest_file);

    return success ? 0 : 1;
}


texts: Remove particular element from an array and return indices of other elements

texts:
I'd like to get the indices of elements of an array with particular element. Is it okay or, or how can I make it even better?

//string Input = "Net Sales,COGS";

int[] numbers = { 0, 1, 2, 3, 4, 5 };
string[] Values = { "Net Sales", "COGS", "COGS%", "Gross Profit", "GP%", "Quantity" };

string[] selectedValues = Input.Split(new char[] { ',' });
selectedIndex = new int[selectedValues.Length];
selectedIndex = selectedValues.Select(n => Array.IndexOf(Values, n)).ToArray();

for (int i = 0; i < selectedIndex.Length; i++)
    numbers = numbers.Where(val => val != selectedIndex[i]).ToArray();

selectedIndex = numbers;


texts:
I am writing web application using flask framework + mongodb. I have an issue, should I use classes for my mongo entities or just use dictionaries for them.

class School:
    def __init__(self, num, addr, s_type):
        self.num = num
        self.addr = addr
        self.s_type = s_type

or just create dictionary for any entity like:

school = { "number" : request['number'] ,
           "address": request['address'],
           "type"   : request['type'] }


texts: Identifying first negative number in array of doubles

texts:
I was asked to create a function that checks if an array of doubles has all negative numbers or none. If these 2 (all negative, all positive) are false, check the first negative number,  using recursion and only using built-in C++ features.

int first_negative(const double val [] , unsigned array, unsigned short instance_ = 0) //Dont change instance!
{
    //None negative?
    bool none_negative;
    for(int i = 0; i < array; i++)
    {
        if(val[i] > 0) none_negative = true;
        else
        {
            none_negative = false;
            break;
        }
    }
    if(none_negative) return 0;

    //All negative?
    bool negative_instance;
    for(int i = 0; i < array; i++)
    {
        if(val[i] < 0) negative_instance = true;
        else
        {
            negative_instance = false;
            break;
        }
    }

    //Never change instance!
    static short instance = instance_;
    if(array < 1) return 0;
    if(val[instance] < 0) return instance;
    instance++;
    return first_negative(val, array, instance);
}

Can I make it better? Can I remove the instance parameter?


texts: Calculate maximum possible helpful flags for n days

texts:
This program is supposed to calculate the mathemathical maximum of helpful flags you can have on the nth day, starting with 0 helpful flags, using the StackExchange system of gaining more possible flags, meaning every 10 helpful flags you gain one possible one, immediately.

#include <stdio.h>

// <summary>
// Small C program to simulate how many helpful flags someone could have raised on both comments and posts
// Assumptions:
// - Flags would be immediately marked helpful or near immediately
// - Every 10 flags, you get one extra flag per day, up to 100 total flags.
// - No declined flags
// @Author: Magisch - http://stackoverflow.com/users/5389107/magisch
// @License: CC0
// </summary>

int main(void) {
    int nDays = 0; // Days to simulate for
    int totalFlags = 0;
    int dailyFlags = 10;
    int bonusCountdown = 0;
    int totalFlagsBeforeCalc = 0;

    printf("Enter the amount of days you want to simulate flags for:\n");
    scanf("%d ", &nDays);

    printf("Computing maximum helpful comment flags and post flags for %d days.\n",nDays);

    for (int i = 0; i < nDays; i++) {
        totalFlags += dailyFlags;
        bonusCountdown += (totalFlags - totalFlagsBeforeCalc);
        totalFlagsBeforeCalc = totalFlags;
        while (bonusCountdown >= 10 && dailyFlags < 100) {
            dailyFlags++;
            totalFlags++;
            bonusCountdown -= 10;
        }
        printf("Day %d : total helpful flags: %d | daily available flags: %d\n", i+1, 2*totalFlags, dailyFlags);
    }
    printf("Simulated %d days. Total helpful flags: %d",nDays,2*totalFlags);
    return 0;
}

Example of the Results for n = 52 : http://pastebin.com/TbjRPjBn

I'm a beginner still in coding (second year apprentice), so please don't hold back on any critique.


texts: Rails 6: Attaching Devise current_user.id to form submissions

texts:
In my Ruby on Rails 6 app:

I have a User class built with Devise, and I scaffolded a List class where each List should belong_to a User.

I want Lists created through my app to be automatically assigned to the logged-in user. This should happen on the back end, after the rest of the new List fields have been posted to the server.

I was able to make this happen by adding a line to the default list-params definition in the scaffolded controller:

def list_params
  params[:list].merge!(:user_id => current_user.id.to_s)
  params.require(:list).permit(:title, :active, :user_id)
end

My questions are:

Am I reinventing the wheel somehow with this approach?
Does modifying the list_params in this way affect the application outside of creating and updating Lists?
Have I introduced any potential security issues by doing things this way?

For reference, here is the rest of the controller:

class ListsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_list, only: [:show, :edit, :update, :destroy]

# GET /lists
# GET /lists.json
def index
  @lists = List.all
end

# GET /lists/1
# GET /lists/1.json
def show
end

# GET /lists/new
def new
  @list = List.new
end

# GET /lists/1/edit
def edit
end

# POST /lists
# POST /lists.json
def create
  @list = List.new(list_params)

  respond_to do |format|
    if @list.save
      format.html { redirect_to @list, notice: "List was successfully created." }
      format.json { render :show, status: :created, location: @list }
    else
      format.html { render :new }
      format.json { render json: @list.errors, status: :unprocessable_entity }
    end
  end
end

# PATCH/PUT /lists/1
# PATCH/PUT /lists/1.json
def update
  respond_to do |format|
    if @list.update(list_params)
      format.html { redirect_to @list, notice: "List was successfully updated." }
      format.json { render :show, status: :ok, location: @list }
    else
      format.html { render :edit }
      format.json { render json: @list.errors, status: :unprocessable_entity }
    end
  end
end

# DELETE /lists/1
# DELETE /lists/1.json
def destroy
  @list.destroy
  respond_to do |format|
    format.html { redirect_to lists_url, notice: "List was successfully destroyed." }
    format.json { head :no_content }
  end
end

private

# Use callbacks to share common setup or constraints between actions.
def set_list
  @list = List.find(params[:id])
end

# Only allow a list of trusted parameters through.
def list_params
  params[:list].merge!(:user_id => current_user.id.to_s)
  params.require(:list).permit(:title, :active, :user_id)
end
end

And here is the form template:

<%= form_with(model: list, local: true) do |form| %>
    <% if list.errors.any? %>

<%= pluralize(list.errors.count, "error") %> prohibited this list from being saved:

          <% list.errors.full_messages.each do |message| %>

<%= message %>

          <% end %>

    <% end %>

      <%= form.label :title %>
      <%= form.text_field :title %>

      <%= form.label :active %>
      <%= form.check_box :active %>

      <%= form.submit %>

  <% end %>


texts: Is the following divide and conquer recursive algorithm for the exponentiation more efficient than the iterative one for large numbers?

texts:
I have the two following algorithms. My analysis says that both of them are \$\mathcal O(m^24^n)\$ i.e they are equivalent for big numbers (more than 32 bits). Is this right? Note that m and n are the bits numbers for x and y
def pow1(x, y):
    if y == 0:
        return 1
    temp = x
    while y > 1:
        y -= 1
        temp *= x
    return temp

def pow2(x, y):
    if y == 0:
        return 1
    temp = pow2(x, y//2)
    if y & 1:    return temp * temp * x
    return temp * temp

The complexity of the first
y-1 iterations and in each iteration, a subtraction taking \$\mathcal O (\lg (y-i))\$, and a multiplication taking \$\mathcal O (im\cdot m)\$, hence the total work takes
\$T=\mathcal O(\sum\limits_{i=1}^ym^2i)=\mathcal O\left(m^2\frac{y(y+1)}2\right)=\mathcal O\left(m^24^n\right)\$
Of the second
We have \$n=\lg y\$ calls and for each, we have multiplications taking \$\mathcal O (2^im\cdot 2^im)\$, hence the total work takes
\$ T=\mathcal O\left(\sum\limits_{i=1}^{n}\left(4^im^2\right)\right)=\mathcal O\left({4^n}{m^2}\right)\tag{for large $n$}\$