Typing training with GUI in Python This script allows you to practice your typing skills, as soon as you finish typing a new word appears for a non-stop typing experience. The code has in memory the top 100 words as per the Pareto Principle and Zipf's Law, of these, the top 10 are more common than the rest.

To start, type start.

Tested in Linux, Python 3.4 but should work in any version in any OS.

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk
import random

FONT = (None, 50)
WORDS = ['the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'I', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 'at', 'this', 'but', 'his', 'by', 'from', 'they', 'we', 'say', 'her', 'she', 'or', 'an', 'will', 'my', 'one', 'all', 'would', 'there', 'their', 'what', 'so', 'up', 'out', 'if', 'about', 'who', 'get', 'which', 'go', 'me', 'when', 'make', 'can', 'like', 'time', 'no', 'just', 'him', 'know', 'take', 'people', 'into', 'year', 'your', 'good', 'some', 'could', 'them', 'see', 'other', 'than', 'then', 'now', 'look', 'only', 'come', 'its', 'over', 'think', 'also', 'back', 'after', 'use', 'two', 'how', 'our', 'work', 'first', 'well', 'way', 'even', 'new', 'want', 'because', 'any', 'these', 'give', 'day', 'most', 'us']

new_word = lambda: random.choice(random.choice((WORDS[0:len(WORDS)//10], WORDS)))

root = tk.Tk()
root.title("Typing trainer")

text_to_copy = tk.Label(root, text = "start", font=FONT)
text_to_copy.pack()

typing_ground = tk.Entry(root, font=FONT)
typing_ground.pack()

points = tk.Label(root, text = "Score: 0", font=FONT)
points.pack()

def if_equal_delete_and_take_other_phrase(ev):
    if text_to_copy.cget("text") == typing_ground.get():
        typing_ground.delete(0, 'end')
        text_to_copy['text'] = new_word()
        points['text'] = "Score: " + str(int(points['text'].split(': ')[-1]) + 1)

root.bind('<Key>', if_equal_delete_and_take_other_phrase)

root.mainloop()

I love seeing functionality like this packed so concisely. Really nice job.

UX

When I ran your code, it ran fine, but a usability problem is that the text entry box does not have focus, you have to click on it to make it have the active focus/cursor. You should add this to your script:

typing_ground.focus_set()

I ran it with python and python3, both worked fine.

Another thing that came up is that it occasionally happens that the next word is the same as the previous word. You should add a re-selection of a new word until it is different, otherwise the experience is "odd" (the word stays the same but your entry widget clears... and when you're typing you are not really looking at the entry box, just the target word.... and since it does not change, you think you've made a mistake.

Variables

Your code uses text entry and display components as variables. This code makes me cringe:

points['text'] = "Score: " + str(int(points['text'].split(': ')[-1]) + 1)

Instead of having a score variable, you store the score in the partial text value of the score displaying widget. Really? You do the same thing with the text to copy. Currently your code is:

def if_equal_delete_and_take_other_phrase(ev):
    if text_to_copy.cget("text") == typing_ground.get():
        typing_ground.delete(0, 'end')
        text_to_copy['text'] = new_word()
        points['text'] = "Score: " + str(int(points['text'].split(': ')[-1]) + 1)

Would it really be so hard to do:

target = "start"
score = 0
def if_equal_delete_and_take_other_phrase(ev):
    global target
    global score
    if target == typing_ground.get():
        score = score + 1
        target = new_word()
        typing_ground.delete(0, 'end')
        text_to_copy['text'] = target
        points['text'] = "Score: " + str(score)

Lambda

The lambda here is simply gratuitous:

new_word = lambda: random.choice(random.choice((WORDS[0:len(WORDS)//10], WORDS)))

It is never used in an anonymous way, and really there's no use for this format at all. It makes the reader expect something "funny", and there's confusion when the only funny thing is the declaration above.

Talk about confusing.... why is the first 10% of the WORDS list more important than the next 10%? The first 10% of the words appear with significantly more frequency because you not only choose the random word from the array, but you choose to use either the first 10% only, or the whole thing. In other words, half of the choices only ever come from the first 10% of the words.

I cannot think of any reason for that, and it makes the code complicated, and it is a head scratcher, and as a consequence, the code maintainer (me) would be cursing your name and hexing your bytestrings. For all things sweet and dainty, at least leave a comment, please. As for me, I'll just rewrite that crap as:

def new_word():
    return random.choice(WORDS)

Hmmm.... let me add in the non-repeating word function too:

def new_word():
    while True:
        nword = random.choice(WORDS)
        if nword != target:
            return nword

Conclusion

I added a #!/usr/bin/python3 line too. It's nice to not have to type these things in linux at least.

The code I ended up with is:

#!/usr/bin/python3
try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk
import random

FONT = (None, 50)
WORDS = ['the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have',
         'I', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you',
         'do', 'at', 'this', 'but', 'his', 'by', 'from', 'they',
         'we', 'say', 'her', 'she', 'or', 'an', 'will', 'my', 'one',
         'all', 'would', 'there', 'their', 'what', 'so', 'up', 'out',
         'if', 'about', 'who', 'get', 'which', 'go', 'me', 'when',
         'make', 'can', 'like', 'time', 'no', 'just', 'him', 'know',
         'take', 'people', 'into', 'year', 'your', 'good', 'some',
         'could', 'them', 'see', 'other', 'than', 'then', 'now',
         'look', 'only', 'come', 'its', 'over', 'think', 'also',
         'back', 'after', 'use', 'two', 'how', 'our', 'work',
         'first', 'well', 'way', 'even', 'new', 'want', 'because',
         'any', 'these', 'give', 'day', 'most', 'us']

target = "start"
score = 0

root = tk.Tk()
root.title("Typing trainer")

text_to_copy = tk.Label(root, text = target, font=FONT)
text_to_copy.pack()

typing_ground = tk.Entry(root, font=FONT)
typing_ground.pack()

points = tk.Label(root, text = "Score: " + str(score), font=FONT)
points.pack()

def new_word():
    while True:
        nword = random.choice(WORDS)
        if nword != target:
            return nword

def if_equal_delete_and_take_other_phrase(ev):
    global target
    global score
    if target == typing_ground.get():
        score = score + 1
        target = new_word()
        typing_ground.delete(0, 'end')
        text_to_copy['text'] = target
        points['text'] = "Score: " + str(score)

root.bind('<Key>', if_equal_delete_and_take_other_phrase)

typing_ground.focus_set()

root.mainloop()


Countdown timer in React.js Code is a countdown timer.

Should I keep this update function separate as is or can I save 3 lines of code and embed this.setState({newDeadline: event.target.value}) directly in the callback function below? eg. onChange={event => this.setState({newDeadline: event.target.value}}

import React, { Component } from 'react';
import './App.css';
import Clock from './Clock';
import {FormGroup, FormControl, Button} from 'react-bootstrap';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      deadline: 'December 25 2017',
      newDeadline: ''
    }
  }

  updateDeadline() {
    if (isNaN(Date.parse(this.state.newDeadline)) || this.state.newDeadline === '') {
      this.setState({deadline: this.state.deadline});
    } else {
      this.setState({deadline: this.state.newDeadline})
    }
  }

  updateNewDeadline(event) {
    this.setState({newDeadline: event.target.value})
  }

  render() {
    return (

Countdown To {this.state.deadline}

        <Clock deadline={this.state.deadline} />
        <form className="app-form">
          <FormGroup>
            <FormControl className="deadline-input"
              placeholder='Enter a new date'
              onChange={event => this.updateNewDeadline(event)}
            />
            <Button bsStyle="primary" block onClick={() => this.updateDeadline()}>Submit</Button>
          </FormGroup>
        </form>

    )
  }
}

export default App;

My two takes in this. In you example your are creating a new event handler on each render, so if you want to do it that way you would for sure want to bind the event handlers in the constructor. But if your never re-using them and it doesent clutter up the JSX "markup" to much (e.g. just a clean setState) I am always using the inline setState like you suggested:

import React, { Component } from 'react';
import './App.css';
import Clock from './Clock';
import {FormGroup, FormControl, Button} from 'react-bootstrap';

class App extends Component {
  constructor(props) {
    super(props);

    //Bound event handlers
    this.updateNewDeadline = this.updateNewDeadline.bind(this);
    this.updateDeadline = this.updateDeadline.bind(this);

    this.state = {
      deadline: 'December 25 2017',
      newDeadline: ''
    }
  }

  updateDeadline() {
    if (isNaN(Date.parse(this.state.newDeadline)) || this.state.newDeadline === '') {
      this.setState({deadline: this.state.deadline});
    } else {
      this.setState({deadline: this.state.newDeadline})
    }
  }

  updateNewDeadline(event) {
    this.setState({newDeadline: event.target.value})
  }

  render() {
    return (

Countdown To {this.state.deadline}

        <Clock deadline={this.state.deadline} />
        <form className="app-form">
          <FormGroup>
            <FormControl className="deadline-input"
              placeholder='Enter a new date'
              onChange={this.updateNewDeadline}
            />
            <Button bsStyle="primary" block onClick={this.updateDeadline}>Submit</Button>
          </FormGroup>
        </form>

    )
  }


Parking lot and vehicle classes The expected functionality is that a user/vehicle interacts with a ParkingLot and it allots the space in Park method based on type of vehicle (here I can expect a few changes, like increase from regular and handicapped to one more functionality for celebrities etc). What would be the route to perfect object oriented code?

class Vehicle
 attr_accessor :regno,:type
 def initialize(regno,type)
     @regno=regno
     @type=type
 end
end

class ParkingLot
 attr_accessor :size , :handicapped_size , :regular_size

 def initialize(size)
    @lot={}
    @size=size
    @handicapped_size=(0.1)*size
    @regular_size=size-@handicapped_size

 end
 def check_regular
    @regular_size>0 ? @regular_size-=1 : false
 end
 def check_handicapped
    @handicapped_size>0 ? @handicapped_size-=1 : false
 end

 def park(vehicle,hour)
    case vehicle.type
    when "regular"
        check_regular ? @lot[vehicle.regno]=Regular_ParkingSpace.new(hour).payment : error()
    when "handicapped"
        check_handicapped ? @lot[vehicle.regno]=Handicapped_ParkingSpace.new(hour).payment : error()
    end
 end

 def unpark(vehicle)
    pay=@lot[vehicle.regno]
    puts "Pls pay us #{pay} rupees"
    @lot.delete(vehicle.regno){|el| puts "#{el} not found in this parking lot \n"}
 end

 def error
    raise "No more vehicles can be parked !! \n"
 end
end
class ParkingSpace
 attr_accessor :hour,:rate
 def initialize(hour,rate)
    @hour=hour
    @rate=rate
 end
 def payment
    @hour * @rate
 end
end

class Regular_ParkingSpace < ParkingSpace
 def initialize(hour,rate=20)
    super
 end
 def payment
    super
 end
end
class Handicapped_ParkingSpace < ParkingSpace
 def initialize(hour,rate=5)
    super
 end
end

Please  mention the principle in use too.

Indentation and whitespace
The Ruby convention is 2 spaces of indentation, and blank lines between methods. I'd also recommend spaces between arguments and operators, e.g. @hour = hour.
Naming
Don't use underscores in class names. It's clear that Regular_ParkingSpace is a kind of ParkingSpace because it inherit directly from that parent class. A name like RegularSpace would be more straightforward and less of a mouthful.
attr_accessor
You're adding a number of synthesized accessor methods with attr_accessor but you never use those methods. Instead you access instance variables directly. My advice is to always use accessor methods when you can. However, attr_accessor generates both readers and writers, and they're public. Which means that external code can just say parking_lot.size = 9999, which doesn't make sense. Of course, you never actually use the size attribute for anything, which brings me to my next point:
Junk code
It sounds harsh, but I just mean "code that doesn't actually do anything". For example the @size variable in ParkingLot which is never used. Or Regular_ParkingSpace having a payment method that just calls super - something that'd happen automatically if the method wasn't there.
Dangerous assumptions
Speaking of the parking lot's size, your way of determining the number of handicap spaces is not vary robust. You just assume it's going to be one tenth of the spaces. Well, what if the parking lot has 8 spaces in total? Then you have 0.8 of a handicap space, and 7.2 regular ones. Or what if it has 213 spaces? Then you have 21.3 handicap spaces. Neither situation makes any sense. For that matter who says there are any handicap spaces at all? There's no reason - that I know if - to assume there's any proportional relationship between the two numbers.
Outright bugs
Following from the above: The way you check for remaining spaces assumes integers. If the remaining number of spaces is anything above zero, you assume that that means there's a whole parking space there. So, in turn, you assume that whatever size was originally passed to ParkingLot.new is cleanly divisible by 10. But that's not given.
End result is that if I make a parking lot with 8 spaces, I can fit 9 vehicles: 1 handicap vehicle (in the 0.8 of a space), and 8 regular ones (the first 7 get a space each, and the last one has to fit in 0.2 of a space).
Oh, and I can just park a car for zero hours, and I'll pay zero rupees.
Pointless classes
You parking lot classes don't really serve any purpose being classes. You instantiate one of them, only to call payment and then discard the instance. In the end, you classes could be replaced with methods, or even just an expression: a * b.
Informal exceptions
Don't just raise a string; create an exception class that inherits from StandardError and raise it instead.

In other words, there's a lot going on here. Making it "more object-oriented" is a secondary concern. And with no concept of time passing, hourly rates don't really make much difference. It's a little weird that the cost gets calculated immediately when parking, and "paid" when the car's retrieved. A real parking lot would do one or the other: Pre-pay for x amount of time (with the possibility of an extra fee if you overstay), or pay for time used when leaving. This is neither of those.


Advent of Code 2019 Day 2 in Rust I'm also doing the fun little Advent of Code challenges in order to learn Rust. Until now things went quite smoothly, but while I'm proceeding with the tasks I'd love to learn where I can actually improve my Rust coding (and not only getting the correct results).

I'm specifically looking for feedback where I'm violating Rust idioms or suggestions e.g. for simplifications as my knowledge of the Rust STD library features is still quite limited. On the other hand in context of those coding challenges I don't really care too much about stuff like input validation/stability/error handling or even performance (as you would in actual production code).

As requested, a small summary of what the program does, as the linked description is admittedly a little exhaustive:

The program basically simulates very basic machine code. A set of instructions represented as a list of integers values is given by a text file (comma delimited values).

Instructions start with an "opcode", describing the operations. In our case this may either be an addition (1), multiplication (2) or program end (99). All other values are deemed invalid as an opcode. The 3 integers following the opcodes are the parameters, giving the addresses of the operands (offset 1 and 2), as well as the target address to store the result (offset 3).

The result of the program is defined to be stored at address 0. In the 2nd part of the task one is given a program result (target_value 19690720) and is supposed to figure out which values need to reside at the memory addresses at 1 and 2 before starting the program (which are in this context called "noun" and "verb") in order to get this result.

Here's my implementation part 2 of day 2:

use std::fs;

fn add_values (value_a: i32, value_b: i32, target: &mut i32) {
    *target = value_a + value_b
}

fn multiply_values (value_a: i32, value_b: i32, target: &mut i32) {
    *target = value_a * value_b
}

fn run_program(memory: &mut Vec<i32>) -> i32 {
    let command_stride = 4;
    let mut current_pos = 0;
    while current_pos < memory.len() {
        let current_instruction = memory[current_pos];
        let address_a = memory[current_pos + 1] as usize;
        let address_b = memory[current_pos + 2] as usize;
        let address_target = memory[current_pos + 3] as usize;
        match current_instruction {
            1 => add_values(memory[address_a], memory[address_b], &mut memory[address_target]),
            2 => multiply_values(memory[address_a], memory[address_b], &mut memory[address_target]),
            99 => break,
            _ => panic!("Invalid command value!")
        }
        current_pos += command_stride;
    }
    //return result of the program stored at address 0
    memory[0]
}

fn main() {
    let contents = fs::read_to_string("input.txt")
        .expect("Something went wrong reading the file");

    let split_codes = contents.split_terminator(',');
    let codes : Vec<i32> = split_codes.filter_map(|v| v.parse::<i32>().ok()).collect();

    let target_value = 19690720;

    for noun in 0..100 {
        for verb in 0..100 {
            let mut current_memory = codes.clone();
            //init noun and verb
            current_memory[1] = noun;
            current_memory[2] = verb;

            let current_result = run_program(&mut current_memory);

            if current_result == target_value {
                 println!("Target value reached, noun: {}, verb {}", noun, verb);
                 println!("Result = {}", 100*noun + verb);
                 break;
            }
        }
    }
}

Some things you could do :

remove these "add" and "multiply" functions
group operations when you read the file and when you split the input
use iterators on your splitted input
assign using the match statement
declare all your variables at once (it's debatable, but if you find it easier to read then go for it ! )
put info in your error message for the code (although it might not help much if you have a bug here, I admit)

It could look something like :

use std::fs;

fn run_program(memory: &mut Vec<i32>) -> i32 {
    for i in (0..memory.len()).step_by(4) {
        let (address_a, address_b, pos) = (memory[i + 1] as usize, memory[i + 2] as usize, memory[i + 3] as usize);
        memory[pos] = match memory[i] {
            1 => {
                memory[address_a] + memory[address_b]
            }
            2 => {
                memory[address_b] * memory[address_b]
            }
            99 => {
                return memory[0];
            }
            c => panic!("Invalid command value : {}", c)
        }
    }
    //return result of the program stored at address 0
    memory[0]
}

fn main() {
    let codes:Vec<i32> = fs::read_to_string("input.txt")
        .expect("Something went wrong reading the file")
        .split(',')
        .filter_map(|v| v.parse::<i32>().ok())
        .collect();

    let target_value = 19690720;

    for noun in 0..100 {
        for verb in 0..100 {
            let mut current_memory = codes.clone();
            //init noun and verb
            current_memory[1] = noun;
            current_memory[2] = verb;

            let current_result = run_program(&mut current_memory);

            if current_result == target_value {
                println!("Target value reached, noun: {}, verb {}", noun, verb);
                println!("Result = {}", 100*noun + verb);
                break;
            }
        }
    }
}

Note : the ".ok()" filter might be dangerous in your stream ! I had a problem for day 5 where I had used wrong types for the instructions, and when the parsing failed they were discarded : I was missing instructions in my "codes" Vec !
You might want to fail if this happens instead, it's way easier to debug...


Convert datagridview data to DataTable I made an algorithm to calculate when the user has to purchase material adjusting the date in which the order has to be made, I'm using datagridviews to make it work, but I was wondering if there is a better way using a DataTable.

private void Suggestion()
{
  for (int i = 1; i < dataGridView9.RowCount; i++)
    {
        string PartNumber = dataGridView9.Rows[i - 1].Cells["PartNumber"].Value.ToString();
        string Requested_Date = dataGridView9.Rows[i - 1].Cells["Requested_Date"].Value.ToString();
        string material = dataGridView9.Rows[i - 1].Cells["Material"].Value.ToString();
        string requierd_Qty = dataGridView9.Rows[i - 1].Cells["Requierd_Qty"].Value.ToString();

  for (int l = 1; l < dataGridView10.RowCount; l++)
    {
        string partNumber = dataGridView10.Rows[l - 1].Cells["PartNumber"].Value.ToString();
        double leadTime = double.Parse(dataGridView10.Rows[l - 1].Cells["PUR LT"].Value.ToString());

        if (partNumber == material)
        {
            DateTime _requested_Date = Convert.ToDateTime(Requested_Date);
            DateTime suggestedDate = GetWorkDays.AddWorkdays(_requested_Date, Convert.ToDouble(leadTime));

            try
            {
                oleDbCmd = new OleDbCommand("InsertSuggested", connection);
                oleDbCmd.CommandType = CommandType.StoredProcedure;

                oleDbCmd.Parameters.Add("@PartNumber", OleDbType.VarChar, 30).Value = material.ToString();
                oleDbCmd.Parameters.Add("@AdjustedDate", OleDbType.Date, 50).Value = _requested_Date;
                oleDbCmd.Parameters.Add("@SuggestedDate", OleDbType.Date, 50).Value = suggestedDate;
                oleDbCmd.Parameters.Add("@Qty", OleDbType.VarChar, 30).Value = requierd_Qty;

                connection.Open();
                oleDbCmd.ExecuteNonQuery();
            }
            catch (OleDbException error)
            {
                MessageBox.Show(error.ToString());
            }
            finally
            {
                connection.Close();
            }
            break;
        }
      }
    }
  }

I want to know if there a better way of achieving this. Right now there inst that much data, but in the long run their might be. If there are other comments of the code please let me know.

Edit:changed variable names to correct ones.

Mixing GUI code and database code violates the single responsibility principle. One class (here your form) should have at the best one responsibility. One method (here Suggestion()) should have at best one responsibility. Your method is retrieving items from the GUI and is storing them into the database.

Based on the naming guidelines

method names should be made out of verbs or verb phrases.
variables should be named (also it is not mentioned explicitly for variables which are local to a method) using camelCase casing. You shouldn't use any type of snake_Case casing.

At least if you have choosen a style, also this style isn't following the guidelines you should stick to the choosen style. Right now you are mixing the casing styles.

Calling Convert.ToDouble() on a double or calling ToString() on a String is redundant.

Your loops are starting at 1 and you are accessing the items by [iterator -1]. You should start at 0 as every array in NET.

The starting at 1 and  the ending condition of < thegrid.RowCount will let you miss one row.

You should retrieve Cells["PUR LT"] only if partNumber == material.

Both OleDbConnection and OleDbCommand are implementing IDisposable so enclosing the usage in a using block will automatically call Dispose() on the objects and therefor also close the connection.

Instead of iterating over the rows of the datagridviews you should consider to use linq to do the job.

You should always assume that a cell of the datagridview can be DBNull.Value. So a checking for DBNull should be done.

Refactoring the former method with implementing the mentioned points will lead to a new class for which I have choosen the name RowContent

public class RowContent
{
    public bool IsValid { get; private set; }
    public DateTime RequestedDate { get; private set; }
    public String Material { get; private set; }
    public String Quantity { get; private set; }
    public DateTime SuggestedDate { get; private set; }

    public RowContent(string requestedDate, string material, string quantity)
    {
        RequestedDate = Convert.ToDateTime(requestedDate);
        Material = material;
        Quantity = quantity;
    }

    public void SetPureLeadTime(String leadTime)
    {
        SuggestedDate = GetWorkDays.AddWorkdays(RequestedDate, Convert.ToDouble(leadTime));
        IsValid = true;
    }
}

next we add a method for checking if the givven DataGridViewCell's value is DBNull.

private bool IsNotDBNull(DataGridViewCell cell)
{
    return !cell.Value.Equals(DBNull.Value);
}

No we extract the retrieving of the datagridviews values to a separate method.

private IEnumerable<RowContent> GetSuggestedContents(DataGridView firstGrid, DataGridView secondGrid)
{
    IEnumerable<RowContent> contents =
        firstGrid.Rows
                        .Cast<DataGridViewRow>()
                        .Where(r=> IsNotDBNull(r.Cells["Requested_Date"]) &&
                                   IsNotDBNull(r.Cells["Material"]) &&
                                   IsNotDBNull(r.Cells["Requierd_Qty"]))
                        .Select(r => new RowContent(r.Cells["Requested_Date"].Value.ToString(),
                                                    r.Cells["Material"].Value.ToString(),
                                                    r.Cells["Requierd_Qty"].Value.ToString()));

    foreach (var rowContent in contents)
    {
        String leadTime =
            secondGrid.Rows
                            .Cast<DataGridViewRow>()
                            .Where(r => IsNotDBNull(r.Cells["PartNumber"]) &&
                                r.Cells["PartNumber"].Value.ToString() == rowContent.Material)
                            .Select(r => r.Cells["PUR LT"].Value.ToString()).FirstOrDefault();

        if (String.IsNullOrEmpty(leadTime)) { continue; }

        rowContent.SetPureLeadTime(leadTime);

    }
    return contents.Where(c => c.IsValid);
}

which can be called like

IEnumerable<RowContent> contents = GetSuggestedContents(dataGridView9, dataGridView10);

And last but not least the database manipulating code which returns an IList<string> containing the Message property of any occured OleDbException

private IList<string> UpdateSuggestedContents(IEnumerable<RowContent> contents)
{
    IList<string> errorMessages = new List<string>();

    using (OleDbConnection connection = new OleDbConnection("your connection string here"))
    using (OleDbCommand oleDbCmd = new OleDbCommand("InsertSuggested", connection))
    {
        oleDbCmd.CommandType = CommandType.StoredProcedure;

        OleDbParameter partNumberParameter = oleDbCmd.Parameters.Add("@PartNumber", OleDbType.VarChar, 30);
        OleDbParameter adjustedDateParameter = oleDbCmd.Parameters.Add("@AdjustedDate", OleDbType.Date, 50);
        OleDbParameter suggestedDateParameter = oleDbCmd.Parameters.Add("@SuggestedDate", OleDbType.Date, 50);
        OleDbParameter quantityParameter = oleDbCmd.Parameters.Add("@Qty", OleDbType.VarChar, 30);

        connection.Open();

        foreach (RowContent content in contents)
        {
            partNumberParameter.Value = content.Material;
            adjustedDateParameter.Value = content.RequestedDate;
            suggestedDateParameter.Value = content.SuggestedDate;
            quantityParameter.Value = content.Quantity;
            try
            {
                oleDbCmd.ExecuteNonQuery();
            }
            catch (OleDbException ex)
            {
                errorMessages.Add(ex.Message);
            }
        }
    }
    return errorMessages;
}


What changes, if any, are required to make the following Perl eval bullet proof? eval {
    # here is put some code that may throw exception
    1;  # Why is the "1;" here ?
} or do {
   my $error = $@;
   # Handle error.
};

Does the following style protect against $@ not being set
correctly ?
What does the following "1;" protect against?
Is the "or do{" better than the saying "if ($@){ " ? If so, why?

Ad. 1. Yes and no - there are still some pitfalls (please read further).

Ad. 2. You must remember about returning truthy value from eval block because it evaluates to last value in block unless some code died, in which case undef is returned, so 1; as last statement in eval block is important.

You also have to localize $@ somehow (my $error = $@ in your example) because it's a global variable which can be changed silently (see Conclusion).

Ad. 3. if ($@) can have one pitfall, i.e. it doesn't catch error when it's false:

eval {
  die '';
  do_something();
};
if ($@) {
  # ooops... we don't get here
}

while or do { } block will always be activated in case of exception

eval {
  die '';
  do_something();
  1;
} or do {
  # caught!
};

Conclusion:

I personally use "eval or do # process error" style of catching errors but common and widely used alternative, which eleminates boilerplate code, is to use Try::Tiny. It's a simple, 0-dependency CPAN module which addresses $@ issues. Its documentation (especially BACKGROUND section) is really worth reading as it answers some of your questions and with even more details.

See also this SO question.


Even handler for text input preview In a WPF application I have the following event handler for PreviewTextInput event in ComboBox control. The main purpose of this code is to select an item in ComboBox via pressing a letter key. There is duplicated logic in this code and I want it removed.

private void OnTextComboBoxPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var comboBox = sender as ComboBox;
    if (!comboBox.IsDropDownOpen)
    {
        return;
    }

    if (!comboBox.IsEditable || !comboBox.IsReadOnly)
    {
        return;
    }

    foreach (var item in comboBox.Items)
    {
        if (item == null)
        {
            continue;
        }

        var textSearch = TextSearch.GetTextPath(comboBox);

        var stringItem = item as string;
        if (stringItem != null)
        {
            if (stringItem.StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
            {
                SelectItemInComboBox(comboBox, item);
                break;
            }

            continue;
        }

        var dependencyObjItem = item as DependencyObject;
        if (dependencyObjItem != null)
        {
            var textMember = TextSearch.GetText(dependencyObjItem);
            if (!string.IsNullOrEmpty(textMember))
            {
                var selectorFunc = ExpressionHelper.GetMemberFunction(dependencyObjItem, textMember);
                var textValue = selectorFunc(dependencyObjItem);

                if (textValue.ToString().StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
                {
                    SelectItemInComboBox(comboBox, item);
                    break;
                }

                continue;
            }
        }

        if (!string.IsNullOrEmpty(textSearch))
        {
            var selectorFunc = ExpressionHelper.GetMemberFunction(item, textSearch);
            var textValue = selectorFunc(item);

            if (textValue.ToString().StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
            {
                SelectItemInComboBox(comboBox, item);
                break;
            }
        }
    }

    e.Handled = true;
}

private void SelectItemInComboBox(ComboBox comboBox, object item)
{
    var comboBoxItem = comboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
    comboBoxItem.IsSelected = true;
}

I prefer a simple cast over as when I don't expect an object to be of any other type. If you do expect this, use as and be sure to check for null.

var comboBox = (ComboBox)sender;
When it makes sense to group code together do so.

if (!comboBox.IsDropDownOpen || !combobox.IsEditable || !combobox.IsReadOnly)
Try to use LINQ where possible.
Place variables close to where they are being used. (textSearch)
Don't overuse var. This is subjective, and there are several discussion about it. (also see comments in the code underneath)
Using continue can make it more difficult to get an overview of the code. In some occasions it is useful, but look at the code below to see how you could replace it with normal if else conditions instead.
Identify redundant code, see what you can eliminate and what you can't. You might have to introduce new intermediate variables. (e.g. textToCompare)

Here is the complete reworked example:

private void OnTextComboBoxPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var comboBox = (ComboBox)sender;
    if (!comboBox.IsDropDownOpen || !combobox.IsEditable || !combobox.IsReadOnly)
    {
        return;
    }

    foreach (var item in comboBox.Items.Where( i => i != null ))
    {
        string textToCompare = null;

        if (item is string)
        {
            textToCompare = (string)item;
        }
        else if (item is DependencyObject)
        {
            DependencyObject dependencyObjItem = (DependencyObject)item;

            string textMember = TextSearch.GetText(dependencyObjItem);
            if (!string.IsNullOrEmpty(textMember))
            {
                // From this sample, I don't know what the following type is!
                // I wouldn't use var here.
                var selectorFunc = ExpressionHelper.GetMemberFunction(dependencyObjItem, textMember);
                textToCompare = selectorFunc(dependencyObjItem);
            }
        }
        else
        {
            string textSearch = TextSearch.GetTextPath(comboBox);
            if (!string.IsNullOrEmpty(textSearch))
            {
                var selectorFunc = ExpressionHelper.GetMemberFunction(item, textSearch);
                textToCompare = selectorFunc(item);
            }
        }

        if (textToCompare != null && textToCompare.StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
        {
            SelectItemInComboBox(comboBox, item);
            break;
        }
    }

    e.Handled = true;
}

private void SelectItemInComboBox(ComboBox comboBox, object item)
{
    var comboBoxItem = comboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
    comboBoxItem.IsSelected = true;
}

I will leave it up to you as an exercise whether you can further eliminate the duplicate code from selectorFunc, and whether it would be useful.


Implementing OR with the lc-3 Today, something possessed me and I started learning assembly. My poison of choice is the lc-3, this is my very first program.

It is actually only the first part of a two part problem, but this already took enough that I thought it merited a review, just in case the day's insanity also expressed itself in my code.

It runs without errors, I'm fairly confident the OR logic is sound, I'd like to focus on ascertaining that I'm storing/loading effectively and in the correct locations.

The task:

  Perform an OR on two binary numbers stored in X3020 and x3021
  Store the result at x3022

My code:

.ORIG x3000 ;
  LD R0, x001f  ; fetches data from x3020, stores into R0
  LD R1, x001f  ; fetches data from x3021, stores into R1

  NOT R0, R0    ; start of OR logic
  NOT R1, R1
  AND R2, R0, R1
  NOT R2, R2   ; end of OR logic

  ST R2, x001B  ; Stores result into x3022
  HALT
.END

Gratitude to the brave and wonderful souls who review assembly code.

LD R0, x001f  ; fetches data from x3020, stores into R0
LD R1, x001f  ; fetches data from x3021, stores into R1
ST R2, x001B  ; Stores result into x3022

All of these instructions are correct. When the first instruction is being executed the PC is at x3001. Adding x001F to it will correctly address location x3020. When the third instruction is being executed the PC is at x3007. Adding x001B to it will address location x3022.
From the manual we learn

  Program Counter; 16-bit register that contains the memory address of the next
  instruction to be fetched. For example, during execution of the instruction at address
  A, the PC contains address A + 1, indicating the next instruction is contained in
  A + 1.

and also

  Memory address space 16 bits, corresponding to 65,536 locations, each
  containing one word (16 bits). Addresses are numbered from 0 (i.e, x0000)
  to 65,535 (i.e., xFFFF).

Here's an alternative to your OR solution

NOT R1,R1
AND R0,R0,R1
NOT R1,R1
ADD R0,R0,R1

The less registers you use the better on the very limited architecture of the LC-3.


Stack implemented using linked list in x86_64 assembly I wrote a stack implementation using a singly linked list in x86_64 assembly. This stack supports the usual push/pop operations as well as first/next for iterating over each element.

I'm looking for general feedback.

Here are the stack subroutines:

; Stack Structure
;   Pointer Head
;   Pointer Current

; Stack Node
;   Pointer Next
;   Pointer Value

; input
;   void
; output
;   stack or 0 on error
StackCreate:
  mov rdi, 24
  call malloc
  test rax,rax
  jz StackCreate_end
  xor rdi, rdi
  mov [rax], rdi
  mov [rax+8], rdi
  ret
StackCreate_end:
  add rsp, 8
  ret

; input
;   stack
; output
;   void
StackDestroy:
  call free
  ret

; input
;   stack
;   value
; output
;   0 on error
StackPush:
  push rdi
  push rsi
  mov rdi, 16
  call malloc
  test rax,rax
  jz StackPush_end
  pop rsi
  pop rdi
  mov rdx, [rdi]
  mov [rax], rdx
  mov [rax+8], rsi
  mov [rdi], rax
  ret
StackPush_end:
  add rsp, 16
  ret

; input
;   stack
; output
;   value or 0 if empty
StackPop:
  mov rsi, rdi
  mov rdi, [rdi]
  test rdi, rdi
  jz StackPop_end
  mov rax, [rdi]
  mov [rsi], rax
  mov rax, [rdi+8]
  push rax
  call free
  pop rax
  ret
StackPop_end:
  xor rax, rax
  ret
  nop;e

; input
;   stack
; output
;   value or 0 if empty
StackFirst:
  mov rax, [rdi]
  test rax, rax
  jz StackFirst_end
  mov rsi, [rax]
  mov [rdi+8], rsi
  mov rax, [rax+8]
StackFirst_end:
  ret

; input
;   stack
; output
;   value or 0 if end
StackNext:
  mov rsi, [rdi+8]
  test rsi, rsi
  jz StackNext_end
  mov rax, [rsi]
  mov [rdi+8], rax
  mov rax, [rsi+8]
  ret
StackNext_end:
  xor rax, rax
  ret

Here is a driver:

[extern puts]
[extern malloc]
[extern free]

[SECTION .data]

arguments:
  db "Incorrect arguments.",10,"Expected: stackme <string1> <string2> ...",0

[SECTION .text]
BITS 64
global main

wrong_arguments:
  mov rdi, arguments
  call puts
  jmp main_end

main:
  cmp rdi, 1
  jle wrong_arguments

  lea r12, [rsi+8]
  lea r13, [rdi-1]

  call StackCreate
  test rax, rax
  jz main_end
  mov r14, rax

pushing_loop:
  test r13, r13
  jz pushing_done
  mov rdi, r14
  mov rsi, [r12]
  call StackPush
  add r12, 8
  dec r13
  jmp pushing_loop
pushing_done:

  mov rdi, r14
  call StackFirst
print_loop:
  test rax, rax
  jz print_done
  mov rdi, rax
  call puts
  mov rdi, r14
  call StackNext
  jmp print_loop
print_done:

stack_delete:
  mov rdi, r14
  call StackPop
  test rax, rax
  jnz stack_delete
stack_delete_done:
  mov rdi, r14
  call StackDestroy

main_end:
  xor eax, eax
  ret

Assembling/Linking

nasm -f elf64 -l stackme.lst stackme.asm
gcc -o stackme stackme.o

The code is generally well written and easy to understand, but I have a few comments on it that could help improve it.

Eliminate "magic numbers"

In the StackCreate routine, the first instruction is mov rdi,24 but it's not clear what 24 signifies in this context.  Either a comment or a named constant or both would help with that.

Add more meaningful comments

The stack structure is not very clear from the comments.  We can infer that the stack consists of nodes, but it's not easy to tell from the code or the comments.

Also, consider the user of the stack code.  There isn't currently enough within the code to understand the calling sequence, register usage or return values.  All of those would be useful to have in the comments.  If you're intending to use a standard ABI, it would be useful to say which one.

Use rep ret as appropriate

The gcc compiler emits rep ret when the ret could be the target of a jump.  This seems weird (and it is!) but the reason is that the branch prediction logic on both AMD and Intel processors works better when the ret is not the target of branch.  So this means the StackFirst_end label in your code should actually have a rep prefix just before the ret.

Use struc as appropriate

Because your stack uses two structures, it would benefit from using NASM's struc/endstruc macros.  This would both make it more clear when the code is manipulating data structures and also eliminate quite a few of the "magic numbers" I mentioned earlier.

Consider refactoring StackFirst and StackNext

Other than minor differences in specific register selection, the StackFirst and StackNext routines are very similar.  It may be possible to combine them to eliminate some code.

Reduce use of malloc and free

The malloc and free calls tend to be relatively computationally expensive, especially relative to the assembly code you've got.  For that reason, it would probably make more sense to either allocate and manage a block rather than calling malloc for every stack push, or to replace calls to malloc and free with some other memory allocation scheme that might be user-replaceable for speed.

Rearrange the loop to avoid unconditional jumps

The current pushing_loop looks like this:

    pushing_loop:
      test r13, r13
      jz pushing_done
      mov rdi, r14
      mov rsi, [r12]
      call StackPush
      add r12, 8
      dec r13
      jmp pushing_loop
    pushing_done:

However, it could be slightly rearranged to eliminate one of the jumps:

      inc r13
      jmp push_test

    pushing_loop:
      mov rdi, r14
      mov rsi, [r12]
      call StackPush
      add r12, 8
    push_test:
      dec r13
      jnz pushing_loop

The unconditional jump is only made once at the top of the loop and all other iterations use only the conditional test at the bottom of the loop.  There are a few other places in the code this could be applied.


Find the longest connect cells region per color I have been studying graphs/BFS/DFS. working on wrapping my head around the following problem

  Given a grid [m,n] where each cell has a value denotes a color, find the longest connected region that shares the same color (color is an int)

I was able to come up with the following algorithm that uses a (BFS) Breadth Search First mechanism. I would appreciate your feedback.

I also wanted to try and craft a solution using DFS. I know I might run into a stack overflow issues if the graph is too big. However, I would appreciate any feedback on how to construct my algo using DFS ( I couldn't wrap my head around DFS with different colors at play)

The initialization method:

/// <summary>
/// Finds the longest connect region per color.
/// </summary>
/// <returns>Returns a pair that has the color and the count of the connected cells</returns>
public static Tuple<int,int> FindLongestConnectedColor()
{
    int[,] graph = {
                        {1, 1, 1, 2,2,3},
                        {1, 1, 1, 2,2,3},
                        {1, 1, 1, 2,2,3}
                    };

    var graphRowsCount = graph.GetLength(0);
    var graphColumnsCount = graph.GetLength(1);

    var visitedCellsPerColor = new Dictionary<int, HashSet<Tuple<int, int>>>();

    // first int represents the color, second int represents the region cells' count
    var longestRegion = new Tuple<int, int>(-1, -1);

    for (int row = 0; row < graphRowsCount; row++)
    {
        for (int column = 0; column < graphColumnsCount; column++)
        {
            var color = graph[row, column];

            if (!visitedCellsPerColor.ContainsKey(color))
            {
                visitedCellsPerColor.Add(color, new HashSet<Tuple<int, int>>());
            }

            if (!visitedCellsPerColor[color].Contains(new Tuple<int, int>(row, column)))
            {
                var length = GetConnectedRegionLength(row, column, graph, visitedCellsPerColor);
                if (longestRegion.Item2 < length)
                {
                    longestRegion = new Tuple<int, int>(color, length);
                }
            }
        }
    }

    return longestRegion;
}

My BFS logic

I am using two queues to avoid boxing/unboxing performance hit
I only consider cells that are of the same color
I only consider unvisited cells if they belong to the same color

Code:

private static int GetConnectedRegionLength(int row, int column, int[,] graph, Dictionary<int, HashSet<Tuple<int, int>>> visited)
{
    var directionRow = new List<int> { -1, +1, 0, 0 };
    var directionColumn = new List<int> { 0, 0, +1, -1 };
    var graphRowsCount = graph.GetLength(0);
    var graphColumnsCount = graph.GetLength(1);

    var connectedCellsCount = 0;

    var color = graph[row, column];

    var q1 = new Queue<int>();
    var q2 = new Queue<int>();

    q1.Enqueue(row);
    q2.Enqueue(column);
    visited[color].Add(new Tuple<int, int>(row, column));
    connectedCellsCount++;

    while (q1.Any())
    {
        // current Row
        var cr = q1.Dequeue();
        // Current Column
        var cc = q2.Dequeue();

        for (int a = 0; a < directionRow.Count; a++)
        {
            var newRow = cr + directionRow[a];
            var newColumn = cc + directionColumn[a];

            if (newRow < 0 || newColumn < 0) continue;
            if (newRow >= graphRowsCount  || newColumn >= graphColumnsCount ) continue;
            if (graph[newRow, newColumn] != color) continue;
            if (visited[color].Contains(new Tuple<int, int>(newRow, newColumn))) continue;

            q1.Enqueue(newRow);
            q2.Enqueue(newColumn);
            visited[color].Add(new Tuple<int, int>(newRow, newColumn));
            connectedCellsCount++;
        }
    }

    return connectedCellsCount;
}

Looks fine overall, but there are a few oddities here and there, and there are some opportunities for significant performance improvements:

Since you're going to visit every node in the given int[,] graph you might as well use a bool[,] instead of a Dictionary<int, HashSet<Tuple<int, int>>>. I see no reason to group visited nodes per color, because you're already keeping track of the largest group separately. For me, this made things about 6x faster.
Using an 'old-style' tuple as return type isn't very descriptive. Consider using value-tuples instead: public static (int color, int count) FindLongestConnectedColor().
In GetConnectedRegionLength, I'd combine directionRow and directionColumn into a single array of (int x, int y) tuples. Not a list - it's not going to be resized. This also provides a small performance increase. Also consider storing it in a static field, so you only need to initialize the array once, for yet another performance increase.
q1 and q2 are rather undescriptive names - openNodes would be better. It's also unclear why there are two queues instead of one (you mentioned the reason in your post, but it's not documented in the code). About that reason - Queue<T> is generic, so a Queue<Tuple<int, int>> or Queue<(int, int)> is not going to involve boxing. Yes, you'll need to create tuple objects, but you no longer need to call Enqueue and Dequeue twice. Performance should be more or less the same. When in doubt, measure!
connectedCellsCount can be initialized to 1 directly.
while (q1.Count > 0) is faster than while (q1.Any()).
a is rather uncommon as a counter variable name - I'd stick to i.
Personally I'm not a fan of putting single if-body statements on the same line: if (...) continue;. It makes these 'early-outs' more difficult to spot when scanning code.
The various if/continue statements can be combined into a single if.

As for breadth-first versus depth-first, I guess I don't really see the point here: the only difference is the order in which you visit nodes, but you still have to visit all of them. Either way, instead of recursion you can also combine iterative code with a stack data-structure. Similar to your current solution, just with a stack instead of a queue.


Summary Output of Pricing Information This function is used in a ASP.NET web application written in C#. It is heavily used to output summary information of the some prices chosen by a user. We are trying to lessen how much we have to scale horizontally.

Here is the original function:

    private static Dictionary<int, string> Cache = new Dictionary<int, string> {{ 1, "Adult" }, { 2, "Child" }};

    public string Build(List<int> priceTypeIds)
    {
        if (session == null)
        {
            return "";
        }

        var uniquePriceTypeIds = priceTypeIds.Distinct();

        var result = new List<string>();

        foreach (var priceTypeId in uniquePriceTypeIds)
        {
            var count = priceTypeIds.Count(x => x == priceTypeId);

            var description = Cache[priceTypeId];

            result.Add($"{count} {description}");
        }

        return string.Join(", ", result);
    }

I rewrote the function to eliminate the amount of string concatenations. But

private static Dictionary<int, string> Cache = new Dictionary<int, string> {{ 1, "Adult" }, { 2, "Child" }};

public static string CreateSummary()
{
    var sb = new StringBuilder();

    List<int> sample = new List<int> { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };

    foreach (var priceTypeId in sample.Distinct())
    {
        if (sb.Length > 0)
        {
            sb.Append(',');
            sb.Append(' ');
        }

        sb.Append('(');
        sb.Append(Sample.Count(x => x == priceTypeId));
        sb.Append(')');
        sb.Append(' ');
        sb.Append(Cache[priceTypeId.ToString()]);
    }

    return sb.ToString();
}

The sample data in the second function is a common use case as we have classes get purchased with 20-30 kids in a single transaction along with chaperones.

It looks to me, that your problem could do with a bit more LINQ and the string concatenation operator.  Specifically the group clause.  Here's one way it could be done:

public static string Method2()
{
    List<int> sample = new List<int> { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };

    var data = String.Join(", ", (from int i in sample
                                 group i by i into g
                                 select $"({g.Count()}) {Cache[g.Key.ToString()]}"));

    return data;
}

The efficiency, I think would be better than what you have so far,the Distinct and each Count are extra iterations over the data, but, it would have to be tested to be sure.

It definitely has the advantage of being more concise.

Having the string format in one place makes it easier to see what's happening.

If you need the data parsed, instead of one long string, at some point, removing the String.Join part will leave an IEnumerable<string>.


Handling of memorystream with streamwriter efficiency My little program I'm working on generates charts (GUI) and (on another tab) lists the values my chart is fed from.

2011.01.01 0:00:00     456
2011.01.02 0:00:00     45
2011.01.03 0:00:00     46
2011.01.04 0:00:00     6
2011.01.05 0:00:00     1500
...

When I click on the "Generate Chart" button, after the chart generator code has run, the following method is also invoked (that generates the table above):

void FillGridDetails(List<NameSeries> chartDataIn)

This fills a grid with the values. (DateTime as key, and float as value, nothing special...)

// Creating the rows.
gridDetails.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(30) }); // First row (Date/Time)
int maxCount = chartDataIn[maxIndex].seriesData.Count;
int rowCount = 1;

// Create the memory stream to write the data in (later this will be written to a file if the users clicks the export button).
ms = new MemoryStream(); // This is a class level variable.
StreamWriter writer = new StreamWriter(ms) { AutoFlush = true };
foreach (var aDataRow in chartDataIn[maxIndex].seriesData)
{
    // Adding the first column's rows.
    Label lblDate = new Label() { Content = aDataRow.Key.ToString(dateFormatIn), HorizontalAlignment = HorizontalAlignment.Center };
    gridDetails.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(30) });
    gridDetails.Children.Add(lblDate);
    Grid.SetRow(lblDate, rowCount);
    Grid.SetColumn(lblDate, 0);
    writer.Write(aDataRow.Key.ToString() + ";");

    // Adding the further columns' rows.
    for (int i = 0; i < chartDataIn.Count; i++)
    {
        string value = chartDataIn[i].seriesData.ContainsKey(aDataRow.Key) ? chartDataIn[i].seriesData[aDataRow.Key].ToString() : "-";
        Label lblData = new Label() { Content = value };
        gridDetails.Children.Add(lblData);
        Grid.SetRow(lblData, rowCount);
        Grid.SetColumn(lblData, i + 1);

        if (i == chartDataIn.Count - 1)
        {
            writer.WriteLine(value == "-" ? "" : value);
        }
        else
        {
            writer.Write(value == "-" ? ";" : value + ";");
        }
    }

    rowCount++;
}

On this tab there is a CSV Export button, click:

SaveFileDialog dlg = new SaveFileDialog()
{
    FileName = "EM_ExportedData",
    DefaultExt = ".csv",
    Filter = "CSV comma separated values (.csv)|*.csv"
};

if ((bool)dlg.ShowDialog())
{
    //try
    //{
    using (FileStream file = new FileStream(dlg.FileName, FileMode.Create, FileAccess.Write))
    {
        ms.WriteTo(file);
        ms.Dispose();
        btnExportCSV.Content = Strings.CSVExported;
        btnExportCSV.IsEnabled = false;
        MessageBox.Show(String.Format(Strings.successfulSavedCSVFile, dlg.FileName));
    }
}

Could it cause any sort of disadvantages in memory efficiency? I'm thinking of, e.g., not closing the filestream or something. If I close the fileStream, later I can't access the memory stream because that's also closed. Any recommendations for this code part is much appreciated.

(What I wanted to do is this: store the values in the memory or somewhere (right after the generation) and when the user wants to export it is simply written to the file. I was also thinking of copy paste the foreach loop but only with the memory-writing parts.)

It looks like you are wasting your efforts on premature optimization. Which also results in a quite ugly code.

I think you should separate your grid-filling logic from csv export. There should be no memory streams, steam writers, etc. in your first method. Also notice that you have code duplication in it, so you might want to extract label creation logic to separate method. Ideally you'd want to remove this logic all together and use WPF ListView (or ItemsControl) with data-binding instead.

As for your second method - you do not need any buffers. Just iterate through your data, create strings and write them directly to your FileStream. You might also want to encapsulate this logic in some separate class and perform it in the background thread so your UI does not freeze for large data.


"Sherlock and queries" challenge I'm writing some Java code for some pretty large datasets, in a puzzle I'm trying to solve.  The output is correct, but the program doesn't run within the time limit for all the test cases.  I've tried a number of optimizations, but can't think about how to improve it.  I'd appreciate your suggestions.

The puzzle is here.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer(br.readLine());
int N = Integer.parseInt(tok.nextToken());
int M = Integer.parseInt(tok.nextToken());
long[] A = new long[N];
int[] B = new int[M];
long[] C = new long[M];
tok = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) A[i] = Long.parseLong(tok.nextToken());
tok = new StringTokenizer(br.readLine());
for (int i = 0; i < M; i++) B[i] = Integer.parseInt(tok.nextToken());
tok = new StringTokenizer(br.readLine());
for (int i = 0; i < M; i++) C[i] = Long.parseLong(tok.nextToken());
br.close();

for (int i = 0; i < M; i++) {
    for (int j = B[i] - 1; j < N; j += B[i]) {
        A[j] = (A[j] * C[i]) % 1000000007;
    }
}
for (long l : A) System.out.print(l + " ");

This is one of the beefs I have with online judging systems like this..... it is not testing the algorithm, or anything like that. Instead, consider doing the very last line like:

// the longest value will be 11 chars long because % 1000000007 + " "
StringBuilder sb = new StringBuilder(N * 11);
for (long l : A) {
    sb.append(l).append(" ");
}
System.out.print(sb.toString());

A single println is almost always N times faster than N printlns.

If that does not make it work in time, then consider reading the entire System.in in to a buffer, and parsing it from the buffer.


Reading a repetitive file with repetitive code I made this code for take some data from a .txt file. The text file is a large list of data from temperature with a format that is repetitive and have some lines at the beginning with the station reference. I took the first ten lines but only one time, then I jump to line 12 to take the headers and then I have a mark that tell me if a new year of records is beginning and jump to line 13 and write from the line 13 to 30.

Is there a Pythonic way, without a lot of next(f)?

from itertools import islice
with open(rutaEscribir,'w') as w:
    with open(rutaLeer) as f:
        for line in islice(f,1,10):
            w.write(line)
        f.seek(0)
        for line in islice(f,12,13):
            w.write(line)
        f.seek(0)
        ano = 1977
        for line in f:
            sena = '&'
            if sena in line:
                print('Found')
                print('Año: ',ano)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                for n in  islice(f,0,31):
                    w.write(n)
                ano += 1

Here is an excerpt from the file:

&                      I D E A M  -  INSTITUTO DE HIDROLOGIA, METEOROLOGIA Y ESTUDIOS AMBIENTALES
                                                                                SISTEMA DE INFORMACION
                                   VALORES TOTALES DIARIOS DE RECORRIDO DEL VIENTO (Kms)                       NACIONAL AMBIENTAL

   FECHA DE PROCESO :  2016/09/08                    ANO  1986                              ESTACION : 26185020  MESOPOTAMIA

   LATITUD    0553 N               TIPO EST    CO                   DEPTO      ANTIOQUIA               FECHA-INSTALACION  1970-JUN
   LONGITUD   7519 W               ENTIDAD     01  IDEAM            MUNICIPIO  LA UNION                FECHA-SUSPENSION
   ELEVACION  2314 m.s.n.m         REGIONAL    01  ANTIOQUIA        CORRIENTE  BUEY

***********************************************************************************************************************************
         DIA       ENERO *  FEBRE *  MARZO *  ABRIL *  MAYO  *  JUNIO *  JULIO *  AGOST *  SEPTI *  OCTUB *  NOVIE *  DICIE *
***********************************************************************************************************************************

          01         144      35        10       32       52        6       81      133       44       29        7       17
          …
          05          35     +          31       18       16       15      110      160      125       12       18       56
          …

As you can see on the right, this is a repetitive file. In line 57 I put the & marker for the start of a new year of records.  The next few lines (57 to 65) contain the geographical position from the station, followed by the month header (ENERO,FEB...).  Then, 31 lines contain the data for that year.  I want to use PANDAS to analyze that data.

My code transforms it into something like this:

As you can see, the repetitive headers for geographical position and the months now appear just once.

But I think is possible to do it in a Pythonic way and not with a lot of next(f).

Well, you could find a "Pythonic" way to skip around a file, but that still wouldn't make it good code, in my opinion.  There are some fundamental issues with your approach that make it rather hackish:

f.seek(0) means that the file isn't being processed sequentially, and creates extra work.
You're hard-coding ano = 1977 when in fact ANO  1977 would be right there in the data file itself!  And you're deliberately skipping over that valuable information!  And then you have to hope that the file really does start with data for 1977!
This data format is human-friendly but machine-hostile.  You say that your ultimate goal is to import the data into pandas for analysis.  But PANDAS doesn't easily understand this IDEAM data format.  In fact, your output is just as difficult to parse as the original, but worse, since stripping out the year headers makes the data less self-documenting.  The work to implement a real parser seems unavoidable.  So, if you're going to transform the data, why not transform it into one of the formats that PANDAS knows how to read?
1, 10, 12, and 13 are "magic" numbers.  There is no way to understand why those numbers are there in the code.  Basically, you're blindly assuming that the input is in a certain format without any verification.  If your assumption is wrong, you could easily load data into your analysis incorrectly, and you would never know about the mistake.  You wouldn't want the wrong kind of publicity for your climate analysis, would you?

Therefore, I consider your approach to be a poor substitute for properly parsing the file.  Here, for example, would be one way to parse this data format:

import fileinput
import re

class IdeamParser:
    def __init__(self, *patterns):
        self.patterns = [(re.compile(regex), act) for regex, act in patterns]

    def parse(self, line_iter):
        for line in line_iter:
            for regex, action in self.patterns:
                matches = regex.search(line)
                if matches:
                    yield from action(self, matches)

    def start_meta(self, matches):
        self.meta = {}
        yield from []

    def read_meta(self, matches):
        self.meta.update(dict(zip(matches.groups()[::2], matches.groups()[1::2])))
        yield from []

    def months_header(self, matches):
        line = matches.group()
        self.month_cols = [m.span() for m in re.finditer(' *(\S+) *[*]', line)]
        yield from []

    def read_data(self, matches):
        day_of_month = int(matches.group(1))
        line = matches.group()
        values = [line[start:end] for start, end in self.month_cols]
        values = [float(val) if re.search(r'\d', val) else None for val in values]
        yield self.meta, day_of_month, values

parser = IdeamParser(
    (r'^\s*(\d{2})\s+(.*)', IdeamParser.read_data),
    (r'I D E A M', IdeamParser.start_meta),
    (r'(VALORES) (.*\(.*\))', IdeamParser.read_meta),
    (r'(FECHA DE PROCESO) : *(\d{4}/\d{2}/\d{2}) *'
        r'(ANO) +(\d{4}) *'
        r'(ESTACION) : *(.*?) *$', IdeamParser.read_meta),
    (r'(LATITUD) +(.*?) *'
        r'(TIPO EST) +(.*?) *'
        r'(DEPTO) +(.*?) *'
        r'(FECHA-INSTALACION) +(.*?) *$', IdeamParser.read_meta),
    …
    (r'\s*DIA +ENERO.*', IdeamParser.months_header),
)
for meta, day_of_month, values in parser.parse(fileinput.input()):
    print(meta, day_of_month, values)

Sample output:

{'DEPTO': 'ANTIOQUIA', 'FECHA DE PROCESO': '2016/09/08', 'LATITUD': '0553 N', 'FECHA-INSTALACION': '1970-JUN', 'ANO': '1986', 'TIPO EST': 'CO', 'ESTACION': '26185020  MESOPOTAMIA', 'VALORES': 'TOTALES DIARIOS DE RECORRIDO DEL VIENTO (Kms)'} 1 [144.0, 35.0, 10.0, 32.0, 52.0, 6.0, 81.0, 133.0, 44.0, 29.0, 7.0, 17.0]
…
{'DEPTO': 'ANTIOQUIA', 'FECHA DE PROCESO': '2016/09/08', 'LATITUD': '0553 N', 'FECHA-INSTALACION': '1970-JUN', 'ANO': '1986', 'TIPO EST': 'CO', 'ESTACION': '26185020  MESOPOTAMIA', 'VALORES': 'TOTALES DIARIOS DE RECORRIDO DEL VIENTO (Kms)'} 5 [35.0, None, 31.0, 18.0, 16.0, 15.0, 110.0, 160.0, 125.0, 12.0, 18.0, 56.0]

The print() statement at the end is just for demonstration.  You should replace it with code that generates a CSV file or SQL INSERT statements or something.  Or you could just load it into PANDAS directly.


Advent of Code 2017 Day 5 (part 1) in Functional Programming (FP) I wanted to practice functional programming (FP) without using any library but using vanilla JS only. So I took a problem from Advent of Code (the 1st part of Day 5):

  An urgent interrupt arrives from the CPU: it's trapped in a maze of
  jump instructions, and it would like assistance from any programs with
  spare cycles to help find the exit.

  The message includes a list of the offsets for each jump. Jumps are
  relative: -1 moves to the previous instruction, and 2 skips the next
  one. Start at the first instruction in the list. The goal is to follow
  the jumps until one leads outside the list.

  In addition, these instructions are a little strange; after each jump,
  the offset of that instruction increases by 1. So, if you come across
  an offset of 3, you would move three instructions forward, but change
  it to a 4 for the next time it is encountered.

  For example, consider the following list of jump offsets:

0
3
0
1
-3

  Positive jumps ("forward") move downward; negative jumps move upward.
  For legibility in this example, these offset values will be written
  all on one line, with the current instruction marked in parentheses.
  The following steps would be taken before an exit is found:

  (0) 3  0  1  -3  - before we have taken any steps.
  (1) 3  0  1  -3  - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1.
  2 (3) 0  1  -3  - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2.
  2  4  0  1 (-3) - jump all the way to the end; leave a 4 behind.
  2 (4) 0  1  -2  - go back to where we just were; increment -3 to -2.
  2  5  0  1  -2  - jump 4 steps forward, escaping the maze.

  In this example, the exit is reached in 5 steps.

  How many steps does it take to reach the exit? Input :
  https://adventofcode.com/2017/day/5/input

My solution in FP:

  const parsedInput = input => input
    .split('\n')
    .map(c => parseInt(c));

  const jumper = input => {
    const currentMaze = input.maze;
    const currentPosition = input.position;
    const currentStepNumber = input.stepNumber;
    if (currentPosition >= currentMaze.length) {
      return currentStepNumber;
    }
    const newOffset = currentMaze[currentPosition] + 1;
    const maze = currentMaze
     .slice(0, currentPosition)
     .concat(newOffset)
     .concat(currentMaze.slice(currentPosition + 1));
    const position = currentPosition + currentMaze[currentPosition];
    const stepNumber = currentStepNumber + 1;
    return jumper({
      maze, position, stepNumber
    });
  };

  const startMaze = parsedInput(INPUT);
  const solution = jumper({
    maze: startMaze,
    position: 0,
    stepNumber: 0
  });

  console.log("solution ", solution);

Running this code with node9 in normal mode will create a RangeError: Maximum call stack size exceeded. I had to "cheat" by running this code in node 6: node --harmony 05_1.js (node 6 supports Tail Cail Optimization (TCO) when the flag --harmony is turned on). I also tried to cache the maze but this didn't help either. I got the feeling that big size Input is the limit for FP.

Simple and pure

Regarding the comments the following is an example of a simple JS solution to the problem. Turns out that it is also a pure function.

// list is a copy of input, thus passing strings is inherently pure
function traverseJumpList(list) {
    list = list.split("\n");  // no need to parse the numbers as
                              // the ++ operator will coerce a string to
                              // a number for you..
    var jumps = 0, index = 0;
    // Assuming that an exit jump is also jumping to negative index
    while (index >= 0 && index < list.length) {
        jumps += 1;
        index += list[index]++;
    }
    return jumps;
}
const solution = traverseJumpList(INPUT);

Recursion

This particular problem can not be solved via recursion without proper tail calls  because you can not know the max steps in advance.

Memory

Even with tail calls on you are still fighting JS because you are not being memory aware. In the function jumper you create a new copy of the maze and then make the next jump via recursion.

This means for each jump you create a complete copy of the maze and hold it in memory until the end. So if you have a maze with 1024 items and it takes 2048 jumps to complete you will have 2097152 unique items. This is very wasteful by any standard.

You should release the previous maze before you make the next jump

  const jumper = input => {
    var currentMaze = input.maze;
    const currentPosition = input.position;
    const currentStepNumber = input.stepNumber;
    if (currentPosition >= input.maze.length) {
       return currentStepNumber;
    }
    const newOffset = input.maze[currentPosition] + 1;
    const maze = input.maze
     .slice(0, currentPosition)
     .concat(newOffset)
     .concat(input.maze.slice(currentPosition + 1));
    const position = currentPosition + input.maze[currentPosition];
    const stepNumber = currentStepNumber + 1;

    // clean up memory
    input = undefined;

    return jumper({maze, position, stepNumber});

  };

Indirect recursion.

An alternative to direct recursion is indirect recursion. This is done by calling the recuse function using a time event. The code is similar but you will need to provide the result as a function call.

This method gives unlimited recursion and frees up all incidental memory by releasing each recursive call's context from the heap before doing the next iteration. Also exiting to context idle makes GC more efficient.

Using your jumper function as an example.

  const jumper = input => {
    const currentMaze = input.maze;
    const currentPosition = input.position;
    const currentStepNumber = input.stepNumber;
    if (currentPosition >= currentMaze.length) {
      // return currentStepNumber;
      showAnswer(currentStepNumber);   // The result must be called in
      return;
    }
    const newOffset = currentMaze[currentPosition] + 1;
    const maze = currentMaze
     .slice(0, currentPosition)
     .concat(newOffset)
     .concat(currentMaze.slice(currentPosition + 1));
    const position = currentPosition + currentMaze[currentPosition];
    const stepNumber = currentStepNumber + 1;
    // call next step via timeout. This will not execute until after
    // this function has exited.
    setTimeout(() => jumper({maze, position, stepNumber}),0);

    // this function now exits before the next jump releasing the
    // original input object
  };

And the starting and answer functions

  jumper({maze: startMaze, position: 0, stepNumber: 0});
  const showAnswer = (result) => console.log(result);

Or you could have jumper return a promise on the first pass which resolves with the answer. I am not too sure if this fits the FP paradigm.


Determine the roots of a Quadratic Equation A code that determines the roots of a quadratic equation.
Also, determine the following based on the discriminant b² – 4ac:

If b² − 4ac is positive, display: “There are TWO REAL SOLUTIONS.”
If b² − 4ac is zero, display: “There is ONLY ONE REAL SOLUTION.”
If b² − 4ac is negative, display: “There are TWO COMPLEX SOLUTIONS.”

#include <stdio.h>
#include <math.h>

int main(){

    int a, b, c, d;
    double root1_real, root2_real, root1_complex, root1_i, root2_complex, root2_i, root_zero;

    printf("Enter a, b and c where a*x*x + b*x + c = 0\n");
    scanf("%d %d %d", &a, &b, &c);

    d = b * b - 4 * a * c;

     if(d > 0){ // Positive
        root1_real = (-b + sqrt(d)) / (2*a);
        root2_real = (-b - sqrt(d)) / (2*a);
        printf("First Root : %.2lf\n", root1_real);
        printf("Second Root : %.2lf\n", root2_real);
        printf("There are TWO REAL SOLUTIONS\n");
     }else if(d < 0){ // Negative
        root1_complex = -b / (2 * a); root1_i = sqrt(-d) / (2 * a);
        root2_complex = -b / (2 * a); root2_i = sqrt(-d) / (2 * a);
        printf("First root : %.2lf + i%.2lf\n", root1_complex, root1_i);
        printf("Second root : %.2lf + i%.2lf\n", root2_complex, root2_i);
        printf("There are TWO COMPLEX SOLUTIONS\n");
     }else{ // Zero
        root_zero = (-b + sqrt(d)) / (2*a);
        printf("Root : %.2lf\n", root_zero);
        printf("There is ONLY ONE REAL SOLUTION\n");
     }

     return 0;

}

int main(void) is preferable, as that's clear about the number of arguments.
I don't understand why the coefficients must be integers - surely a quadratic equation can have any real coefficients?
We don't test whether the scanf() actually converted all three inputs.  If we are given something that's not an integer (perhaps a different kind of number, perhaps just garbage input), then the program will proceed with incorrect data, and produce output that might be plausible, instead of a sensible error message.  We need something more like:
double a, b, c;
if (scanf("%lf %lf %lf", &a, &b, &c) != 3) {
   fputs("Invalid input\n", stderr);
   return 1;
}

There is another case of invalid input that's not checked - if a is zero, we don't want to divide by it.
You seem to have got confused which part is real and which imaginary here:
    root1_complex = -b / (2 * a); root1_i = sqrt(-d) / (2 * a);
    root2_complex = -b / (2 * a); root2_i = sqrt(-d) / (2 * a);

If we use better variable names, and reduce their scope a bit, we can make that simpler:
    double real = -b / (2 * a);
    double imag = sqrt(-d) / (2 * a);

And we can do all the printing in a single call to printf:
    printf("First root : %.2f + i%.2lf\n"
           "Second root : %.2lf + i%.2lf\n"
           "There are TWO COMPLEX SOLUTIONS\n",
           real, -imag,   real, imag);

When we know d is zero, there's really no point computing its square root:
 } else { // Zero
    root_zero = -b / (2*a);

As suggested in a comment, it might also be worth computing that common part of the three expressions to outside the if/else:
const double real =  -b / a / 2;
if (d > 0) { // Positive
    double root = sqrt(d) / a / 2;
    ⋮
} else if (d < 0) { // Negative
    double imag = sqrt(-d) / a / 2;
    ⋮
} else { // Zero
    ⋮
}

Here's a lightly modified version with my suggestions applied:
#include <stdio.h>
#include <math.h>

int main(void)
{
    printf("Enter a, b and c where ax² + bx + c = 0\n");
    double a, b, c;
    if (scanf("%lf%lf%lf", &a, &b, &c) != 3) {
        fputs("Invalid input\n", stderr);
        return 1;
    }
    if (!a) {
        fputs("Quadratic term must not be zero\n", stderr);
        return 1;
    }

    const double d = b * b - 4 * a * c;

    printf("Finding the roots of %gx² + %gb + %g = 0\n", a, b, c);

    const double real =  -b / a / 2;
    if (d > 0) {
        double root = sqrt(d) / a / 2;
        printf("First Root: %.4g\n"
               "Second Root: %.4g\n"
               "There are TWO REAL SOLUTIONS\n",
               real - root,   real + root);
    } else if (d < 0) {
        double imag = sqrt(-d) / a / 2;
        printf("First root: %.4g + %.4gi\n"
               "Second root: %.4g + %.4gi\n"
               "There are TWO COMPLEX SOLUTIONS\n",
               real, -imag,   real, imag);
    } else { // d == 0
        printf("Root: %.4g\n"
               "There is ONLY ONE REAL SOLUTION\n",
               real);
    }
}


Recording error messages from an exception How do I shorten these if else statements? As you can see, those elses are repeated.

if (exception.InnerException != null)
{
    if (!string.IsNullOrEmpty(exception.InnerException.Message))
    {
        errorMessage = exception.InnerException.Message;
    }
    else if (!string.IsNullOrEmpty(exception.Message))
    {
        errorMessage = exception.Message;
    }
    else
    {
        errorMessage = exception.ToString();
    }
}
else if (!string.IsNullOrEmpty(exception.Message))
{
    errorMessage = exception.Message;
}
else
{
    errorMessage = exception.ToString();
}

In C# 6 or later you can write it in a single line of code using the null conditional operator (?.) and the null coalescing operator (??):

ver errorMessage =  exception.InnerException?.Message ??
                    exception.Message ??
                    exception.ToString();

Note that it will not handle empty strings (if the Message property contains an empty string it will be returned), but then again, I've never heard of exceptions with empty strings as their message...

If you fear that situation, you can always create an extension method for strings that will return null for empty strings:

public static string NullIfEmpty(this string str)
{
    return string.IsNullOrEmpty(str) ? null : str;
}

and then use it like this:

ver errorMessage =  exception.InnerException?.Message?.NullIfEmpty() ??
                    exception.Message?.NullIfEmpty() ??
                    exception.ToString();


My attempt at an immutable container view in C++ I have this very simple template:

#include <algorithm>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <list>
#include <set>
#include <vector>

template<class Container>
class ImmutableContainerView {
private:
    Container& my_container;
public:
    ImmutableContainerView(Container& container) :
    my_container {container} {}

    typename Container::const_iterator cbegin() const {
        return my_container.cbegin();
    }

    typename Container::const_iterator cend() const {
        return my_container.cend();
    }

    typename Container::const_reverse_iterator crbegin() const {
        return my_container.crbegin();
    }

    typename Container::const_reverse_iterator crend() const {
        return my_container.crend();
    }

    typename Container::size_type size() const {
        return my_container.size();
    }

    bool empty() const {
        return my_container.empty();
    }
};

int main(int argc, const char * argv[]) {
    std::initializer_list<int> il = { 1, 2, 4, 5, 6 };

    std::list<int>   my_list   = il;
    std::set<int>    my_set    = il;
    std::vector<int> my_vector = il;

    ImmutableContainerView<std::list<int>>   my_immutable_list(my_list);
    ImmutableContainerView<std::set<int>>    my_immutable_set(my_set);
    ImmutableContainerView<std::vector<int>> my_immutable_vector(my_vector);

    // Iterators:
    std::ostream_iterator<int> out_it (std::cout, ", ");
    std::copy(my_immutable_list.cbegin(), my_immutable_list.cend(), out_it);
    std::cout << "\n";

    std::copy(my_immutable_set.cbegin(), my_immutable_set.cend(), out_it);
    std::cout << "\n";

    std::copy(my_immutable_vector.cbegin(), my_immutable_vector.cend(), out_it);
    std::cout << "\n";

    // Reversed iterators:
    std::copy(my_immutable_list.crbegin(), my_immutable_list.crend(), out_it);
    std::cout << "\n";

    std::copy(my_immutable_set.crbegin(), my_immutable_set.crend(), out_it);
    std::cout << "\n";

    std::copy(my_immutable_vector.crbegin(), my_immutable_vector.crend(), out_it);
    std::cout << "\n";

    // Size:
    std::cout << my_immutable_list.size() << "\n";
    std::cout << my_immutable_set.size() << "\n";
    std::cout << my_immutable_vector.size() << "\n";

    // Empty:
    std::cout << std::boolalpha;
    std::cout << my_immutable_list.empty() << "\n";
    std::cout << my_immutable_set.empty() << "\n";
    std::cout << my_immutable_vector.empty() << "\n";

    return 0;
}

I would like to hear comments on how to improve it. In particular, is it possible to do some metaprogramming trickery such that it can adapt to different containers; for example, it could provide operator[size_t] for std::vector, but find for std::set?

Your view isn't immutable, though immutability might be a property of the underlying object. It's a constant view, meaning the underlying object might change, but not from that view. The canonical way to get a constant view is by the way to use a constant reference, unless the view should erase some of the differences between underlying containers, like std::string_view does.

You are missing .begin(), .end(), .rbegin() and .rend().
Your view is constant, fine, but forcing everyone to explicitly say so for each function-call breaks interface conventions.
The missing functions are the common interface, the ones you provided just optional convenience-functions for calling manually which might not be provided even if possible, and certainly never used in generic code. Take a look at <iterator> and the free functions for accessing any generic range there.


I need help optimizing a function that returns all divisors This is my code:
export function all_divisors(num: number): number[] {
    return range(1, num+1).filter(i => num % i === 0).toArray();
}

the range function(docs) is part of the IterPlus library and is a pretty self-explanatory inclusive-exclusive range function, again, what I'm doing using the filter function is pretty self-explanatory, .toArray() converts IterPlus<number> to an array number[].
Anyway, I'd like some help optimizing this, as it is pretty slow when working with larger numbers(it took ~190ms for 3,000,000 and ~3ms for 30,000).
I don't care about code-golfing, or meant to code-golf in the first place, it was just convienient at the time.

Welcome to Code Review!
When factorising a number, you have the property that; if a number \$ a \$ is factor of \$ n \$, then \$ \frac{n}{a} \$ is also a factor of \$ n \$.
This immediately reduces your loop from \$ 1..n \$ by half to \$ 1..\frac{n}{2} \$.
Now, another optimisation to be done could be memoisation taking into account the property above. If the number \$ \frac{n}{a} \$ is a factor, then all factors of this number would also be factors for your original number \$ n \$.
Next step you can think about is checking only for prime factors, and then using the memoisation of factors from above.
There are several other factorisation algorithms to efficiently calculate. Take a look at some of such algorithms discussed in this article. (https://cp-algorithms.com/algebra/factorization.html)


JavaScript mixins - extending and super methods I've read a lot of stuff about mixins, inheritance and such, and in the end I came up with this solution for extending a class with multiple mixins. I haven't seen this anywhere else...

var Classes = {}; // I keep all classes inside this objects, so I can do new Classes[obj_name]();
Classes.asA = function () {
    var _init = this.init; // keep a copy of the previously declared method, if any
    this.init = function (a) {
        if (_init) _init.call(this, a); // call super method, if any
        this.a = a; // declare additional properties here
    }
    this.methodA = function () {
        console.log("a: "+this.a);
    }
}
Classes.asB = function () {
    var _init = this.init;
    this.init = function (a) {
        if (_init) _init.call(this, a);
        this.b = a+1;
    }
    this.methodB = function () {
        console.log("b: "+this.b);
    }
}
Classes.Obj = function () {
    var _init = this.init;
    this.init = function (a) {
        if (_init) _init.call(this, a);
        this.z = a-2;
    }
    this.methodZ = function () {
        console.log("z: "+this.z);
    }
}
Classes.asA.call(Classes.Obj.prototype); // extend Obj with asA
Classes.asB.call(Classes.Obj.prototype); // extend Obj with asB

var obj = new Classes.Obj();
obj.init(7); // will call in order asA.init, asB.init, Obj.init
obj.methodA(); // outputs "a: 7"
obj.methodB(); // outputs "b: 8"
obj.methodZ(); // outputs "z: 5"

Is this a good method? Do you see any problems with it?

The main things is that your system is much more verbose and harder to understand than simply hard-coding all the calls to superclass methods:

function A(a) {
    this.a = a;
}
A.prototype = {
    methodA: function () {
        console.log("a: "+this.a);
    }
};

function B(a) {
    this.b = a+1;
}
B.prototype = {
    methodB: function () {
        console.log("b: "+this.b);
    }
};

function Obj(a) {
    A.call(this, a);
    B.call(this, a);
    this.z = a-2;
}
// Using underscore.js extend() to mix in methods from A and B
Obj.prototype = _({
    methodZ: function () {
        console.log("z: "+this.z);
    }
}).extend(A.prototype, B.prototype);

var o = new Obj(7);
o.methodA();
o.methodB();
o.methodZ();

Instead you should have some sort of factory method that creates new classes for you, setting up the mixins behind the scenes. For example:

var Foo = createClass({
    mixins: [ClassA, ClassB],
    someMethod: function() { ... }
});

I suggest you study some existing libraries that implement their own JavaScript class systems. There are lots of nuances of the JS object model that you need to be aware of. I strongly suggest you don't use your own home-grown class-system for production, but instead adopt some already bettle-tested implementation. But writing you own is a good way to learn more deeply about JavaScript.


Deque implementation in Ruby class Element

  attr_accessor :datum,  :prev , :next

  def initialize(datum,next_element=nil, prev_element=nil)
    @datum = datum
    @next = next_element
    @prev = prev_element
  end

end

class Deque

  attr_reader :first, :last

  def push(datum)
    if @last.nil?
      @last = Element.new(datum)
      @first = @last
    elsif @last == @first
      @last = Element.new(datum,@first)
      @first.prev = @last
    else
      prev = @last
      @last = Element.new(datum,prev)
      prev.prev = @last
    end
  end

  def pop
    datum = @last.datum
    @last = @last.next if @last
    datum
  end

  def shift
    datum = @first.datum
    @first = @first.prev
    @first.next = nil  if @first
    datum
  end

  def unshift(datum)
    if @last.nil?
      @last = Element.new(datum)
      @first = @last
    elsif @last == @first
      @first = Element.new(datum,nil,@last)
      @last.next = @first
    else
      prev = @first
      @first = Element.new(datum,nil, prev)
    end
  end

end

I'm very confused by your naming - or perhaps you are. When pushing something onto a non-empty deque, you create a new Element and set its next element to be the preceding one. I.e. when examining the appended element, I'd see that its next is in fact the one before it. And vice-versa for unshift. It seems to work out (or I think it does) because you're at least consistent about the next-means-previous, and previous-means-next.
Or you've simply got push and unshift (and pop and shift backwards. Which is think is the case.
You could make good use of Struct for your Element class. And I'd make it a private inner class, since it's not meant for external use

class Deque
  # ...

  private

  Element = Struct.new(:datum, :prev, :next)
end

Saves you having to type the whole class declaration.
While pop and shift return the actual data, your first and last accessors return Element instances. I'd suggest that pop/push/shift/unshift/first/last all return data, while you use different methods/variables internally to get the Element-wrapped data. Say head and tail.
You don't need to check for nil as often as you do. Forgetting for at moment the prev/next confusion, your push method could be just

def push(datum)
  if @last.nil?
    @last = @first = Element.new(datum)
  else
    @last = Element.new(datum, @last)
  end
end

As an alternative to your current approach, you could put some more logic into Element to clean up the code in Deque. I.e. give Element methods like append and prepend which create a new Element instance that's properly linked to the receiver. It avoids you having to set things from the outside.

class Deque
  def initialize
    @head = nil
    @tail = nil
  end

  def push(datum)
    if @tail
      @tail = @tail.append(datum)
    else
      @head = @tail = Element.new(datum)
    end
  end

  def pop
    return nil unless @tail
    datum, @tail = @tail.datum, @tail.prev
    datum
  end

  def unshift(datum)
    if @head
      @head = @head.prepend(datum)
    else
      @head = @tail = Element.new(datum)
    end
  end

  def shift
    return nil unless @head
    datum, @head = @head.datum, @head.next
    datum
  end

  def first
    @head ? @head.datum : nil
  end

  def last
    @tail ? @tail.datum : nil
  end

  private

  Element = Struct.new(:datum, :prev, :next) do
    def prepend(datum)
      raise "Can't prepend here" if self.prev
      self.prev = self.class.new(datum, nil, self)
    end

    def append(datum)
      raise "Can't append here" if self.next
      self.next = self.class.new(datum, self, nil)
    end
  end
end

The exceptions being raised in prepend/append are there to catch cases where you try to append/prepend something "in the middle" if the deque. Doing so would only modify one side of the linkage, causing the list to branch and things to go weird.

Of course, the simplest deque in Ruby is the built-in Array.

deque_instance = []

And done.


Datetime in JavaScript Can please someone review and give me suggestions for improving this code?  I am very new to JavaScript.

I need to create a method in JavaScript which will take parameters as

DateRange (possible values as Today/This Week/This Month
BooleanFullDate (possible values as true/false)

Now, when the parameter value is Today, it should return

10/23/2013
10/23/2013

When This Week and BooleanFullDate are true, it should return

10/20/2013
10/26/2013

When This Week and BooleanFullDate are false, it should return

10/20/2013
10/23/2013

When This Month and BooleanFullDate are true, it should return

10/01/2013
10/31/2013

When This Month and BooleanFullDate are false, it should return

10/01/2013
10/23/2013

For which I have written my code here.

Lastly, can someone please suggest improvements for the code?

original question posted

EDIT:- Source code

function GetStartAndEnd(dateRange, bGetFullRange) {
    var dateObject = new Date();

    var dateobj = new Date()
    var month = dateobj.getMonth()+1
    var day = dateobj.getDate()
    var year = dateobj.getFullYear()

    var start = undefined;
    var end = undefined;
    if (dateRange.toLowerCase() == "today") {
        start = month + "/" + day + "/" + year;
        end = month + "/" + day + "/" + year;
    } else if (dateRange.toLowerCase() == "this week") {
        var curr = new Date;
        var firstDay = new Date(curr.setDate(curr.getDate() - curr.getDay()));
        var lastDay = new Date(curr.setDate(curr.getDate() - curr.getDay() + 6));

        var fmonth = firstDay.getMonth()+1;
        var fday = firstDay.getDate();
        var fyear = firstDay.getFullYear();
        start = fmonth + "/" + fday + "/" + fyear;

        var lmonth = lastDay.getMonth()+1;
        var lday = lastDay.getDate();
        var lyear = lastDay.getFullYear();
        end = lmonth + "/" + lday + "/" + lyear;

    } else if (dateRange.toLowerCase() == "this month" && bGetFullRange) {
        var date = new Date(),
            y = date.getFullYear(),
            m = date.getMonth();
        var firstDay = new Date(y, m, 1);
        var lastDay = new Date(y, m + 1, 0);

        var fmonth = firstDay.getMonth()+1;
        var fday = firstDay.getDate();
        var fyear = firstDay.getFullYear();
        start = fmonth + "/" + fday + "/" + fyear;

        var lmonth = lastDay.getMonth()+1;
        var lday = lastDay.getDate();
        var lyear = lastDay.getFullYear();
        end = lmonth + "/" + lday + "/" + lyear;

    } else if (dateRange.toLowerCase() == "this month" && !bGetFullRange) {
        var date = new Date(),
            day = date.getDate(),
            y = date.getFullYear(),
            m = date.getMonth();
        var firstDay = new Date(y, m, 1);
        var lastDay = new Date(y, m + 1, 0);

        var fmonth = firstDay.getMonth()+1;
        var fday = firstDay.getDate();
        var fyear = firstDay.getFullYear();
        start = fmonth + "/" + fday + "/" + fyear;

        end = m+1 + "/" + day + "/" + y;

    }
    console.log({
        "start": start,
            "end": end
    });

    return {
        "start": start,
            "end": end
    }
}
GetStartAndEnd("Today");
GetStartAndEnd("this week");
GetStartAndEnd("this month", true);
GetStartAndEnd("this month", false);

I see some issues with your code

There's a lot of repetition
Your return values should be actual Date objects, and perhaps handle the time component too. Formatting the date is outside the function's responsibilities. Who knows how the formatting or use of the start/end dates might change? But what won't change is that the function should return start and end, so stick to that.
Your arguments are a clue that something's not quite right: The 2nd argument only makes sense if the 1st argument is "this month". Why not respect the 2nd arg for weeks too?
A style thing, but by convention JS functions are lowerCamelCase unless they're constructors (i.e. classes). So Date is uppercase, as it's a constructor, but your function should be getStartAndEnd

To take a page from the ActiveSupport library for Ruby, which has excellent date/time helpers, it might be more beneficial to break everything up into the separate functions (and encapsulate them in an object to avoid polluting the global namespace).

For instance:

var DateHelper = {
  beginningOfDay: function (date) {
    var beginning = new Date(date);
    beginning.setHours(0, 0, 0, 0);
    return beginning;
  },

  endOfDay: function (date) {
    var end = new Date(date);
    end.setHours(23, 59, 59, 999);
    return end;
  },

  beginningOfWeek: function (date) {
    var beginning = DateHelper.beginningOfDay(date);
    beginning.setDate(date.getDate() - date.getDay());
    return beginning;
  },

  endOfWeek: function (date) {
    var end = DateHelper.endOfDay(date);
    end.setDate(date.getDate() - date.getDay() + 6);
    return end;
  },

  beginningOfMonth: function (date) {
    var beginning = DateHelper.beginningOfDay(date);
    beginning.setDate(1);
    return beginning;
  },

  endOfMonth: function (date) {
    var end = DateHelper.endOfDay(date);
    end.setMonth(date.getMonth() + 1, 0);
    return end;
  }

  //... more helper functions?
}

From this, you can build more complex functionality. For instance, your original function could now be written as:

function getStartAndEnd(rangeName, extendToEnd) {
  // At minimum, we'll want the range of the current date
  var range = {
    start: DateHelper.beginningOfDay(new Date),
    end:   DateHelper.endOfDay(new Date);
  };

  extendToEnd = extendToEnd || false; // default to false

  switch(rangeName.toLowerCase()) {
    case "this week":
      range.start = DateHelper.beginningOfWeek(range.start);
      if( extendToEnd ) {
        range.end = DateHelper.endOfWeek(range.end);
      }
      break;
    case "this month":
      range.start = DateHelper.beginningOfMonth(range.start);
      if( extendToEnd ) {
        range.end = DateHelper.endOfMonth(range.end);
      }
      break;
    default:
      // do nothing
      break;
  }
  return range;
}

That'll give you start/end date objects that you can format however you want (which, of course, would be a job for another tiny function).

But now that everything's broken up into separate, more focussed functions, you can mix and match to suit your needs. I'd avoid calling functions with string arguments that define what you want back. Probably better to simply have a thisWeek() function somewhere, or a thisMonth() function, and leave string interpretation at an even higher level.

Note, by the way, that time and date stuff is always tricky. For instance, all of these functions assume you're talking about the user's local time zone. Depending on your context, that might cause issues. Also, where I live the beginning of a week would be a Monday, not a Sunday. So beware of such things.