texts: Get column of a matrix python with index operator

texts:
How can I refactor this code to generalize the argument parsing? I feel like this code can be better but I can't find a way. The usage syntax of the index operator is similar to the NumPy indexing syntax.

    def __getitem__(self, arg):
    """
    [] operator to index elements in the matrix
    Usage:
    >> mat[0] returns first row
    >> mat[3, :] return the 4th row
    >> mat[:, 7] return the 8th column
    >> mat[0, 0] returns first element
    """
    if isinstance(arg, int):
        return self.matrix[arg]
    elif isinstance(arg, tuple):
        if isinstance(arg[0], int) and isinstance(arg[1], int):
            y, x = arg
            return self.matrix[x][y]
        elif isinstance(arg[0], slice) and isinstance(arg[1], int):
            return self.get_column(arg[1])
        elif isinstance(arg[0], int) and isinstance(arg[1], slice):
            return self.get_column(arg[1])
    else :
        raise TypeError('Invalid indexing arguments type', arg)

Also, how can I make a setitem function that uses the [] operator to set columns without rewriting the getitem function inside it? Here is my current implementation without the possibility of setting a column.

    def __setitem__(self, arg, value):
    if isinstance(value, Fraction):
        self[arg] = value
    elif isinstance(value, list) and all(isinstance(elem, Fraction) for elem in value):
        self[arg] = value
    else:
        raise TypeError('Invalid value type', value)


texts:
As I understand creating lots of resource managers in C# may be a bad idea so I thought that the best thing to do would be to create a singleton for this.

However, I'm not 100% if this is a good idea, or if this is a good way to implement it.

The main thing about the implementation I am unsure about is making the "Instance" private and creating number of static functions to expose the functionality. This means I can call Local.GetString instead of Local.Instance.GetString which is less clunky. I have not seen any singleton implementation which does this so I wonder if there is some problem with it.

I am also using locking but I don't see how to get around that so that is probably fine.

public class Locale
{
    // using System.Lazy<T> -- see http://msdn.microsoft.com/en-us/library/dd642331.aspx
    static readonly Lazy<Locale> lazy = new Lazy<Locale>(() => new Locale(), true);
    static readonly object _locker = new object();

    Dictionary<Type, ResourceManager> _managers;

    public Locale()
    {
        _managers = new Dictionary<Type, ResourceManager>();
    }

    static Locale Instance { get { return lazy.Value; } }

    public static ResourceManager GetManager(Type resourceType)
    {
        return Instance.GetResourceManager(resourceType);
    }

    public static string GetString(Type resourceType, string name)
    {
        var manager = Instance.GetResourceManager(resourceType);
        return manager.GetString(name);
    }

    public static string GetString(Type resourceType, string name, CultureInfo culture)
    {
        var manager = Instance.GetResourceManager(resourceType);
        return manager.GetString(name, culture);
    }

    public static object GetObject(Type resourceType, string name)
    {
        var manager = Instance.GetResourceManager(resourceType);
        return manager.GetObject(name);
    }

    public static object GetObject(Type resourceType, string name, CultureInfo culture)
    {
        var manager = Instance.GetResourceManager(resourceType);
        return manager.GetObject(name, culture);
    }

    ResourceManager GetResourceManager(Type resourceType)
    {
        lock (_locker)
        {
            ResourceManager manager;
            if (!_managers.TryGetValue(resourceType, out manager))
            {
                manager = new ResourceManager(resourceType);
                _managers.Add(resourceType, manager);
            }
            return manager;
        }
    }
}

I am using it like so

public class LocalizedDescriptionAttribute : DescriptionAttribute
{
    readonly Type _resourceType;
    readonly string _resourceName;
    readonly CultureInfo _culture;

    public LocalizedDescriptionAttribute(Type resourceType, string resourceName)
        : this(resourceType, resourceName, null)
    {
    }

    public LocalizedDescriptionAttribute(Type resourceType, string resourceName, CultureInfo cultureInfo)
        : base()
    {
        _resourceType = resourceType;
        _resourceName = resourceName;
        _culture = cultureInfo;
    }

    public override string Description
    {
        get
        {
            if (_culture == null)
                return Locale.GetString(_resourceType, _resourceName);
            return
                Locale.GetString(_resourceType, _resourceName, _culture);
        }
    }
}

I have of course read Jon Skeet's article on singletons.


texts: Determine if a string has all unique characters

texts:
I'm practicing algorithms (for future interviews) while learning about Big O notation and was wondering if there's a faster or more optimal way of writing an algorithm to see if a string has all unique characters (assuming you can't use additional data structures).

- (BOOL)containsUniqueCharacters:(NSString *)string {

    //Make sure that it's case insensitve
    string = [string uppercaseString];

    //Create a buffer for our string
    NSUInteger length = [string length];
    unichar buffer[length];
    [string getCharacters:buffer range:NSMakeRange(0, length)];

    //Iterate through each of our characters
    for (int i = 0; i < length; i++) {

        //Iterate through every other character and compare it with our current character
        for (int n = 0; n < length; n++) {

            //Compare current character with every other character
            if (buffer[i] == buffer[n] && i != n) {
                return NO;
            }
        }
    }

    return YES;
}

If I'm correct, is the time complexity for this \$O(n^2)\$, and the space complexity \$O(1)\$?


texts: Ruby script to send PragPub magazine to Kindle

texts:
I wrote a little ruby script to download issues of PragPub magazine and send them to my Kindle via email. I would love to get some feedback on it.

One part, specifically, where I feel like there might be a better way is where it downloads the file and writes to disk. It used to do this:

open(filepath, 'wb') do |file|
  file << open(url).read
end

But this was causing a problem when the issue was not available yet. The http request would fail and there would be an empty file left on disk. So I changed it to this:

  begin
    content = open(url).read
  rescue OpenURI::HTTPError => e
    abort "Unable to download #{filename}: #{e.message}"
  end
  open(filepath, 'wb') do |file|
    file << content
  end

This works better, but feels a little clunky.

Also, is it common/acceptable in Ruby-land to just write a procedural style script like this, or should it be organized into class(es) and methods?

pragpub2kindle.rb

#!/usr/bin/env ruby

require 'open-uri'
require 'mail'
require 'optparse'

options = {}
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: pragpub2kindle.rb [options] [yyyy-mm]"
  options[:mailto] = nil
  opts.on('-t', '--mailto EMAIL', 'Send attachment to email address') do |email|
    options[:mailto] = email
  end
  options[:mailfrom] = nil
  opts.on('-f', '--mailfrom EMAIL', 'Send attachment from email address') do |email|
    options[:mailfrom] = email
  end
  options[:dir] = nil
  opts.on('-d', '--dir DIR', 'Directory to save files') do |dir|
    options[:dir] = dir
  end
  opts.on('-h', '--help', 'Display this screen') do
    puts opts
    exit
  end
end

optparse.parse!

mandatory = [:mailto, :mailfrom]
missing = mandatory.select{ |param| options[param].nil? }
if not missing.empty?
  puts "Missing options: #{missing.join(', ')}"
  puts optparse
  exit
end

dir = options[:dir] || Dir.getwd
if (!(File.directory?(dir) && File.writable?(dir)))
  puts "Directory not valid or not writable: #{dir}"
  puts optparse
  exit
end

if ARGV.length == 1
  year_month = ARGV.first
  if !year_month.match(/\d{4}-\d{2}/)
    puts "Invalid date format: #{year_month}"
    puts optparse
    exit
  end
else
  year = Time.now.strftime("%Y")
  month = Time.now.strftime("%m")
  year_month = "#{year}-#{month}"
end

filename = "pragpub-#{year_month}.mobi"
year = year_month[0..3]

url = "http://magazines.pragprog.com/#{year}/#{filename}"
filepath = File.join(dir, filename)

if File.exists?(filepath)
  puts "#{filename} already exists"
else
  puts "Downloading #{filename}..."
  begin
    content = open(url).read
  rescue OpenURI::HTTPError => e
    abort "Unable to download #{filename}: #{e.message}"
  end
  open(filepath, 'wb') do |file|
    file << content
  end
  mail_to = options[:mailto]
  mail_from =  options[:mailfrom]
  puts "Sending #{filename} to #{mail_to}..."
  mail = Mail.new
  mail.to = mail_to
  mail.from = mail_from
  mail.subject = filename
  mail.attachments[filename] = {
    :mime_type => 'application/x-mobipocket-ebook',
    :content => File.read(filepath)
  }
  mail.deliver!
end


texts:
I've been learning Java for about 3 weeks now, and I was hoping someone could check over my code for me, and let me know how to improve.

I am aware that the maths class could be removed (I could've typed answer = inputA * inputB etc. within the switch statement) but this is just because I wanted to practice using multiple classes.

import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    Maths Maths = new Maths();

    double answer = 0;
    double inputA, inputB;
    char operator;
    boolean done = false;

     while (done == false) {
        System.out.print("Please enter your sum: ");

        inputA = input.nextDouble();
        operator = input.next().charAt(0);
        inputB = input.nextDouble();

        switch (operator) {
            case '+': answer = Maths.add(inputA, inputB);
                      break;
            case '-': answer = Maths.subtract(inputA, inputB);
                      break;
            case '*': answer = Maths.multiply(inputA, inputB);
                      break;
            case '/': answer = Maths.divide(inputA, inputB);
                      break;
            case '^': answer = Maths.power(inputA, inputB);
                      break;
        }

            System.out.println(answer);
    }

    input.close();

  }

}

And my second class...

public class Maths {

    double add(double a, double b) {
        double answer = a+b;
        return answer;
    }

    double subtract(double a, double b) {
        double answer = a-b;
        return answer;
    }

    double multiply(double a, double b) {
        double answer = a*b;
        return answer;
    }

    double divide(double a, double b) {
        double answer = a/b;
        return answer;
    }

    double power(double a, double b){
        double answer =a;

        for (int x=2; x<=b; x++){
            answer *= a;
        }

        return answer;
    }

}


texts: Given a shape, return all triangles that can be formed

texts:
Given a shape, get all triangles that can be possible by connecting the points.

  Example: given 3 points, only 1 triangle is possible, but given a pentagon, 10 are possible.

Also the combination formula is \$\dfrac{n!}{r!(n-r)!}\$.  Does it mean \$O(n!)\$ is the complexity?

Looking for:

Code review optimization and best practices.
Verifying complexity:

Time:  \$O\left(\dfrac{n!}{r!  (n-r)!}\right)\$ - which I guess is the same as \$O(n!)\$.

Space:  \$O\left(\dfrac{n!}{r! (n-r)!} \cdot r\right)\$ - space occupied by the list to be returned.

public final class GetTriangles {

    private GetTriangles() {}

    /**
     * Returns the list of all the triangles possible, given the input shape.
     * If the less than three points are returned it causes illegal argument exception
     */
    public static List<int[]> combinate (int n) {
        if (n < 3) throw new IllegalArgumentException("The input shape has less than 3 points:  " + n);
        final List<int[]> list = new ArrayList<int[]>();
        for (int i = 1; i < n - 1; i++) {
            compute(i, new int[3], 0, n, list);
        }
        return list;
    }

    private static void compute(int startFrom, int[] a, int arrPosition, int n, List<int[]> list) {
        if (arrPosition == a.length - 1) {
            a[arrPosition] = startFrom;
            list.add(Arrays.copyOf(a, a.length));
            return;
        }

        a[arrPosition] = startFrom;

        for (int i = startFrom + 1; i <= n; i++) {
            compute(i, a, arrPosition + 1, n, list);
        }
    }

    public static void main(String[] args) {
       final List<int[]> list = combinate(5);

       int[] a1  = {1, 2, 3};
       int[] a2  = {1, 2, 4};
       int[] a3  = {1, 2, 5};
       int[] a4  = {1, 3, 4};
       int[] a5  = {1, 3, 5};
       int[] a6  = {1, 4, 5};
       int[] a7  = {2, 3, 4};
       int[] a8  = {2, 3, 5};
       int[] a9  = {2, 4, 5};
       int[] a10 = {3, 4, 5};

       final List<int[]> list1 = Arrays.asList(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);

       for (int i = 0; i < list.size(); i++) {
           assertArrayEquals(list.get(i), list1.get(i));
       }
    }
}


texts: Reading a gzipped file with JSON data for thousands of users

texts:
I'm a newbie in Python.

I need to read a GZ file contains thousands of users.
But I think my code is not optimized in this case. Could anyone can help me? What should I do to improve performance? Or is it standard?

if os.path.isfile("file.gz"):
    with gzip.GzipFile("file.gz", 'r') as fin:
        for line in fin:
            if get_new_user is True:
                if datetime.strptime(json.loads(line).get('UpdatedAt'), '%Y-%m-%dT%H:%M:%S.%fZ').date() == (datetime.today()-timedelta(1)).date():
                    users.append(json.loads(line))
            else:
                users.append(json.loads(line))
    os.remove("file.gz")
    return users


texts:
Is there a very short way to do this same thing in a pure LINQ based way?  It seems like I should not have to do all of this below to get to the OrderBy.

Dictionary<DataColumn, DateTime> columns = new Dictionary<DataColumn, DateTime>();
int startIndex;
int endIndex;
for (int i = 0; i < table.Columns.Count; ++i)
{
    // these columns need to be sorted
    startIndex = table.Columns[i].Caption.IndexOf('(');
    endIndex = table.Columns[i].Caption.IndexOf(')');
    if (startIndex > 0 && endIndex > 0)
    {
        // create a standard date
        string monthYear = table.Columns[i].Caption.Substring(
            startIndex + 1, endIndex - startIndex - 1);
        columns.Add(
            table.Columns[i],
            DateTime.Parse(monthYear.Replace("/", "/01/")).Date);
    }
    else
    {
        // all other columns should be sorted first
        columns.Add(table.Columns[i], DateTime.MinValue);
    }
}

// perform the LINQ order by
columns = columns.OrderBy(o => o.Value).ToDictionary(o => o.Key, o => o.Value);

// order the original table uses the dictionary
for (int i = 0; i < columns.Count; ++i)
{
    table.Columns[columns.Keys.ElementAt(i).Caption].SetOrdinal(i);
}


texts:
The below code feels ugly, how can I make it better? (The part i don't like is the ||=. I also don't know if I like the resulting data structure. (An array of hashes)

def survey_results
    @survey_results = []
    unless params[:step_survey_id].blank?
      SurveyResult.find_by_step_survey_id(params[:step_survey_id]).step_survey.step_survey_questions.each do |survey_question|
          survey_result = {:question => survey_question.value}
          answers = {}
          survey_question.survey_result_answers.each do |survey_result_answer|
            #Setup initial answer hash with key as the response, only used when needed
            answers[survey_result_answer.response] ||= 0
            answers[survey_result_answer.response] += 1
        end
        survey_result[:answers] = answers
        @survey_results.push(survey_result)
      end
    end
  end


texts: Automate the Boring Stuff – Chess Dictionary Validator – Optimal Solution

texts:
Brief introduction: so the point of the question is that the author doesn't really talk about good or bad code quality and I really wanted some feedback to have a grasp of how the code for others to read should look like. I mean, for the very first solution of the task I would check different parameters manually just to finish it and the function looked really bulky, so I took some time to make it neat.
Task: the dictionary value represent a chess board, for example {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'}. Write a function named that takes a dictionary argument and returns True or False depending on if the board is valid.
A valid board will have exactly one black king and exactly one white king. Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'. This function should detect when a bug has resulted in an improper chess board.
My solution:
def chessboardCheck(board):

    piecesDict={'pawn':8,'knight':2,'bishop':2,'rook':2,'queen':1,'king':1} #to count pieces on the board

    if list(board.values()).count('wking')!=1 or list(board.values()).count('bking')!=1: #kings check
        print('The board is invalid: kings requirement not met.')
        return False
    for piece in board.values():
        if piece[0] not in 'wb': #piece color
            print('The board is invalid: improper color reference.')
            return False
        elif piece[1:] not in piecesDict.keys(): #piece type
            print('The board is invalid: improper piece reference.')
            return False
        elif list(board.values()).count(piece) > piecesDict.get(piece[1:]): #pieces count
            print('The board is invalid: improper pieces count.')
            return False
    for cell in board: #axis correctness
        if cell[0] not in '12345678' or cell[1] not in 'abcdefgh':
            print('The board is invalid: improper cell reference.')
            return False

    print('All checks are clear: the board is valid.')
    return True

This is the least lines I could come up with, but if there are more shortcuts to take, please do not hesitate to point! Also I would like to hear opinions on introducing variables: I tried to avoid them wherever I knew how, but maybe it's not always the way to go? Thanks!


texts: Passing connection for multiple classes/methods

texts:
I have made a connection method which returns TCPMasterConnection.

public Class Connect{

String ipAddress;
int port;
TCPMasterConnection tcpCon;

    public TCPMasterConnection OverTCP(String ipAddress, int port)
    {
      this.ipAddress = ipAddress;
      this.port = port;

      TCPMasterConnection tcpConnection = null;

    try {
        tcpConnection = new TCPMasterConnection(InetAddress.getByName(ipAddress));
    } catch (Exception e) {
        e.getMessage();
    }
    tcpConnection.setPort(port);
    try {
        tcpConnection.connect();
    } catch (Exception e) {
        e.printStackTrace();
    }
      return tcpConnection;
    }

    public void setTcpCon(TCPMasterConnection tcpCon) {
       this.tcpCon = tcpCon;
    }
}

And I have multiple methods which uses TCPMasterConnection:

public Class Write extends Connect{

public int[] OverTCP_16Bit_Int(int unitID, int startAddress, int dataToWrite int count) throws Exception
{
   this.unitID = unitID;
   this.startAddress = startAddress;
   this.dataToWrite = dataToWrite;
   this.count = count;

   SimpleRegister reg = new SimpleRegister(dataToWrite);
   Register[] registers = new Register[count];

   for(int i = 0; i<registers.length; i++)
   {
       registers[i] = reg;
   }

   WriteMultipleRegistersRequest write_mreq = new WriteMultipleRegistersRequest();

   write_mreq.setReference(startAddress);
   write_mreq.setUnitID(unitID);
   write_mreq.setRegisters(registers);

   ModbusTCPTransaction transaction = new ModbusTCPTransaction(tcpCon);
   transaction.setRequest(write_mreq);
   transaction.execute();
   return transaction.getResponse();
  }
   public void setTcpCon(TCPMasterConnection tcpCon) {
     this.tcpCon = tcpCon;
   }
 }
}

public Class Read extends Connect{

public int[] OverTCP_16Bit_Int(int unitID, int startAddress, int count) throws Exception
{

this.unitID = unitID;
   this.startAddress = startAddress;
   this.count = count;
   this.x = new int [count];
   this.Stringas = new String[count];

   ReadMultipleRegistersRequest read_mreq = new ReadMultipleRegistersRequest();

   read_mreq.setUnitID(unitID);
   read_mreq.setReference(startAddress);
   read_mreq.setWordCount(count);

   ModbusTCPTransaction transaction = new ModbusTCPTransaction(tcpCon);
   transaction.setRequest(read_mreq);
   transaction.execute();
   ReadMultipleRegistersResponse read_mres = (ReadMultipleRegistersResponse) transaction.getResponse();

   for (int n = 0; n < read_mres.getWordCount(); n++)
   {
       x[n] = read_mres.getRegisterValue(n);
   }
  return x
  }
   public void setTcpCon(TCPMasterConnection tcpCon) {
      this.tcpCon = tcpCon;
 }
 }
}

So in main I do this:

public static void main(String[] args) throws Exception {

  String ip = "127.0.0.1";
  int port = 502;

  Connect connect = new Connect();

  Read read = new Read();
  Write write= new Write();

  TCPMasterConnection connectTCP = null;

  Connect[] objectList = new Connect[2];

  objectList[0] = read;
  objectList[1] = write;

  connectTCP = connect.OverTCP(ipAddress, port);

  for(Connect x: objectList){
      x.setTcpCon(connectTCP);
  }
}

Is this a proper way to do this?

So my point is to make a proper way to transfer connection through multiple classes for each method they have. So I don't have to do something like this every time user wants to use different function.

Connection connect = new Connect
TCPMasterConnection connectTCP = connect.OverTCP("127.0.0.1", 502);
read.setTcpCon(connectTCP);
read.DoStuff();

write.setTcpCon(connectTCP);
write.DoStuff();

I made in main class so that it transfers connection but I don't know if it is a proper way and overall I want to improve my code.


texts:
I've created working  setters/getters for an application, that will use a few different classes. This classes will use one class, that will store all data. I know, when I will use a standard constructor of container class, I'll get tons on nulls, due to different instance of container class.

I've created container class within a singleton, that works, but I wanted to ask if anything could be done better, or if this code follow the best practice.

public class Container {

    private String appName = null;
    private String appOwner = null;

    private Container() {
        System.out.println("Start");
    }

    private static class SingletonHolder {
        private final static Container INSTANCE = new Container();
    }

    public static Container getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public String getAppOwner() {
        return appOwner;
    }

    public void setAppOwner(String appOwner) {
        this.appOwner = appOwner;
    }
}

Sample class, that will use this container:

public class SecondClass {
     Container ctn = Container.getInstance();
}

Right now, when I use in main class:

ctn.setAppOwner(owner);

I get a proper value in any other classes, when I call this:

Container ctn = Container.getInstance();
ctn.getAppOwner();

Is that a good approach?


texts: More Revealing Module Patter in Javascript

texts:
It is known a Revealing Module Pattern in javascript, and here it is a little example.

var Module = (function(){
     var a = 3,
         init = function(a_user){ a = a_user; },
         update = function(){},
         get = function(){return a},
         set = function(a_user){ a = a_user; };

     return {
         init : init,
         update : update,
         get : get,
         set : set
     }
})();

It's good for lots of uses. But I modified it in 2 steps, and some people tell me that I've overloaded it, and my new variations take lots of memory. So I ask, if my variations are really bad, and I shouldn't use it?

Variation 1

I like to separate public and private logic. It's useful, because I separate methods, which I allow to users of my module (in the client code).

For example:

var MyModule = (function(){
     var
         pr = {}, // Private Scope
         PU = {}; // Public Scope

     pr.fetch = function(){}; // fetching data
     pr.build = function(){}; // building DOM of module
     pr.show  = function(){}; // showing our object
     pr.hide  = function(){}; // hiding our object
     //... Other private methods

     // Public methods
     PU.init = function(){
         pr.fetch().build().show();
         return PU; // for making chains
     }
     PU.update = function(){};
     //... other Public methods

     return PU;
})();

I know, that in usual Revealing Module Pattern methods that are in last return are public, but other - private. But when you calling private method there, you just type it name, and it's unknown if it is a private method of this module, or it's a global function, that's why I have separated object - pr and PU.

Variation 2:

Sometimes I had need to insert some of modules twice on a page (or maybe more). So, I understand that it's not a module anymore, because Module can't have instances, Module is just a bundle of related functions. But I've decided to make a Module that can generate instances of itself.
I've used my code from Variation 1 with a little fix:

var MyModule = function(){
     var
         pr = {}, // Private Scope
         PU = {}; // Public Scope

     pr.fetch = function(){}; // fetching data
     pr.build = function(){}; // building DOM of module
     pr.show  = function(){}; // showing our object
     pr.hide  = function(){}; // hiding our object
     //... Other private methods

     // Public methods
     PU.init = function(){
         pr.fetch().build().show();
         return PU; // for making chains
     }

     PU.update = function(){};
     //... other Public methods

     // Constructor
     PU.__construct = function() {
         // constructor code
         return PU;
     }

     return PU.__construct.apply(this, arguments);
};

// Usage:
var m1 = new MyModule(/* some options*/);
m1.init();

var m2 = new MyModule(/* other options */);
m2.init();

Are these variation really bad? Should I avoid them, as some people have said to me some time earlier...


texts:
This is an alternative parser based on the specifications from this question.  Briefly stated, the input file is a text file which has at least 33 fields separated by semicolons.
If the fourth field begins with either a T or an E, the line is valid and a subset of it written to the output file.  Specifically, fields as numbered from \$0\$, should be output in this order: \$ \{0, 2, 3, 4, 5, 6, 10, 9, 11, 7, 32\}\$, each separated by a comma.  All other fields are discarded.
One of the other answers there suggested that one could use a Flex-based parser instead. My own efforts were not faster, but I'm hoping that someone can review this and show me how to extract more speed from this version.
lexer.l
%{
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <experimental/iterator>
#include <iterator>
#undef YY_DECL
#define YY_DECL int FileLexer::yylex()

class FileLexer : public yyFlexLexer {
public:
    FileLexer(std::istream& in, std::ostream& out) :
        yyFlexLexer{&in, &out},
        out{out}
    {}
    using FlexLexer::yylex;
    /// the yylex function is automatically created by Flex.
    virtual int yylex();
private:
    /// pointer to the current value
    std::vector<std::string> vec;
    std::ostream& out;
    unsigned fieldcount{0};
    bool valid{true};
};

%}
%option warn nodefault batch noyywrap c++
%option yyclass="FileLexer"

FIELD  [^;\n]*
DELIM   ;
%%

{DELIM} { }
\n      {
            if (valid && fieldcount >= 33) {
                std::copy(vec.begin(), vec.end(), std::experimental::make_ostream_joiner(out, ","));
                out << '\n';
            }
            vec.clear();
            fieldcount = 0;
            valid = true;
            return 1;
        }
{FIELD} {
            if (valid) {
                switch (fieldcount++) {
                    case 0:
                    case 1:
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                    case 9:
                    case 32:
                        vec.push_back(yytext);
                        break;
                    case 3:
                        if (yytext[0] == 'E' || yytext[0] == 'T') {
                            vec.push_back(yytext);
                            valid = true;
                        } else {
                            valid = false;
                        }
                        break;
                    case 10:
                        {
                            auto n{vec.size()};
                            vec.push_back(yytext);
                            std::iter_swap(vec.begin()+n, vec.begin()+n-2);
                        }
                        break;
                    case 11:
                        {
                            auto n{vec.size()};
                            vec.push_back(yytext);
                            std::iter_swap(vec.begin()+n, vec.begin()+n-1);
                        }
                        break;

                }
            }
        }
%%
int main(int argc, char *argv[]) {
    if (argc >= 3) {
        std::ifstream in{argv[1]};
        std::ofstream out{argv[2]};
        FileLexer lexer{in, out};
        while (lexer.yylex() != 0)
        {}
    }
}

Compile with:
flex -o parsefile.cpp lexer.l
g++ -O2 -std=gnu++17 parsefile.cpp -o parsefile

This works, but it is slow (2.165 s) on my machine, with the same million-line input file as mentioned in my answer to the other question.
I tried it a few different ways, but I was unable to get a version that was faster than the PHP code in the other question.  The switch statement logic is arguably a bit overly clever and stores only the needed fields in the desired order, but the speed was about the same as the straightforward implementation.
If it matters, I'm using gcc version 10.1 and flex 2.6.4 on a 64-bit Linux machine.


texts: Ternary gate handling - more succinct way then a bunch of if statements

texts:
I have classes representing gates (OR, XOR, AND etc) with the following method that is called whenever a property changes.

Here is the XORGate code:

public void computeOutput() {
        if (this.input1 != null && this.input0 != null) {
            if (this.input0.getValue() || this.input1.getValue()) {
                if (this.input0.getValue() && this.input1.getValue()) {
                    this.output.setValue(false);
                }
                else {
                    this.output.setValue(true);
                }

            } else {
                this.output.setValue(false);
            }
        }
        else {
            this.output.Value = false;
        }

    }

It's horrible, but I can't think of a nicer way. It works as follows:

If any of the inputs are null, treat the output as false. If any of the inputs are true BUT not all of the outputs are true (i.e just one is true), set the output to true. If BOTH input terminals are true, output is false. And finally, if none of the input is true, output is false.

Very basic stuff.


texts: VBA function that returns color RBG code of a referenced cell

texts:
I have this function I'm building to return the RBG code of a cell I input.  The code "works" but something funny is going on.  If I write multiple functions each referencing different cells, then all the functions simultaneously show the last cell I run through the function.

I'm probably doing something trivial here, but I'm also new to VBA.

 Public Function ColorCode(Reference As Range) As Variant

' Function to return RGB code of a single cell when referenced

Dim RGBColor As Long

Dim Red As Long, Green As Long, Blue As Long

Range(Reference.Address).Activate
RGBColor = Selection.Interior.Color

    Red = &HFF& And RGBColor

    Green = (&HFF00& And RGBColor) \ 256

    Blue = (&HFF0000 And RGBColor) \ 65536

ColorCode = Red & "/" & Green & "/" & Blue

End Function


texts: How can I prettify blocks with more than 2 of each block?

texts:
Actually, I just have no ideas.

How can I make breaklines to make it more readable?

Can anyone suggest ways on improving this?

module TestingDataLoad
  def get_files_from(search_target)

    Dir[search_target].each do | d |
      testing_files={}
      if File.directory? d
        Dir.glob("#{d}/*json") do |file|
          if File.basename(file,".json") =~ /(\w+)(_\d+-\d+)/
            event_type = $1.to_sym
            if testing_files.has_key? event_type
              testing_files[event_type] << file
            else
              testing_files[event_type] = [file]
            end
          elsif File.basename(file,".json") =~ /(\w+)/
            event_type = $1.to_sym
            testing_files[event_type] = [file]
          end
        end
      end

      return testing_files
    end
  end


texts:
How can I make this better?

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

#define ARP_CACHE       "/proc/net/arp"
#define ARP_BUFFER_LEN  1024
#define ARP_DELIM       " "

int readLine(int Fd, char *Buffer)
{
    if (Fd < 0)
    {
        return -1;
    }

    char ch;
    size_t Read = 0;

    while (read(Fd, (Buffer + Read), 1))
    {
        ch = Buffer[Read];
        if (ch == '\n')
        {
            break;
        }
        Read++;
    }

    if (Read)
    {
        Buffer[Read] = 0;
        return 0;
    }

    return -1;

}

char * getField(char * Line_Arg, int Field)
{
    char * Line = malloc(strlen(Line_Arg)), *ptr;
    memcpy(Line, Line_Arg, strlen(Line_Arg));
    ptr = Line;

    char * s;
    s = strtok(Line, ARP_DELIM);
    while (Field && s)
    {
        s = strtok(NULL, ARP_DELIM);
        Field--;
    };

    char * ret;
    if (s)
    {
        ret = (char*)malloc(strlen(s) + 1);
        memset(ret, 0, strlen(s) + 1);
        memcpy(ret, s, strlen(s));
    }
    free(ptr);

    return s ? ret : NULL;
}

int main()
{
    int Fd = open(ARP_CACHE, O_RDONLY);

    if (Fd < 0)
    {
        fprintf(stdout, "Arp Cache: Failed to open file \"%s\"\n", ARP_CACHE);
        return 1;
    }

    char Buffer[ARP_BUFFER_LEN];

    /* Ignore first line */
    int Ret = readLine(Fd, &Buffer[0]);

    Ret = readLine(Fd, &Buffer[0]);
    int count = 0;

    while (Ret == 0)
    {
        char * Line;
        Line = &Buffer[0];

        /* Get Ip, Mac, Interface */
        char * Ip       = getField(Line, 0);
        char * Mac      = getField(Line, 3);
        char * IfaceStr = getField(Line, 5);

        fprintf(stdout, "%03d: Mac Address of [%s] on [%s] is \"%s\"\n",
                ++count, Ip, IfaceStr, Mac);

        free(Ip);
        free(Mac);
        free(IfaceStr);

        Ret = readLine(Fd, &Buffer[0]);
    }
    close(Fd);
    return Ret;
}


texts: Finding shortest sequences of integers whose product is larger than n

texts:
Here is the task:

For an integer n, return a list of the k length integers sequences whose product is larger than n but as close to n as possible (i.e. smallest larger than n number), and whose largest member is the smallest possible. For each sequence length k, there is one such sequence, and we want to have the sequences for all possible k's. 1 doesn't count as a valid member. The sequences are ordered from largest to smallest member.

For example, for n=100, the longest non-trivial sequence is with k=7 and is [2, 2, 2, 2, 2, 2, 2]. sequences with k>7 will be just an extension to this sequence (i.e. additional 2's appended to this list) and thus we will disregard them as trivial and will not care for them.

For k=2 the sequence of choice for n=100 is [10, 10]. It is better than [12, 9] since the largest member is smaller. If the largest member is the same in two sequences of the same length then the decision moves to the next largest, etc.

The shortest sequence for n=100 is obviously the trivial [100].

And the full list for n=100 is:

In: productsequences(100)

out:
[[2, 2, 2, 2, 2, 2, 2],
 [3, 3, 2, 2, 2, 2],
 [3, 3, 3, 2, 2],
 [4, 3, 3, 3],
 [5, 5, 4],
 [10, 10],
 [100]]

This is the recursive code I've came up with. It seems to be working well. However for large numbers it becomes slow.

How can I improve it? Can the same be achieved faster for large numbers?

def productsequences(n, maxn=None):
    """
    Returns a list of valid integer sequnces of different lengths whose
    product is the smallest larger than n.
    """
    if n <= 1:
        return []
    if maxn == None:
        maxn = n
    seqlist= []
    for i in range(2, min(maxn, n) + 1):
        if n % i:
            r = productsequences((n // i) + 1, i)
        else:
            r = productsequences(n // i, i)
        if len(r) == 0:
            seqlist.append([i])
        else:
            for k in r:
                seqlist.append([i] + k)
    nontrivial = []
    lim = n # Just a large enough initial value. needs to be larger than
    # log(n, 2) + 1
    for k in seqlist: # keep just one sequnce of every length
        if len(k) < lim:
            nontrivial.append(k)
            lim = len(k)
    return nontrivial


texts: compare two logic commented one to my logic java

texts:
I'm trying to review this block of code to make sure logic is fine. The first version that I commented will create duplicated order 'my college developer' but I fixed it but "really not sure" I want to make sure my fix it exactly same as commented code

the old logic "this code include duplicated"

public void setOrderedProduct(String prodName, int eoq) {
    String productCd = getProdCd(prodName);
    // Here only one time one product
    boolean prodPresent = false;
    int indexOfProd = 0;
    int sizeOfItems = items.size();
    for (int i = 0; i < sizeOfItems; i++) {
        PurchaseOrderDTO itemVal = items.get(i);
        if (itemVal.getProdcd().equalsIgnoreCase(productCd)) {
            prodPresent = true;
            indexOfProd = i;
            break;
        }
    }
    itemData.setProdname(prodName);
    itemData.setQty(eoq);
    itemData.setProdcd(productCd);
    double costPrice = ProductView.getProductCost(vendorno, productCd);
    itemData.setPrice(costPrice);
    double extPrice = ProductView.getProductMSRP(vendorno, productCd);
    itemData.setExt(extPrice);

    if (!prodPresent) {
        if (eoq != 0) {
            items.add(itemData);
            // Now add the details to the database
            ProductView.addPurchaseDetails(itemData, vendorno);
        }
    } else {
        if (eoq > 0) {
            items.set(indexOfProd, itemData);
            ProductView.updatePurchaseDetails(itemData, vendorno);
        } else {
            items.remove(indexOfProd);
            ProductView.removePurchaseDetails(itemData, vendorno);
        }
    }
    if (items.size() > 0)
        calculateTotal();
}

my fixed logic

public void setOrderedProduct(String prodName, int eoq) {
    boolean dataPresent = false;
    if (orderedProdNameList.contains((Object) prodName)) {
        dataPresent = true;
    }
    if (dataPresent) {
        int indexOfProdName = orderedProdNameList.indexOf((Object) prodName);
        String productCd = getProdCd(prodName);
        // Here only one time one product
        PurchaseOrderDTO itemData = new PurchaseOrderDTO();

        boolean prodPresent = false;
        itemData.setProdname(prodName);
        itemData.setQty(eoq);
        itemData.setProdcd(productCd);
        double costPrice = ProductView.getProductCost(vendorno, productCd);
        itemData.setPrice(costPrice);
        double extPrice = ProductView.getProductMSRP(vendorno, productCd);
        itemData.setExt(extPrice);
        // Now add the details to the database
        ProductView.addPurchaseDetails(itemData, vendorno);
        if (eoq > 0) {
            items.set(indexOfProdName, itemData);
            ProductView.updatePurchaseDetails(itemData, vendorno);
        } else if (eoq == 0) {
            for (int i = 0; i < items.size(); i++) {
                if (items.get(i).getProdname().equalsIgnoreCase(prodName)) {
                    items.remove(i);
                    ProductView.removePurchaseDetails(itemData, vendorno);
                }
            }
        }

    } else {
        orderedProdNameList.add(prodName);
        String productCd = getProdCd(prodName);
        // Here only one time one product
        PurchaseOrderDTO itemData = new PurchaseOrderDTO();

        boolean prodPresent = false;
        itemData.setProdname(prodName);
        itemData.setQty(eoq);
        itemData.setProdcd(productCd);
        double costPrice = ProductView.getProductCost(vendorno, productCd);
        itemData.setPrice(costPrice);
        double extPrice = ProductView.getProductMSRP(vendorno, productCd);
        itemData.setExt(extPrice);
        items.add(items.size(), itemData);
        ProductView.addPurchaseDetails(itemData, vendorno);
    }
    if (items.size() > 0) {
        calculateTotal();
    }
}


texts:
Background:

Didn't what to have to reference bulky 3rd party lib for inline data driven tests and wanted to use standard MS testing framework.

Created helper InlineDataDrivenTest to provide a workaround for this limitation.

Usage

[TestClass]
public class DataDrivenTests : MiscUnitTests {

    [TestMethod]
    public void Should_Do_Data_Driven_Test() {
        //Arrange
        var source = new TestDataSource();
        var test = InlineDataDrivenTest.Create(source);
        test.Setup(c => c.TestAdd(0, 0, 0));
        //Act
        test.Run();
        //Assert
        var summary = test.GetResult();
        Assert.IsTrue(summary.Succeeded, summary.Message);
    }

    [TestMethod]
    public void Should_Do_Data_Driven_Test_And_Fail() {
        //Arrange
        var target = new TestDataSource();
        var test = InlineDataDrivenTest
            .Create(target)
            .Setup(m => m.TestSubtract(0, 0, 0));
        //Act
        test.Run();
        //Assert
        var summary = test.GetResult();
        Assert.IsTrue(summary.Failed == 1, summary.Message);
    }

    public class TestDataSource {

        [DataDrivenTestMethod]
        [DataRow(1, 2, 3)]
        [DataRow(4, 5, 9)]
        public void TestAdd(int a, int b, int expected) {
            Calculator c = new Calculator();
            int actual = c.Add(a, b);
            Assert.AreEqual(expected, actual);
        }

        [DataDrivenTestMethod]
        [DataRow(4, 2, 2)]
        [DataRow(4, 1, 1, DisplayName = "Should fail for demo purposes")]
        public void TestSubtract(int a, int b, int expected) {
            Calculator c = new Calculator();
            int actual = c.Subtract(a, b);
            Assert.AreEqual(expected, actual);
        }

    }

    public class Calculator {

        public int Add(int a, int b) {
            return a + b;
        }

        public int Subtract(int a, int b) {
            return a - b;
        }
    }
}

Thoughts and feed back on code.

This solves the immediate need but I'm looking to improve on current model.


texts:
I'm trying to create a simple way for current & future (non VBA literate) employees to accomplish some of the tasks I've struggled with. The first being Parsing cells containing Line Feed Characters.

When reports are produced from Workday, sometimes they have to be produced for each item separately, and you end up with a folder like this -

Within each book is a sheet of the same name, but cut off at 31 characters (the maximum for sheet names).

I'd like to enable the user to simply select the folder containing the books and consolidate, rename and alphabetize the sheets.

All in the same module (the CONST) used later, main sub:

Option Explicit
Public Const COMPUTER As String = "C:\"

Public Sub CombineWorkbooks()

    Dim myPath As String
    myPath = UserInputDirectory(COMPUTER)
    If myPath = vbNullString Then
        MsgBox "You cancelled the operation", vbCritical
        Exit Sub
    End If

    Application.DisplayAlerts = False
    Application.EnableEvents = False
    Application.ScreenUpdating = False

    Dim destinationWorkbook As Workbook
    Set destinationWorkbook = Workbooks.Add
    destinationWorkbook.Sheets("Sheet2").Delete
    destinationWorkbook.Sheets("Sheet3").Delete

    Dim sourceWorkbook As Workbook
    Dim sourceWorksheet As Worksheet

    Dim strFilename As String
    strFilename = Dir(myPath & "\*.xls", vbNormal)
    If Len(strFilename) = 0 Then Exit Sub

    Do Until strFilename = ""
        Set sourceWorkbook = Workbooks.Open(Filename:=myPath & "\" & strFilename)
        Set sourceWorksheet = sourceWorkbook.Worksheets(1)
        RenameSheet sourceWorksheet
        sourceWorksheet.Copy After:=destinationWorkbook.Worksheets(destinationWorkbook.Worksheets.Count)
        sourceWorkbook.Close False
        strFilename = Dir()
    Loop
    destinationWorkbook.Sheets("Sheet1").Delete

    Application.DisplayAlerts = True
    Application.EnableEvents = True

    AlphebetizeSheets destinationWorkbook
End Sub

And the supporting cast

Private Sub AlphebetizeSheets(ByVal myBook As Workbook)
    Dim i As Long
    Dim j As Long

    For i = 1 To myBook.Worksheets.Count
        For j = i To myBook.Worksheets.Count
            If UCase(myBook.Sheets(j).Name) < UCase(myBook.Sheets(i).Name) Then
                  myBook.Sheets(j).Move before:=Sheets(i)
             End If
        Next
    Next
    Application.ScreenUpdating = True
    Application.GetSaveAsFilename
End Sub

Private Sub RenameSheet(ByVal targetSheet As Worksheet)
    Dim myParser As Long
    Dim newName As String
    myParser = InStr(1, targetSheet.Name, "(")
    If myParser > 0 Then
        newName = Trim(Left(targetSheet.Name, myParser - 1))
        targetSheet.Name = newName
    End If
End Sub

Private Function UserInputDirectory(ByVal baseDirectory As String) As String
    Dim userFolder As FileDialog
    Dim directoryName As String
    MsgBox "Please select the folder the workbooks are in"
    Set userFolder = Application.FileDialog(msoFileDialogFolderPicker)
    With userFolder
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = baseDirectory
        If .Show <> -1 Then GoTo FolderPicked
        directoryName = .SelectedItems(1)
    End With
FolderPicked:
    UserInputDirectory = directoryName
    Set userFolder = Nothing
End Function

I'm sort of worried that there's too much going on in the CombineWorkbooks() sub and that I've missed some errors that may need to be handled.


texts:
Here is part of my implementation of reading a Kinesis stream. I am not confident that this is the best way to implement synchronizing returns from goroutine.

Assuming there are N shards in the stream, the code spawns goroutines for each shard in the stream for processing. Goroutine-N works indefinitely until the underlying context is canceled or until an error is encountered during processing.

The code below is supposed to wait for all N routines to terminate successfully (i.e without any of them writing to errc) or wait for at least one routine to write to errc (return an error).

If all routines terminate without writing to errc, the WaitGroup sync lock is released, closing the errc and done channels. Which would, in turn, resume the current thread. However, if one of the routines terminate writing to errc, we force all routines to terminate by calling the underlying context's cancel function and wait for done channel to close.

func (c *Consumer) scanShards(col Collector, streamName string, ids []string) error {
    checkpoints, err := col.GetSequenceNumberForShards(streamName, ids)
    if err != nil {
        return fmt.Errorf("error retrieving stored checkpoints for shards: %v", err)
    }

    errc := make(chan error, 1)
    done := make(chan error, 1)
    wg := sync.WaitGroup{}
    wg.Add(len(ids))
    for _, id := range ids {
        seqNum := checkpoints[id]

        ctx, cancel := context.WithCancel(context.Background())
        c.cancelFuncs = append(c.cancelFuncs, cancel)
        go func(ctx context.Context, shardID, startSeqNum string) {
            defer wg.Done()
            if err := c.scanShard(ctx, shardID, startSeqNum); err != nil {
                errc <- fmt.Errorf("error in shard %q: %v", shardID, err)
            }
        }(ctx, id, seqNum)
    }
    go func() {
        wg.Wait()
        close(errc)
        close(done)
    }()
    err = <-errc
    if err != nil {
        // Cancel all scans, to release the worker goroutines from
        // the pool.
        for _, cancel := range c.cancelFuncs {
            cancel()
        }
    }
    <-done // Wait for all goroutines to exit.
    return err
}


texts: Implementation of observer pattern for Node.js

texts:
I wrote an implementation of observer pattern as part of my online battle Chess game:

const observers = Symbol();

class Observer{

    constructor(){

        if(new.target === Observer){

            throw new Error('Cannot create new Observer object. Observer is supposed to be inherited only.');
        }

        /**
         * @private
         * @type {Set}
         */
        this[observers] = new Set();
    }

    on(observer, event, callback){

        this.getObservers().add({

            observer,
            event,
            callback
        });
    }

    off(observer, event){

        const observers = this.getObservers();
        const observerEntries = this.getObservers().values();

        for(let entry of observerEntries){

            if(entry.observer === observer && entry.event === event){

                observers.delete(entry);
            }
        }
    }

    notify(event, data = {}){

        const observerEntries = this.getObservers().values();

        for(let entry of observerEntries){

            if(entry.event === event){

                entry.callback.call(entry.observer, data);
            }
        }
    }

    getObservers(){

        return this[observers];
    }
}

module.exports = Observer;

The source code for the full game is in a GitHub repository. This is an early version, without many features implemented and possibly with many bugs. I have a humble request to review my code. I'm aware of several things (backend Node code is very messy). The client-side is written in MVC and Observer patterns. I'm looking for feedback (both positive and negative) and advice/guidelines.


texts: how can I optimize this code for a powerline?

texts:
I made this code for a past test, I only got 30/100 points obtainable, because it went out of time,how can I make it more efficient?
#include <iostream>
#include <fstream>
bool check(int s[], int n)
{
    for (int i = 0; i < n; i++)
    {
        if (s[i] < s[i + 1] && i != n - 1)
        {
            return false;
        }
    }
    return true;
}
int main()
{
    std::ifstream in("input.txt");
    std::ofstream out("output.txt");
    int n;
    int s[1000000];
    bool legge = false;
    int c = 0;
    in >> n;
    for (int i = 0; i < n; i++)
    {
        in >> s[i];
    }
    legge = check(s,n);
    while (!legge)
    {
        for (int i = 0; i < n; i++)
        {
            int m = i+1;
            if (s[i] < s[m] && i != n-1)
            {
                s[i] = s[m];
            }
        }
        legge = check(s,n);
        c ++;
    }
    out << c;
}

Text:
In order to increase their efficiency, a new law mandates that every tower in a power line must be at least
as high as the following one. Luca needs to change the height of some towers, in order to meet the new
requirements. Every day, starting from the first tower, Luca will increase the height of every tower to
the same height of the next one. Of course, if one tower is already taller than the following one it will
not be modified. How many days does Luca need to finish the job?


texts: Looping through one million rows and corresponding columns

texts:
I'm trying to find some name, go to the corresponding column, and then search and go back to corresponding name and paste in a different worksheet. This code basically first finds the name then goes to the corresponding column and stores the value. It searches for that value in another column and goes to the corresponding column after the search and copies the corresponding column values and pastes in another worksheet.

Is it possible to make this code execute in less time? I want to it run for less than 10 secs. I am working on around max rows and columns.

  Dim mRange As Range, lastrow As Long, coresponC as String, wsheet1 as Worksheet, wsheet2 as Worksheet
  Dim xoffset As Object, searchIndex As Object, connData as Variant, aData as Variant, alldata2 as Variant, cRange As Range

Set cRange = wsheet2.Range(wsheet2.Range("C1"), wsheet2.Cells(Rows.Count, 1).End(xlUp))
aData = cRange.Value

Set mRange = wsheet2.Range(wsheet2.Range("A1"), wsheet2.Cells(Rows.Count, 1).End(xlUp))
alldata2 = indexRange.Value
lastrow = wsheet2.UsedRange.Rows.Count + 1

  For i = 1 To UBound(aData, 1)
    If wsheet2.Cells(i, 3).Value = "Mic" Or wsheet2.Cells(i, 3) = "Ram" Or wsheet2.Cells(i, 3) = "Sam" Or wsheet2.Cells(i, 3) = "Tom" Then
     Set coresponC = wsheet2.Cells(i, 3)
       Set xofset = coresponC.Offset(columnoffset:=7)

           If InStr(1, xoffset, "1.") <> 0 Then
               With wsheet2.Range("a1:a" & lastrow)
               Set searchIndex = .Find(wsheet2.Range("J" & i).Value, LookIn:=xlValues)

              If Not searchIndex Is Nothing Then
                 firstAddress = searchIndex.Address

              Do
                  searchIndex.Offset(columnoffset:=3).Copy
                  wsheet1.Range("B" & x).PasteSpecial
              Loop While Not searchIndex Is Nothing And searchIndex.Address <> firstAddress
             x = x + 1
           End If
           End With
           End If
           End If
   next i


texts: Python : adding a columns with count of missing values by row

texts:
I have a big python data-frame and I am trying to add a column to it with average number of missing values by row. I have inherited some code that is working but I'd like to reduce memory usage by removing intermediary values.
Here is a toy exemple :
students = [ ('jack', np.NaN, 'Sydeny' , 'Australia') ,
                 ('Riti', np.NaN, 'Delhi' , 'India' ) ,
                 ('Vikas', 31, np.NaN , 'India' ) ,
                 ('Neelu', 32, 'Bangalore' , 'India' ) ,
                 ('John', 16, 'New York' , 'US') ,
                 ('John' , 11, np.NaN, np.NaN ) ,
                (np.NaN , np.NaN, np.NaN, np.NaN )
                 ]
dfObj = pd.DataFrame(students, columns = ['Name' , 'Age', 'City' , 'Country'])

And the code I inherited :
print('NanCounter -> transform')
nan_count = pd.DataFrame(data = np.mean(dfObj.isna().values, axis=1).astype('float32'), columns=['nan_count']).set_index(dfObj.index)
X_ = pd.concat([dfObj, nan_count], axis=1)
X_.set_index(dfObj.index, inplace=True)

It seems quite a convoluted way to just write :
print('NanCounter -> transform')
dfObj['nan_count'] = np.mean(dfObj.isna().values, axis=1).astype('float32')

Plus it seems to consume more memory. I am concerned I am missing something about calculcations. Are those expression equivalent ? Namely, what would be the interest with working with a supplementary variable ?


texts:
I would like to hear feedback from an interviewer's perspective on how to improve the following code:

from collections import Counter

def word_map(string):
    word_dict = {}
    stop_word_file=open("stopwords.txt", "r")
    stop_words =stop_word_file.read().split()
    for word in string.split():
        word = filter(str.isalnum, word).lower()
        word = word.strip()
        if word != '' and word not in stop_words:
            if word in word_dict.keys():
                word_dict[word] +=1
            else:
                word_dict[word] = 1

    return word_dict

file = open("story.txt", "r")

five_top_words = Counter(word_map(file.read())).most_common(5)
for letter, count in five_top_words:
    print '%s : %10d' %(letter, count)


texts: Getting position of coordinates and checking if they match

texts:
I have to compare variables to obtain coordinates.

           l
upleft     l     upright
-----------l--------------
downleft   l     downright
           l

Here is what I am doing now:

protected function check_if_quadrant_is_valid($variable)
    {
        $middle_of_x = 297;
        $middle_of_y = 421;

       $heigth =  $variable["y"] <= $middle_of_y ?   "up" :  "down";

       $side =  $variable["x"] <= $middle_of_x ?  "left" : "right";

            $variable_location = $heigth . $side;

            if($this->item->$variable_location == 1)
            {
                return true;
            }
         return false;
    }

The variable $variable is an array with x and y as key and their coordinates as value.

The variable $item is an object. It contains whether the variable should be in the quadrant. It contains $item->upleft, $item->upright, $item->downleft, $item->downright that are booleans.

The point of this function is to retrieve the quadrant of the $variable and check if it is valid within the $item.

The code works perfectly, however it feels very cheap.

Here is the same that can be copypasted and their values changed to test:

function check_if_quadrant_is_valid()
    {
        #Change at will
        $item["upleft"] = 0;
         $item["upright"] = 1;
          $item["downleft"] = 1;
           $item["downright"] = 1;

        $variable["y"] = 90;
        $variable["x"] = 20;

        $middle_of_x = 297;
        $middle_of_y = 421;

       $heigth =  $variable["y"] <= $middle_of_y ?   "up" :  "down";

       $side =  $variable["x"] <= $middle_of_x ?  "left" : "right";

            $variable_location = $heigth . $side;

            if($item[$variable_location] == 1)
            {
                return true;
            }
         return false;
    }


texts:
I already learned JAVA, a few design patterns (Controllers, etc.) and OOP. I'm trying too build some PHP scripts in OOP (a blog). I want to collect some articles from the DB and store in an array. I'm doing this with a repository (like I do this is JAVA). Is this correct?

Artikel.php :

class Artikel {
private $id;
private $naam;

function __construct($id, $naam) {
    $this->id = $id;
    $this->naam = $naam;
}
function getId() {
    return $this->id;
}

function getNaam() {
    return $this->naam;
}

function setId($id) {
    $this->id = $id;
}

function setNaam($naam) {
    $this->naam = $naam;
}
}

ArtikelMapper.php

    require_once '../Classes/Artikel.php';
    class ArtikelMapper {
    private $database;

    function __construct($database) {
        $this->database = $database;
    }

    function getArtikels(){
        /* become a mysql query, this is just for showing */
        $array = array();
        $art1 = new Artikel(1, "name1");
        array_push($array, $art1);
        $art2 = new Artikel(2, "name2");
        array_push($array, $art2);
        return $array;
    }
}

ArtikelRepository.php

require_once '../Classes/Artikel.php';
require_once '../Mappers/ArtikelMapper.php';
class ArtikelRepository {
    private $artikelMapper;
    private $artikelArray;

    function __construct($database) {
        $this->artikelMapper = new ArtikelMapper($database);
        $this->artikelArray = $this->artikelMapper->getArtikels();
    }

    function getArtikels(){
        return $artikelArray;
    }

    function addArtikels($artikel){
        array_push($this->artikelArray, $artikel);
    }

}


texts:
I created a class to scrape URLS, parse and validate emails and get internal links.
How can I achieve the SOLID principles in this class written in Javascript to make a web scraper?
const axios = require('axios');
const fs = require('fs')
const {
    JSDOM
} = require('jsdom');
class Scraper {
    static dangerDomains = ['loan', 'work', 'biz', 'racing', 'ooo', 'life', 'ltd', 'png'];
    static emailRegex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi;
    static domObject = null;
    static internalLinks = new Set();
    static externalLinks = new Set();
    constructor(url) {
        this.url = url;
        this.emails = new Set();
        this.dangerEmails = new Set();
    }

    async executeScraper() {
        const fetchedData = await this.fetchUrlAndGetDom(this.url);
        const links = await this.getInternalLinks();
        const linksArray = Array.from(Scraper.internalLinks);
        const emails = await this.fetchInternalLinks(linksArray);
        this.addEmails(emails);
        this.validateEmails();
        await this.writeFile();
    }

    const result = async fetchInternalLinks(internalLink) {
        const result = await Promise.all(internalLink.map((link) => {
            return this.fetchUrlAndGetDom(`${this.url}${link}`);
        }));
        return result;
    }

    async fetchUrlAndGetDom(url) {
        try {
            const response = await axios(url);
            if (response.status === 200) {
                let htmlData = await response.data;
                Scraper.domObject = await new JSDOM(htmlData);
                let dades = this.searchForEmails();
                return dades;
            } else if (response.status === 404) {
                console.log('this page doesnt exists')
                return process.exit(1);
            }
        } catch (error) {
            console.log(error)
            return process.exit(1);
        }
    }

Get all the internal links from a website to scrape them

    getInternalLinks() {
        let links = Scraper.domObject.window.document.body;
        links = links.querySelectorAll('a[href^="/"]');
        Array.from(links).filter(link => Scraper.internalLinks.add(link.getAttribute('href')));
    }

Use of a regex to find all the emails in the dom

    searchForEmails() {
        let emailsInDom = Scraper.domObject.window.document.body.innerHTML;
        let emails = emailsInDom.toString().match(Scraper.emailRegex)
        return emails;
    }

Validate all the emails found in the dom

    validateEmails() {
        const validatedEmails = Array.from(this.emails).filter(email => {
            let domainName = email.split('@')[1].split('.')[1];
            if (Scraper.dangerDomains.includes(domainName)) {
                this.dangerEmails.add(email);
                this.emails.delete(email);
            } else return email;
        });
    }

Write the emails in a file

    async writeFile() {
        return new Promise((resolve, reject) => {
            fs.writeFile('./emails.txt', Array.from(this.emails), err => {
                if (err) reject('Could not write file');
                resolve('success');
            });
        });
    }

Add email to the propertie emails

    addEmails(emailsInDom) {
        Array.from(emailsInDom).filter(el => {
            if(el !== null) {
                el.filter(el => this.emails.add(el))
      }
    });
    }
}

This execute the scraper

const Scraper = require('./Scraper');
const scraper = new Scraper('any url');
(async () => {
  try {
    const dades = await scraper.executeScraper();

  } catch (e) {
    console.log(e)
  }
})()


texts: Linq IEnumerable extensions for void functions

texts:
I found myself wanting to use Linq to map void methods to an IEnumerable to modify all items. The existing Linq methods require a return variable when mapping, since they are based on Func.

So I decided to try my hand at creating some extension methods myself. This is the first time I've done anything like this, so if there are any pitfalls I'm missing, please do tell.

I created two extensions, one which applies a foreach loop to all elements, calling an Action<T> for each. The second one is basically the Zip extension, which allows for two IEnumerables to be iterated together and again maps a Action<T1,T2> to both of them.

public static void ForEachAction<T>(this IEnumerable<T> sequence, Action<T> action) {
  foreach(T value in sequence) {
    action(value);
  }
}

public static void ForEachActionZip<Tbase, Tsecond>(this IEnumerable<Tbase> sequence, IEnumerable<Tsecond> second, Action<Tbase, Tsecond> action) {
  sequence.Zip(second, (first, other) => new { first, other }).ForEachAction(x => action(x.first, x.other));
}

You can then use this like so:

someList.ForEachAction(x => x.Update());

or

someList.ForEachActionZip(secondList, (a, b) => a.Update(b));


texts:
Can you check my merge sort implementation?  From all of my testing it seems like it works, but I just wanted to make sure I am doing it as good as possible, and it couldn't be optimized any further.

private static void merge(int[] c,int[] a, int[] b){
    int i = 0;//index for a
    int j = 0;//index for b
    for(int k = 0; k < c.length; k++){
        //check a[] edge case
        if(i >= a.length){
            c[k] = b[j];
            j++;
        }else if(j >= b.length){
            c[k] = a[i];
            i++;
        }else if(a[i] < b[j]) {
            c[k] = a[i];
            i++;
        } else {
            c[k] = b[j];
            j++;
        }
    }
}

public static void mergeSort(int[] A){
    if(A.length > 1){
        int pivot = A.length / 2;
        int[] left = Arrays.copyOfRange(A, 0, pivot);
        int[] right = Arrays.copyOfRange(A, pivot,A.length);
        mergeSort(left);
        mergeSort(right);
        merge(A,left,right);
    }
}


texts: Find Common Denominator for 2 Fractions with JavaScript - Simplify & Improve

texts:
I wrote a JavaScript that takes 2 fractions and finds the common denominator for both. If the user inputs 2/6 and 1/2 --- the script outputs 2/6 + 3/6. I'm interested in feedback on possibly simplifying it or improving it. Thanks.

JS Bin: http://jsbin.com/omelen/1/edit

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>


texts:
As you probably know, Python slices like arr[1:3] etc. do NOT provide a view onto list and instead creates a copy of the list, what can be not optimal performance if array is big and you make for example arr[1:] (copies all exept first)
the idea of a view to an array is like :

class ylist_view():

    def __init__(self,lst, begin, end):

        self.list = lst
        self.len = end - begin
        self.begin = begin
        self.end = end

    def __getitem__(self, i):
        if i<0: i += self.len
        return self.list[self.begin + i]

    def __setitem__(self, i,value):
        if i<0: i += self.len
        self.list[self.begin + i] = value

     def __str__(self):
            return  '[' + ', '.join( str(self.list[i]) for i in range(self.begin, self.end)) + ']'

class inbox():

    def __init__(self, value):
        self.value = value

    def __str__(self):
        return '<' + str(self.value) + '>'

    def __repr__(self):
        return '<' + str(self.value) + '>'

    a =   [ inbox(x) for x in  [1,2,3,4,5]]

    b = a [1:3]

    b[0] = 20 # creates a copy

    print('list a is unchanged:', a)
    print('b = a [1:3] is a copy of a :', b)

    c = ylist_view(a,1,3)

    c[0] = 20

    print('ylist_view c is a view to a:', a)

Inbox class is a dummy class for illustration.
As you can see, b = a [1:3] is a copy, whereas c = ylist_view(a,1,3) references the original array.
Does it make sense to use this approach in a real Python project or there is some built-in in Python to do that?


texts: Given bit strings, perform a bitwise addition

texts:
I'm looking for code-review, optimizations and best practices. This code is a Java adaptation of code on geeksforgeeks.org. Please verify if space complexity is \$O(n)\$ where n is number of bits, and aux complexity is \$O(1)\$, since no temporary space was needed. Whatever space was needed was used for return value not for temporary purpose. Rectify my understanding of space and aux complexity if wrong.

public class AddBinaryStrings {

    public static String addBinaryStrings(String num1, String num2) {

        final StringBuilder sum = new StringBuilder(Math.max(num1.length(), num2.length()) + 1);
        String shortNum;
        String longNum;
        if (num1.length() < num2.length()) {
            shortNum = num1;
            longNum = num2;
        } else {
            shortNum = num2;
            longNum = num1;
        }

        int carry = 0;
        int i = longNum.length() - 1;
        int j = shortNum.length() - 1;

        for (; j >= 0; j--, i--) {
            int num1Digit = longNum.charAt(i) - '0';
            int num2Digit = shortNum.charAt(j) - '0';

            sum.append(num1Digit ^ num2Digit ^ carry);
            carry = (num1Digit & num2Digit) | (num1Digit & carry) | (num2Digit & carry);
        }

        for (; i >= 0; i--) {
            int num1Digit =  longNum.charAt(i) - '0';
            sum.append(num1Digit ^ carry);
            carry = num1Digit & carry;
        }

        if (carry == 1) {
            sum.append(1);
        }

        return sum.reverse().toString();
    }
}

public class AddBinaryStringTest {

    @Test
    public void testCarry() {
        assertEquals("1000" , AddBinaryStrings.addBinaryStrings("101","11"));

    }

    @Test
    public void testNoCarry() {
        assertEquals("1101", AddBinaryStrings.addBinaryStrings("1000", "101"));
    }

}


texts: Represent a person who has different roles for different offices

texts:
People have different types of roles depending on the office they are working at. For example, a person has two roles (cashier,cleaner) at OfficeMax and five roles(manager,security,etc) at OfficeLess.  Typescript is used.

interface Person {
    name : string,
    roles : OfficeRoles
}

interface OfficeRoles {
    roles : OfficeRole[],
    office : Office
}

interface OfficeRole {
    getType() : RoleType
}

interface Office {
    name : string
}

enum RoleType {
    CLERK,CUSTODIAN,SECURITY;
}

The following Person object would represent John, who is a Clerk and Security at OfficeMax:

let office : Office = { name : "OfficeMax" };
let roles : Role[] = [ new ClerkRole( "John" ) , new SecurityRole(1) ];
let person : Person = { name : "John" , roles : roles };

class ClerkRole implements Role {
    private name : string;
    constructor( name : string ) {
        this.name = name;
    }
    getType() { return RoleType.CLERK; }
}

class SecurityRole implements Role {
    private id : number;
    constructor( id : number ) {
        this.id = id;
    }
    getType() { return RoleType.SECURITY; }
}

Is the above a good representation of the requirements?  Specifically, I had trouble with the OfficeRole interface as the different office roles do not share any commonality.


texts:
I wrote some code to solve this problem https://www.hackerrank.com/challenges/string-o-permute which basically states: take an even length string and swap all the even indexed characters. For example the string "abcd" should become "badc". I'm looking for a general code review as I'm very new to F# and specifically I'd really like to get rid of the ignoredTupleValue variable, it seems like a kludge to me. I'd also like to collapse the whole thing into one function but I was running into scoping issues with the StringBuilder.

open System
open System.Text

[<EntryPoint>]
let main argv =
    let numCases = Console.ReadLine() |> int
    for i = numCases downto 1 do
        let strIn = Console.ReadLine()
        let pairs = Seq.pairwise strIn
        let ignoredTupleValue = ('1', '1')
        let swappedTuples = pairs |> Seq.mapi (fun idx pair ->
                                if idx % 2 = 0 then
                                    let (a, b) = pair
                                    (b, a)
                                else
                                    ignoredTupleValue)
        let answer = Seq.fold (fun (sb : StringBuilder) pair ->
                                if pair <> ignoredTupleValue then
                                    let (a, b) = pair
                                    sb.Append(a) |> ignore
                                    sb.Append(b) |> ignore
                                sb)
                                (new StringBuilder())
                                swappedTuples
        printfn "%s" (answer.ToString())
    0


texts:
I am trying to simply measure my code execution time.

public class PerfMeasureUtil {

    private static final Logger LOG = Logger.getLogger(PerfMeasureUtil.class.getName());
    private long startTime;
    private long duration;
    private static final EnvironmentProperties env = new EnvironmentProperties();

    /**
     * start counting the time
     *
     * @return self
     */
    public PerfMeasureUtil start() {
        if (env.isDev()) {// || env.isTest()) {
            LOG.log(Level.INFO, "====================================== measurement starts");
            this.startTime = System.currentTimeMillis();
        }
        return this;
    }

    /**
     * stops counting the time and returns the result
     *
     * @param methodName
     * @return
     */
    public long stop(String methodName) {
        if (env.isDev()) {// || env.isTest()) {
            this.duration = System.currentTimeMillis() - startTime;
            LOG.log(Level.INFO, "====================================== {0}", methodName);
            LOG.log(Level.INFO, "time spend: {0}ms", duration);
            LOG.log(Level.INFO, "======================================");
            return duration;
        }
        return -1;
    }
}

EnvironmentProperties has a boolean property based on the Maven build type. The measurement should be executed only on dev, or maybe testing environment, not in production. Now I call it like this everywhere, where it is needed:

    PerfMeasureUtil measureUtil = new PerfMeasureUtil().start();
    foo = readFooFromSomewhere();
    bar.applyFoo();
    printResult(bar);
    measureUtil.stop("FooBarApplication.aplyFooOnBar");

Is there something that could be made clearly better? I am not sure about the permanent if-check even on other built types when it is not needed.

And of course the pollution of code is pretty bad with it, but this way I have more control on the code amount measured. Maybe annotation could help?


texts:
This seems like an awful lot of code and I'm guessing can be condensed and made more efficient somehow. Can anyone suggest this to me at all?

// Add the active class to the first element
$('.indexWorkDetailsInner:first').addClass('active');

// Next Button Click
$('.indexWorkRight').click(function() {

    // Move all except the active element to the left
    $('.indexWorkDetailsInner').each(function() {
        if($(this).hasClass('active')) { }
            else {
                $(this).css({'left':'-450px'});
            }
    });

    // Animate the active element off the screen
    $('.indexWorkDetailsInner.active').stop().animate({'left' : '450px'}, 1000, function () {

        $(this).removeClass('active').css({'left':'-450px'}); // Remove the active class, and move element back to the left
        $(this).next('.indexWorkDetailsInner').animate({'left' : '0px'}, 1000).addClass('active'); // Animate the next element in to view
        $('.indexWorkDetailsInner:last').after($('.indexWorkDetailsInner:first')); // Move the last element to after the first

    });

});

// Previous Button Click
$('.indexWorkLeft').click(function() {

    // Move all except the active element to the right
    $('.indexWorkDetailsInner').each(function() {
        if($(this).hasClass('active')) { }
            else {
                $(this).css({'left':'450px'});
            }
    });

    // Animate the active element off the screen
    $('.indexWorkDetailsInner.active').stop().animate({'left' : '-450px'}, 1000, function () {

    $(this).removeClass('active').css({'left':'450px'}); // Remove the active class, and move element back to the right
    $('.indexWorkDetailsInner:first').before($('.indexWorkDetailsInner:last')); // Move the first element before the last item
    $(this).prev('.indexWorkDetailsInner').animate({'left' : '0px'}, 1000).addClass('active'); // Animate the previous element in to view

    });

});

// Add the active class to the first element
$('.indexMonitorWork img:first').addClass('active');

// Next Button Click
$('.indexWorkRight').click(function() {

    // Move all except the active element to the left
    $('.indexMonitorWork img').each(function() {
        if($(this).hasClass('active')) { }
            else {
                $(this).css({'left':'-370px'});
            }
    });

    // Animate the active element off the screen
    $('.indexMonitorWork img.active').stop().animate({'left' : '370px'}, 1000, function () {

        $(this).removeClass('active').css({'left':'-370px'}); // Remove the active class, and move element back to the left
        $(this).next('.indexMonitorWork img').animate({'left' : '0px'}, 1000).addClass('active'); // Animate the next element in to view
        $('.indexMonitorWork img:last').after($('.indexMonitorWork img:first')); // Move the last element to after the first

    });

});

// Previous Button Click
$('.indexWorkLeft').click(function() {

    // Move all except the active element to the right
    $('.indexMonitorWork img').each(function() {
        if($(this).hasClass('active')) { }
            else {
                $(this).css({'left':'370px'});
            }
    });

    // Animate the active element off the screen
    $('.indexMonitorWork img.active').stop().animate({'left' : '-370px'}, 1000, function () {

    $(this).removeClass('active').css({'left':'370px'}); // Remove the active class, and move element back to the right
    $('.indexMonitorWork img:first').before($('.indexMonitorWork img:last')); // Move the first element before the last item
    $(this).prev('.indexMonitorWork img').animate({'left' : '0px'}, 1000).addClass('active'); // Animate the previous element in to view

    });

});

It is code for a work carousel. The first two functions move the text left and right. The bottom function moves the image screenshot.


texts: improve the design of class “accuracy” in Python

texts:
I am learning about the class and methods in Python.

The class Accuracy is a class of several (13 in total) statistic values between a reference polygon and one or more segmented polygons based on shapely module.

from numpy import average

#some stat

def ra_or(ref, seg):
    return average([(ref.intersection(s).area/ref.area) for s in seg])

def ra_os(ref, seg):
    return average([(ref.intersection(s).area/s.area) for s in seg])

def sim_size(ref, seg):
return average([(min(ref.area, s.area)/max(ref.area,s.area)) for s in seg])

def AFI(ref,seg):
   return (ref.area - max([s.area for s in seg]))/ref.area

where ref.intersection(s).area is the area of intersection between reference and segmented polygon-i

my class design (really basic and probably to improve) is:

class Accuracy(object):
    def __init__ (self,ref,seg = None, noData = -9999):
        if seg == None:
            self.area = ref.area
            self.perimeter = ref.length
            self.centroidX = ref.centroid.x
            self.centroidY = ref.centroid.y
            self.data =  [self.centroidX,
                        self.centroidY,
                        self.area,
                        self.perimeter,
                        noData,
                        noData,
                        noData,
                        noData,
                        noData]
        else:
            self.area = ref.area
            self.perimeter = ref.length
            self.centroidX = ref.centroid.x
            self.centroidY = ref.centroid.y
            self.segments = len(seg)
            self.RAor = ra_or(ref,seg)
            self.RAos = ra_os(ref,seg)
            self.SimSize = sim_size(ref,seg)
            self.AFI = AFI(ref,seg)
            self.data = [self.centroidX,
                        self.centroidY,
                        self.area,
                        self.perimeter,
                        self.segments,
                        self.RAor,
                        self.RAos,
                        self.SimSize,
                        self.AFI]

from shapely.geometry import Polygon

p1 = Polygon([(2, 4), (4, 4), (4, 2), (2, 2), (2, 4)])
p2 = Polygon([(0, 3), (3, 3), (3, 0), (0, 0), (0, 3)])

accp1 = Accuracy(p1,[p2])
accp1.data
[3.0, 3.0, 4.0, 8.0, 1, 0.25, 0.1111111111111111, 0.44444444444444442, -1.25]

accp1 = Accuracy(p1)
accp1.data
[3.0, 3.0, 4.0, 8.0, -9999, -9999, -9999, -9999, -9999]


texts: Fill ArrayList of String with empty String to maintain order of elements

texts:
I'm writing a logic for converting data fetched from data base into CSV format.
The total number of header fields in CSV file are 14. Now it is possible that not all the field values are available. To give an example the data could be :

__________________________________________
|C1 | C2 | C3 | C4 | C5 |....|C12|C13|C14|
------------------------------------------
| V | V  | V  | V  | V  | V  | V |   |   |
| V | V  | V  | V  | V  |    |   |   |   |
| V | V  | V  | V  | V  |    |   |   |   |

Now I use an ArrayList to store the data in order of CSV fields. Also the values for first five columns (C1-C5) and the column C12 of CSV file are always available . The values for C6-C11 may or may not be available and they are stored in another list.And this will always be the case.Now to maintain the order, I have to insert empty string in ArrayList. So the code would be like -

ArrayList<String> csvRow = new ArrayList<String>();
// adding mandatory values (C1-C5)
csvRow.add(value); // there will be 5 such statement.
if(!optionalValList.isEmpty()) {
   // add the values to csvRow List for the C6-C11 fields
}else {
     csvRow.add(""); csvRow.add("");
     // do this for C6-C11 fields. So there
     // will be 6 such statements to add the empty string to List to
     // maintain the order of fields in CSV.
     csvRow.add(value); //adding the mandatory C12 field

 }

Note : Values C1-C5 and C12 are always available. And this will always be the case.

Now I don't like this approach. So I have come up with a logic using the lambda expression which will replace the logic in else block. It is as below :

 public List<String> createList(List<String> inputList){
   return IntStream.range(0,14)
            .mapToObj(i -> (i < inputList.size())? inputList.get(i):"")
            .collect(Collectors.toList());
 }

So the else block will be like :

else {
  csvRow = createList(csvRow);
  csvRow.set(11,value); // setting the column C12
}

Now I want get feedback on this approach. Is this abuse of the lambda features?
If yes how can I do this better.


texts: Typeahead / Autocomplete using AngularJS directive

texts:
I am writing a Type-ahead / Autocomplete search with angular using directive and filter service. I am almost there but need your expert opinions on things which I am planning to achieve.

Git Repository

@Todos:

Look and feel
Allow navigation using keyboard
Enter and Esc key handling

Could anyone review and suggest more optimize ways of writing this?

Also, shall I bind events within a parent controller scope or directive scope? Here is how my directive looks like:

var modServiceDef = angular.module('modSerDefinition', []);

modServiceDef.controller('modDefCtrl', ['$scope', 'myFactory', function($scope,  myFactory) {
    myFactory.getData().then(function (httpData) {
            $scope.dataToPopulate = httpData;
        },function(httpData) {
            console.log('name retrieval failed.');
        });
    }
]);

modServiceDef.directive('typeAhead',[function() {
    return {
        scope : {
            cinfo:'=datalist',
        },
        link:function(scope,element,attr) {
            scope.visible = true;
            scope.updateSearchTerm = function(selName) {
                scope.sterm = selName;
            }
        },
        templateUrl:'templates/typeahead.tmpl'
    }
}]);

modServiceDef.factory('myFactory', function($http,$q) {
    var factory = {};
    var def = $q.defer();
    factory.getData = function() {
        $http.get('https://raw.githubusercontent.com/dominictarr/random-name/master/first-names.json')
            .success(function(res){
                factory.data = res;
                def.resolve(res);
            })
            .error(function(err){
                def.reject(err);
            })
            return def.promise;
        }
    return factory;
});

HTML:

<type-ahead datalist="dataToPopulate"></type-ahead>

Template:

<input type='search' id='idSearch' ng-model='sterm' placeholder='Enter Search Term' />

      {{data}}


texts: Subtract first and last nodes of linked list

texts:
Problem from www.interviewbit.com.

  Problem : Given a singly linked list, modify the value of first half nodes such that :

  1st node’s new value = the last node’s value - first node’s current value

  2nd node’s new value = the second last node’s value - 2nd node’s current value,
  and so on …

  NOTE :
  If the length L of linked list is odd, then the first half implies at first floor(L/2) nodes. So, if L = 5, the first half refers to first 2 nodes.
  If the length L of linked list is even, then the first half implies at first L/2 nodes. So, if L = 4, the first half refers to first 2 nodes.
  Example :

  Given linked list 1 -> 2 -> 3 -> 4 -> 5,
  Return 4 -> 2 -> 3 -> 4 -> 5

  as
  for first node, 5 - 1 = 4
  for second node, 4 - 2 = 2

  Try to solve the problem using constant extra space.

This is my solution on the website's shell. How can this code be better?

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param A : head node of linked list
    # @return the head node in the linked list
    def subtract(self, A):

        if not A.next:
            return A
        fast = A
        slow = A
        prev = None
        cnt = 0
        # reach till half
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            cnt += 1
        if fast:
            start = slow.next
        else:
            start = slow
        #reverse the latter half
        while start:
            temp = start.next
            start.next = prev
            prev = start
            start = temp

        firstA = A
        lastA = prev
        prev1 = prev
        currA = A

        # modify values of first half
        while cnt:
            currA.val = lastA.val - firstA.val
            firstA = firstA.next
            lastA = prev.next

            prev = prev.next

            currA = currA.next
            cnt -= 1

        # reverse the list again
        new_prev =None
        while prev1:
            temp = prev1.next
            prev1.next = new_prev
            new_prev = prev1
            prev1 = temp

        return A


texts: Creating an array that loops out on the frontend - Don't Repeat Yourself?

texts:
Entire Code Here

Don't repeat yourself

I know of the "Don't repeat yourself". Still it's getting messy in some places. The code below contains three blocks of code.

They are similar in some ways and different in others. It doesn't follow the same pattern in all ways.

What it does

It creates an array that I loop out on the frontend.

Question

Is there any better way to do this kind of stuff? Less messy, better structure?

$message_start = 'h2 tags - ';
$message_end = '' . $this->count_h2 . '';
if( $this->count_h2 == 0 ) {
    $message = 'No tags found. Add some!';
    $array['content_editor']['count_h2']['status'] = 2;
} elseif( $this->count_h2 == 1 ) {
    $message = 'Some found. Too few!';
    $array['content_editor']['count_h2']['status'] = 1;
} else {
    $message = 'Many found. Great!';
    $array['content_editor']['count_h2']['status'] = 0;
}
$array['content_editor']['count_h2']['message'] = $message_start . $message . $message_end;
$array['content_editor']['count_h2']['count'] = $this->count_h2;

$message_start = 'h3-h6 tags - ';
$h2_h6 = $this->count_h3 + $this->count_h4 + $this->count_h5 + $this->count_h6;
$counter = ( $h2_h6 == 0 ) ? '' : $h2_h6;
$message_end = '' . $counter . '';
if( $h2_h6 == 0 ) {
    $message = 'No found. Add some!';
    $array['content_editor']['count_h3_h6']['status'] = 1;
} else {
    $message = 'Found, great!';
    $array['content_editor']['count_h3_h6']['status'] = 0;
}
$array['content_editor']['count_h3_h6']['message'] = $message_start . $message . $message_end;
$array['content_editor']['count_h3_h6']['count'] = $this->h2_h6;

$message_start = 'Title keywords - ';
$counter = ( $this->found_keywords1_post_title == 0 ) ? '' : $this->found_keywords1_post_title;
$message_end = '' . $counter . '';
if( count( $this->keywords1 ) == 0 ) {
    $message = 'No primary added.';
    $array['content_editor']['missing_keywords1_post_title']['status'] = 2;
} elseif( $this->found_keywords1_post_title == 0 ) {
    $message = 'No primary found.';
    $array['content_editor']['missing_keywords1_post_title']['status'] = 2;
} else {
    $s = ( $this->found_keywords1_post_title != 1 ) ? 's' : '';
    $message = 'Primary found.';
    $array['content_editor']['missing_keywords1_post_title']['status'] = 0;
}
$array['content_editor']['missing_keywords1_post_title']['message'] = $message_start . $message . $message_end;
$array['content_editor']['missing_keywords1_post_title']['count'] = $this->found_keywords1_post_title;


texts: Searching for an idiomatic Rust implementation of Minimum Edit Distance (LeetCode #72)

texts:
I am solving LeetCode Dynamic Programming challenges (this one is #72, at https://leetcode.com/problems/edit-distance).
Here below, I've implemented a Rust solution for the minimum edit distance between two strings problem. (Note that this solution works and passes all the test cases on LeetCode)
use std::collections::HashMap;
use std::cmp::min;

impl Solution {
    pub fn min_distance(word1: String, word2: String) -> i32 {
        let mut D: HashMap<(i32, i32), i32> = HashMap::new();
        let m = word1.len() as i32;
        let n = word2.len() as i32;

        let w1: Vec<char> = word1.chars().collect();
        let w2: Vec<char> = word2.chars().collect();

        for i in 0..=m {
            D.insert((i, 0), i);
        }
        for j in 0..=n {
            D.insert((0, j), j);
        }

        for i in 1..=m {
            for j in 1..=n {
                if w1[(i-1) as usize] == w2[(j-1) as usize] {
                    D.insert((i, j), *D.get(&(i-1, j-1)).unwrap());
                } else {
                    let p = *D.get(&(i - 1, j - 1)).unwrap();
                    let q = *D.get(&(i - 1, j)).unwrap();
                    let r = *D.get(&(i, j - 1)).unwrap();

                    D.insert((i, j), 1 + min(p, min(q, r)));
                }
            }
        }

        return *D.get(&(m, n)).unwrap();
    }
}

I've actually also solved the same thing in JAVA, which I have a much better command on...
public class EditDistance {
    public static int minDistance(String word1, String word2) {
        int m = word1.length();
        int n = word2.length();
        int[][] D = new int[m+1][n+1];

        for(int i=0; i<=m; ++i) D[i][0] = i;
        for(int j=0; j<=n; ++j) D[0][j] = j;

        for(int i=1; i<=m; ++i) {
            for(int j=1; j<=n; ++j) {
                if(word1.charAt(i-1) == word2.charAt(j-1)) D[i][j] = D[i-1][j-1];
                else D[i][j] = 1 + Math.min(D[i-1][j-1], Math.min(D[i-1][j], D[i][j-1]));
            }
        }
        return D[m][n];
    }

    public static void main(String[] args) {
        System.out.println(minDistance("intention", "execution"));
    }
}

Something about my Rust solution seems off to me. Not really sure but here are some of my irritations:

I couldn't find a better way to iterate a string and refer to it by its index easily other than having to convert it to a vector.

I think I'm unwrap()-ing too much. Although I'm not aiming for code golf here, it still feels subconsciously that I could have avoided so many unwrap()s.

I feel a bit bad because I kind of word to word translated my solution from Java... perhaps there's a more Rust-idiomatic way of doing whatever I did?

Looking forward to your advise and help :-) Thanks in advance!


texts:
I have finished my Python Hangman app with very basic code.

import random
import sys

# lets set some variables
wordList = [
"lion", "umbrella", "window", "computer", "glass", "juice", "chair", "desktop",
 "laptop", "dog", "cat", "lemon", "cabel", "mirror", "hat"
           ]

guess_word = []
secretWord = random.choice(wordList) # lets randomize single word from the list
length_word = len(secretWord)
alphabet = "abcdefghijklmnopqrstuvwxyz"
letter_storage = []

def beginning():
    print("Hello Mate!\n")

    while True:
        name = input("Please enter Your name\n").strip()

        if name == '':
            print("You can't do that! No blank lines")
        else:
            break

beginning()

def newFunc():
    print("Well, that's perfect moment to play some Hangman!\n")

    while True:
        gameChoice = input("Would You?\n").upper()

        if gameChoice == "YES" or gameChoice == "Y":
            break
        elif gameChoice == "NO" or gameChoice == "N":
            sys.exit("That's a shame! Have a nice day")
        else:
            print("Please Answer only Yes or No")
            continue

newFunc()

def change():

    for character in secretWord: # printing blanks for each letter in secret word
        guess_word.append("-")

    print("Ok, so the word You need to guess has", length_word, "characters")

    print("Be aware that You can enter only 1 letter from a-z\n\n")

    print(guess_word)

def guessing():
    guess_taken = 1

    while guess_taken < 10:

        guess = input("Pick a letter\n").lower()

        if not guess in alphabet: #checking input
            print("Enter a letter from a-z alphabet")
        elif guess in letter_storage: #checking if letter has been already used
            print("You have already guessed that letter!")
        else:

            letter_storage.append(guess)
            if guess in secretWord:
                print("You guessed correctly!")
                for x in range(0, length_word): #This Part I just don't get it
                    if secretWord[x] == guess:
                        guess_word[x] = guess
                        print(guess_word)

                if not '-' in guess_word:
                    print("You won!")
                    break
            else:
                print("The letter is not in the word. Try Again!")
                guess_taken += 1
                if guess_taken == 10:
                    print(" Sorry Mate, You lost :<! The secret word was",         secretWord)

change()
guessing()

print("Game Over!")

So, I have couple questions about my code:

I have started to lean some stuff about classes in Python and I thought "Hey, let's write this Hangman with Classes)" But after some coding I realised, i just made classes with 1 func and instead of func() I just called them class.func() and that's all. Is there any good reason why and how I should use classes in a Hangman game?
I know that code is very basic and at my level I shouldn't exactly mind effectiveness of the code but still - Which Part Should be improved ( not the code itself but my logic there)? I want to write in a "proper" way but my code still looks super basic.


texts: Python3 Stack implementation with List built-in

texts:
So, inspired by this other code review, I wanted to see if I could implement a very basic stack without the linked-list approach taken by the OP in their implementation.

To that end, I came up with the following Stack class.  I wrote it for Python 3, but it actually works as-is in Python 2 as well:

class Stack:
    _stack = []

    def __init__(self):
        self._stack = []

    @property
    def size(self):
        return len(self._stack)

    @property
    def count(self):
        return self.size

    def __sizeof__(self):
        return self.size

    def pop(self):
        if self.size == 0:
            return "Cannot pop from an empty stack."

        item = self._stack[self.size - 1]
        self._stack.remove(item)
        return item

    def peek(self):
        if self.size == 0:
            return "Cannot peek into an empty stack."

        return self._stack[self.size - 1]

    def push(self, item):
        self._stack.append(item)

    def __iter__(self):
        return iter(self._stack)

I'm probably missing some key parts of what one would want from a Stack, but any improvement is welcome.  Literally any improvement.

Note there were a couple things I did intentionally:

I intentionally initialize the _stack attribute as an empty list both in the class itself and in __init__.  For some reason PyCharm complains if the attribute isn't already part of the class when being worked with in __init__, so this is more or less to get PyCharm to stop yelling at me.
I intentionally have __sizeof__ declared as referring to the size property function.  This lets len(StackObject) work if someone doesn't want to do stack.size.

With these in mind, feel free to tell me what you think, or point out any mistakes I've made.  (I'm not an expert in data structures, so I may have gotten some points messed up a little).