texts:
I'm trying to find a way to handle decimals in mongodb. Is there any good way and/or should I handle it with a class like this:

using System;

public class MongoDecimal
{
    public long Value { get; set; }
    public long SubValue { get; set; }
    public long SubValueToValue { get; set; }

    public decimal ToDecimal()
    {
        return Convert.ToDecimal(Value) + (Convert.ToDecimal(SubValue) / Convert.ToDecimal(SubValueToValue));
    }

    public override string ToString()
    {
        return ToDecimal().ToString();
    }

    public string ToString(IFormatProvider provider)
    {
        return ToDecimal().ToString(provider);
    }

    public string ToString(string format)
    {
        return ToDecimal().ToString(format);
    }

    public string ToString(string format, IFormatProvider provider)
    {
        return ToDecimal().ToString(format, provider);
    }

    public static MongoDecimal ToMongoDecimal(decimal value)
    {
        const long subValueToValue = 100000000;
        return ToMongoDecimal(value, subValueToValue);
    }

    public static MongoDecimal ToMongoDecimal(decimal value, long subValueToValue)
    {
        var major = Math.Truncate(value);
        var minor = Math.Truncate((value - major) * Convert.ToDecimal(subValueToValue));

        return new MongoDecimal
        {
            Value = Convert.ToInt64(major),
            SubValue = Convert.ToInt64(minor),
            SubValueToValue = subValueToValue
        };
    }

    public static MongoDecimal operator +(MongoDecimal value, MongoDecimal value2)
    {
        var right = SafeDecimal(value);
        var left = SafeDecimal(value2);

        return ToMongoDecimal(left.ToDecimal() + right.ToDecimal(), left.SubValueToValue >= right.SubValueToValue ? left.SubValueToValue : right.SubValueToValue);
    }

    public static MongoDecimal operator -(MongoDecimal value, MongoDecimal value2)
    {
        var right = SafeDecimal(value);
        var left = SafeDecimal(value2);

        return ToMongoDecimal(left.ToDecimal() - right.ToDecimal(), left.SubValueToValue >= right.SubValueToValue ? left.SubValueToValue : right.SubValueToValue);

    }

    public static MongoDecimal operator *(MongoDecimal value, MongoDecimal value2)
    {
        var right = SafeDecimal(value);
        var left = SafeDecimal(value2);

        return ToMongoDecimal(left.ToDecimal() * right.ToDecimal(), left.SubValueToValue >= right.SubValueToValue ? left.SubValueToValue : right.SubValueToValue);

    }

    public static MongoDecimal operator /(MongoDecimal value, MongoDecimal value2)
    {
        var right = SafeDecimal(value);
        var left = SafeDecimal(value2);

        if (right.Value == 0 && right.SubValue == 0)
            throw new DivideByZeroException();

        return ToMongoDecimal(left.ToDecimal() / right.ToDecimal(), left.SubValueToValue >= right.SubValueToValue ? left.SubValueToValue : right.SubValueToValue);
    }

    public static bool operator ==(MongoDecimal value, MongoDecimal value2)
    {
        if (value == null && value2 == null) return true;
        if ((value == null && value2 != null) || (value != null && value2 == null)) return false;

        return value.ToDecimal() == value2.ToDecimal();
    }

    public static bool operator !=(MongoDecimal value, MongoDecimal value2)
    {
        return !(value == value2);
    }

    public override bool Equals(object obj)
    {
        return this == (obj as MongoDecimal);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = (int)2166136261;
            hash = (hash * 1677619) ^ Value.GetHashCode();
            hash = (hash * 1677619) ^ SubValue.GetHashCode();
            hash = (hash * 1677619) ^ SubValueToValue.GetHashCode();
            return hash;
        }
    }

    public static MongoDecimal SafeDecimal(MongoDecimal d)
    {
        if (d != null)
            return d;
        return new MongoDecimal { SubValue = 0, Value = 0, SubValueToValue = 1 };

    }
}


texts: Look for existing pivottables and change date/year colums based off the “Value” filter

texts:
We have a macro that updates all dates/years in all our pivottables (around 100 of them pulling out data from our OLAP cube) based off of a "Master Date" at the top of our sheet (which is being updated monthly).
The problem is, that the way we're doing it, takes up a lot of space, and we've been forced to split the macro into multiple subs since it started exceeding the compile limit.

As you can see in the code example, its a very primitive way of updating the dates.

The next big problem is that the "YearMonth" filter that is being used to show the year and month is different, because some PT are looking at order quantity (QtyOrdered) and some are looking at sales quantity (QtyCustPackSlip), whihch are using a separate "YearMonth" filter.

Sub UpDateAllPivots()
' UpDateAllPivots Macro, nr.1

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'These ranges are the "Master Date
    D1 = Sheets("DATA").Range("B6").Value
    D2 = Sheets("DATA").Range("C6").Value
    D3 = Sheets("DATA").Range("D6").Value
    D4 = Sheets("DATA").Range("E6").Value
    D5 = Sheets("DATA").Range("F6").Value
    D6 = Sheets("DATA").Range("G6").Value
    D7 = Sheets("DATA").Range("H6").Value
    D8 = Sheets("DATA").Range("I6").Value
    D9 = Sheets("DATA").Range("J6").Value
    D10 = Sheets("DATA").Range("K6").Value
    D11 = Sheets("DATA").Range("L6").Value
    D12 = Sheets("DATA").Range("M6").Value

'This is a PT looking at QtyOrdered, using the Date.YearMonth
ActiveSheet.PivotTables("PivotTable1").PivotFields( _
        "[Date].[YearMonth].[YearMonth]").VisibleItemsList = Array("", _
        "[Date].[YearMonth].&[" & D1 & "]", "[Date].[YearMonth].&[" & D2 & "]", "[Date].[YearMonth].&[" & D3 & "]", _
        "[Date].[YearMonth].&[" & D4 & "]", "[Date].[YearMonth].&[" & D5 & "]", "[Date].[YearMonth].&[" & D6 & "]", _
        "[Date].[YearMonth].&[" & D7 & "]", "[Date].[YearMonth].&[" & D8 & "]", "[Date].[YearMonth].&[" & D9 & "]", _
        "[Date].[YearMonth].&[" & D10 & "]", "[Date].[YearMonth].&[" & D11 & "]", "[Date].[YearMonth].&[" & D12 & "]")

'This is a PT looking at QtyCustPackSlip, using the StatusPickedDatetimeKey
ActiveSheet.PivotTables("PivotTable3").PivotFields( _
        "[StatusPickedDatetimeKey].[YearMonth].[YearMonth]").VisibleItemsList = Array("", _
        "[StatusPickedDatetimeKey].[YearMonth].&[" & D1 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D2 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D3 & "]", _
        "[StatusPickedDatetimeKey].[YearMonth].&[" & D4 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D5 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D6 & "]", _
        "[StatusPickedDatetimeKey].[YearMonth].&[" & D7 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D8 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D9 & "]", _
        "[StatusPickedDatetimeKey].[YearMonth].&[" & D10 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D11 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D12 & "]")

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub

What we ultimately want is to compress it into something that isn't as big, since we're only getting more data. You can imagine how big this is with 100+ PT's and growing.

I was wondering if you could make a loop that looks through all used rows, looking for pivottable1-pivottable(n+1), seing if it exist. If it does exist, then it goes through a switch with two cases being that it either uses QtyOrdered ot QtyCustPackSlip, and updates the .YearMonth accordingly.


texts:
I have a simple function that takes a string and reverses it:

def reverse(string):
    begin = 0
    end = len(string) - 1
    strlist = [i for i in string]
    while(begin < end):
        temp = strlist[begin]
        strlist[begin] = strlist[end]
        strlist[end] = temp
        begin += 1
        end -= 1
    return ''.join(strlist)

print reverse('flash')

I know it's only a simple function but I'm keen to see where my thought process could be improved (even in such a simple context) for future projects.


texts:
I have the following classes. I wonder if this structure makes sense in any terms especially the usage of the UserDetails class from Spring. Should I use loadbyusername method to create and remove methods in account service or is it okay? Then where should we use loadbyusername method?

Base class to cover fundamental properties like id, createdAt, etc.

@Accessors(chain = true)
@Data
@MappedSuperclass
public class Base {
@Id
private String id = UUID.randomUUID().toString();

@CreatedDate
private Date createdAt;

@LastModifiedDate
private Date updatedAt;
}

Account class

@Entity
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"})
@Data
public class Account extends Base {
@NotNull
private String username;

@NotNull
private String password;

@NotNull
@Email
private String email;

@NotNull
private Role role;

}

Account details class implementing userdetails

public class AccountDetails implements UserDetails {

private Account account;

public AccountDetails(Account account) {
    this.account = account;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return null;
}

@Override
public String getPassword() {
    return account.getPassword();
}

@Override
public String getUsername() {
    return account.getUsername();
}

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
public boolean isEnabled() {
    return true;
}
}

Account service

@Service
public class AccountService {

@Autowired
AccountRepository accountRepository;

@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;

@Autowired
ModelMapper modelMapper;

public boolean create(AccountDTO accountDTO) {
    if (usernameExists(accountDTO.getUsername())) {
        throw new UsernameExistsException();
    }

    Account account = modelMapper.map(accountDTO, Account.class);
    account.setPassword(bCryptPasswordEncoder.encode(account.getPassword()));
    account.setId(UUID.randomUUID().toString());
    account.setRole(Role.USER);

    if (accountRepository.save(account) != null) {
        return true;
    } else {
        throw new RuntimeException();
    }
}

public boolean remove(AccountDTO accountDTO) {
    if (!usernameExists(accountDTO.getUsername())) {
        throw new UsernameNotFoundException("Account named " + accountDTO.getUsername() + " not found");
    }

    Optional<Account> account = accountRepository.findByUsername(accountDTO.getUsername());
    accountRepository.delete(account.get());

    if (!usernameExists(accountDTO.getUsername())) {
        return true;
    }

    return false;
}

public boolean usernameExists(String username) {
    return accountRepository.findByUsername(username).isPresent();
}
}

AccountDetailsService implementing userdetailsservice

@Service
public class AccountDetailsService implements UserDetailsService {

@Autowired
AccountRepository accountRepository;

@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    Optional<Account> optionalAccount = accountRepository.findByUsername(s);

    if (!optionalAccount.isPresent()) {
        throw new UsernameNotFoundException("Account named " + s + " not found");
    }

    return new AccountDetails(optionalAccount.get());
}
}


texts:
I wrote this little helper to render a table, however, working with nested content_tag is messy.

  def semantic_table(table_headers)
     content_tag(:table, class: 'ui basic striped table') do
       (content_tag :thead do
         content_tag(:tr) do
           table_headers.each { |h| concat content_tag(:th, h) }
         end
       end).+ content_tag(:tbody) { yield }
     end
  end

For example

# users/index.html.slim
= semantic_table ['Username', 'Email', 'Registration date'] do
  = render @users

That's the only way I could make it work, without overusing concat. This code smells off, how do I refactor it?

I would also like to extract _user.html.slim partial's functionality to the helper, though I don't know how

 # _user.html.slim
 tr
   td = link_to user.name, user
   td = mail_to user.email
   td = time_tag user.created_at


texts: Iterating over an Array and an Iterable (List)

texts:
I have a byte array and a List of a custom object ByteRule and I'm needing to loop around and perform an operation on both but only as long as one of both is available, the original method is as follows:

private final List<ByteRule> rules;

@Override
public boolean match(final InetAddress addr)
{
    final byte[] bytes = addr.getAddress();
    for(int i = 0; i < this.rules.size() && i < bytes.length; i++)
    {
        final int value = bytes[i] < 0 ? (int) bytes[i] + 256 : bytes[i];
        if(!this.rules.get(i).match(value))
        {
            return false;
        }
    }
    return true;
}

Obviously the this.rules.get(i) on every iteration is inefficient, however as I need to maintain a counter, an enhanced for loop means keeping a separate counter and performing a check on it every time like so (list declaration skipped for space):

@Override
public boolean match(final InetAddress addr)
{
    final byte[] bytes = addr.getAddress();
    int counter = 0;
    for(final ByteRule rule : this.rules)
    {
        if(counter + 1 == bytes.length) break; //In case there aren't enough bytes
        final int value = bytes[counter] < 0 ? (int) bytes[counter] + 256 : bytes[counter];
        if(!rule.match(value))
        {
            return false;
        }
        counter++;
    }
    return true;
}

Is there a cleaner/more efficient solution to this problem that I'm missing?


texts: Get latest jsons with respect to [version and name] key in subjson in java

texts:
This is the json

[
  {
    "SUBTASK": {
      "id": 10,
      "name": "TestMap",
      "description": "",
      "version":"1.0"
    }
  },
  {
    "SUBTASK": {
      "id": 23,
      "name": "TestMap",
      "description": "",
      "version":"2.0"
    }
  },
  {
    "SUBTASK": {
      "id": 12,
      "name": "Tree",
      "description": "",
      "version":"13.0"
    }
  },
  {
    "SUBTASK": {
      "id": 32,
      "name": "Tree",
      "description": "",
      "version":"10.0"
    }
  }
]

Need to get latest among the number of SUBTASKS ie. filter the latest versions of SUBTASK with respected to name.

So the final json will be like:

final:[{"SUBTASK":{"id":12.0,"name":"Tree","description":"","version":"13.0"}},{"SUBTASK":{"id":23.0,"name":"TestMap","description":"","version":"2.0"}}]

I achived using the below the java code :

Java Snippet

 public void getLatest(String json) throws Exception {
        // converting json to java Object
        List<Map<String, Object>> taskList = new Gson().fromJson(json, new TypeToken<List<Map<String, Object>>>() {
        }.getType());

        Map<String, Object> taskVersionedMap = new HashMap<String, Object>();

        for (int i = 0; i < taskList.size(); i++) {
            Map<String, Object> processMap = taskList.get(i);
            Map<String, Object> process = (Map<String, Object>) processMap.get("SUBTASK");

            String process_name = process.get("name").toString() + "_" + process.get("version");
            taskVersionedMap.put(process_name, processMap);

            for (Map.Entry<String, Object> entry : taskVersionedMap.entrySet()) {
                String[] split = entry.getKey().split("_");
                double version = Double.parseDouble(split[1]);
                String name = split[0];
                for (Map.Entry<String, Object> entry2 : taskVersionedMap.entrySet()) {
                    String[] split_2 = entry2.getKey().split("_");
                    double version_2 = Double.parseDouble(split_2[1]);
                    String name_2 = split_2[0];
                    if (name.equals(name_2)) {
                        if (version < version_2) {
                            String removedProcessName = name + "_" + version;
                            taskVersionedMap.put(removedProcessName, "ignored");
                        }
                    }
                }

            }
        }
        List<Map<String, Object>> filteredVersionList = new ArrayList<Map<String, Object>>();
        for (Map.Entry<String, Object> mapValues : taskVersionedMap.entrySet()) {
            if (!mapValues.getValue().toString().equals("ignored")) {
                try {
                    filteredVersionList.add((Map<String, Object>) mapValues.getValue());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("final:"+new Gson().toJson(filteredVersionList));

    }

The above code gives accurate result expected and is time consuming.

But is it possible to optimize the code since real data json at process will be verry big almost 500 more subtasks


texts: Node/Express authenticate Google email address

texts:
Trying to set up express server that will authenticate a user's Google email before proceeding.

The code below works, but is there any way to make it more elegant?

The whole new Promise thing feels clunky.

Still wrapping my head around async functions. All the googleapis functions are async, so I feel there's a better way.

I wanted to "wrap" the whole getEmail inside the app.get('/oauth2callback'... but I'm confused by how to "bubble up" a response from several levels of nested async calls so that the app.get call can send the final res to client (if that makes any sense.)

const { google } = require('googleapis');
const express = require('express');

const oauth2Client = new google.auth.OAuth2(
  oauthID, oauthSecret, // from google dev console
  "http://localhost:3000/oauth2callback" //callback URL
);

async function getEmail(auth, code) {
  const { tokens } = await oauth2Client.getToken(code)
  oauth2Client.setCredentials(tokens);
  return new Promise((resolve) => {
    google.people('v1').people.get(
      { auth: auth, resourceName: 'people/me', personFields: 'emailAddresses' },
      (err, res) => {
        if (err) { resolve(err) }
        email = res.data.emailAddresses && res.data.emailAddresses.length && res.data.emailAddresses[0].value
        resolve(email);
      }
    )
  });
}

const app = express();

app.get('/', async (req, res) => {
  const URL = await oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile']
  });
  res.send(`<a href="${URL}">login</a>`);
});

app.get('/oauth2callback', (req, res) => {
  getEmail(oauth2Client, req.query.code)
    .then(r => res.send('••Your Google email is: ' + r))
    .catch(e => res.send('••Error: ' + e))
})

app.listen(3000)

UPDATE: A few hours later, here's what I came up with:

const authURL = auth.generateAuthUrl({
  access_type: 'offline',
  scope: ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile']
});
//...
app.get('/oauth2callback', (req, res) => {
  auth.getToken(req.query.code)
    .then(r => {
      auth.setCredentials(r.tokens)
      google.people('v1').people.get(
        { auth: auth, resourceName: 'people/me', personFields: 'emailAddresses' }
      )
        .then(r => {
          email = r.data.emailAddresses && r.data.emailAddresses.length && r.data.emailAddresses[0].value;
          res.json({email: email})
        })
        .catch(e => res.send('••Error in people: ' + e))
    })
    .catch(e => {
      res.send(`Problem logging in, <a href="${authURL}">try again</a>`)
    })
})

This works, too ... but is it "better"?


texts:
I have written a Sudoku solver, for the euler problem and also packaged it into a ruby gem.  In my solution strategies I do a lot of iteration (double/triple nested loops, I am coming from Java/C).  One method in particular has a lot of if checks and iteration.  Would it be better to package this iteration into an enumerator method or another approach all together?  I am trying to learn the ruby way.  To be clear all the code works but I fear it is written terribly.

All the code can be seen here.

This is from grid.rb

  def x_wing
    box_line_reduction
    remaining_points.each do |point|
      point.nums.each do |num|
        [:x, :y].each do |symbol|
          arr = @points.select{ |p| p.nums.include?(num) && p.send(flip(symbol)) == point.send(flip(symbol)) && p.value == 0  }
          if arr.count == 2 && @points.select { |p| p.value == num && p.send(flip(symbol)) == point.send(flip(symbol)) }.count == 0
            last = @points.select { |p| p.nums.include?(num) &&
                                    arr.map{ |a| a.send(symbol) }.include?(p.send(symbol)) &&
                                    (!arr.include?(p)) &&
                                    p.value == 0 && check_row(p.y,p,num,symbol) }
            if last.all? { |x| x.send(flip(symbol)) == last.first.send(flip(symbol)) } &&
               last.count == 2 &&
               @points.select { |p| p.value == num && p.send(flip(symbol)) == last.first.send(flip(symbol)) }.count == 0
                 final = arr + last
                 places = final.map { |m| m.send(symbol) }.uniq
                 remaining_points.select { |p| places.include?(p.send(symbol)) && (!final.include?(p)) }.each do |poi|
                 poi.nums = poi.nums - [num]
              end
            end
          end
        end
      end
    end


texts:
So, yes, I know that "you shouldn't derive from std containers" but by now it's more of philosophical rule in my mind than a technical one. I've googled again for the one fundamental reason one should never-ever-ever-ever-do-that-ever-ever-ever-or-you-die but couldn't find it.

So, if there's nothing fundamentally wrong with the following and if we set aside performance considerations, can I a get a plain-old code review of this:

namespace growth
{
    template<size_t N>
    class linear
    {
    public:
        static_assert(N != 0, "Linear growth requires positive factor");

        static size_t grow(size_t size, size_t capacity)
        {
            return (size == capacity) ? capacity + N : capacity;
        }
    };

    template<typename Ratio = std::ratio<2, 1>>
    class geometric
    {
    public:
        static_assert(Ratio::num > Ratio::den, "Geometric growth requires ratio greater than 1");

        static size_t grow(size_t size, size_t capacity)
        {
            return (size == capacity) ? std::max((size_t)(capacity * (Ratio::num / (double)Ratio::den)), capacity + 1) : capacity;
        }
    };
}

template<typename T, typename Growth, class Allocator = std::allocator<T>>
class custom_growth_vector : public std::vector<T, Allocator>
{
public:
    using vector = std::vector<T, Allocator>;

    using vector::vector;

    void push_back(T&& value)
    {
        vector::reserve(Growth::grow(vector::size(), vector::capacity()));
        vector::push_back(value);
    }

    // Also replace emplace_back, insert, etc.
};

// ...

// Grows by 50% rather than double when size == capacity.
custom_growth_vector<int, growth::geometric<ratio<3, 2>>> cgvi;


texts:
Below is the code for my templated callback implementation. Currently it works for a single parameter. One thing I was going to try and do next was increase the argument to the function from 1..N arguments. Ideally this would be as simple as adding Args... everywhere using variadic templates. I don't have a lot of experience yet with variadic templates so any advice on this is helpful.

#include <iostream>
#include <vector>

template <typename R, typename Arg>
class Callback
{
  public:
  typedef R (*FuncType)(void*, Arg);
  Callback (FuncType f, void* subscription) : f_(f), subscription_(subscription) { }

  R operator()(Arg a)
  {
    (*f_)(subscription_,a);
  }

  private:
  FuncType f_;
  void* subscription_;
};

template <typename R, typename Arg, typename T, R (T::*Func)(Arg)>
R CallbackWrapper (void* o, Arg a)
{
  return (static_cast<T*>(o)->*Func)(a);
}

class Pricer
{
  public:
  typedef Callback<void,unsigned int> CbType;

  void attach ( CbType cb )
  {
    callbacks_.emplace_back(cb);
  }

  void receivePrice ( double price )
  {
    broadcast(static_cast<unsigned int>(price*100));
  }

  void broadcast (unsigned int price)
  {
    for ( auto& i : callbacks_)
    {
      i(price);
    }
  }

  private:
  std::vector<CbType> callbacks_;
};

class Strategy
{
  public:
   Strategy(Pricer*  p) :  p_(p)
   {
     p->attach(Callback<void,unsigned int>(&CallbackWrapper<void,unsigned int, Strategy, &Strategy::update>, static_cast<void *>(this)));
   }

   void update(unsigned int price)
   {
    //update model with price
     std::cout << "Received price: " << price / 100.0 <<  std::endl;
   }

  private:
  Pricer* p_;
};

int main ( int argc, char *argv[])
{
  Pricer p;
  Strategy s(&p);

  p.receivePrice(105.67);
}


texts: Python Socket programming chat - getting a handle on PEP conventions

texts:
A while back I wrote a socket programmed chat in Python. This question isn't really about the program specifically, moreso on conventions of Python and my style of coding. I've only been using Python for a couple of months and any pointers would be appreciated.

Here's some code I'm curious about:

# in case of inappropriate arguments, remind user how to execute
if len(sys.argv) != 3:
    print("\nExecute the script as below:")
    print(" $ ./sock_client.py <IP Address> <Port>")
    print("For example: `./sock_server.py 127.0.0.1 8008`.")
    print("Additionally, ensure the socket server is live beforehand.\n")
    sys.exit(1)

In all of my Python projects so far, which all are ran from a terminal, I have a block of code like this at the top to ensure number of arguments, and if not, remind the user on how to execute. I don't know if this is good convention or not.

def send_user(m, u):
    """
    Sends a message to a single client.

    Parameter:
    m -- the message to send
    u -- the client to send to
    """
    for c in CLIENT_LIST:
        # only specific client/user
        if CLIENT_LIST[c] == u:
            c.send(bytes(m, "utf8"))

Here's an example docstring. Were I to have a return statement, it would look more like this, though:

def function(param1, param2):
    """
    What function does in a couple words.
    More detail if needed.

    Parameter:
    param1 -- some parameter
    param2 -- another parameter

    Return:
    -- some value

What is considered ideal convention for docstrings?

Here's the full repo: link.


texts: Shell script: is it doing what I think it's doing

texts:
I've not written many shell scripts and cobbled this together from examples. The 'if' condition should check if this is already running and quite if so. The 'wget' call should trigger the php page and write any output to a txt file. The script will be launched by cron. Is this a reasonable approach?

#!/bin/sh
if ps -ef | grep -v grep | grep "dev.mydomain.biz/system_processdata.php" ; then
        exit 0
else
        wget -q -O /tmp/system_processimport.txt http://dev.mydomain.biz/system_processdata.php?a=37&b=61
        exit 0
fi


texts:
I'm learning python and created a number guessing game on which I would like to get your feedback on the structure and style of the program.

import random

LOWER_NUMBER = 1
HIGHEST_NUMBER = 10

def print_header():
    print("-" * 40)
    print("Welcome to the number guessing game")
    print("-" * 40)

def user_input():
    """Collect and validate the entries made by the users

    Returns
    -------
    int
        Gives back the validated number entered by the user.
    """
    while True:
        try:
            guess = int(
                input(f'Enter your Guess of a number between '
                      f'{LOWER_NUMBER} - {HIGHEST_NUMBER}: '))
            if guess < LOWER_NUMBER or guess > HIGHEST_NUMBER:
                print("The entered number is out of range, try again.")
                continue
        except ValueError:
            print('you did not enter a number, please try again.')
            continue
        else:
            break
    return guess

def generate_number_to_guess(lower_number, higher_number):
    """Generates a random number between the given lowest and highest number

    Parameters
    ----------
    lower_number : int
        Lowest number for the generator

    higher_number : int
        highest number for the generator

    Returns
    -------
    int
        returns the generated random number that is in the given range.
    """
    return random.randint(lower_number, higher_number)

def play_again():
    """Perform and validate entry for a next game

    Returns
    -------
    string
        returns the validated user entry for a next game.
    """
    while True:
        new_game = input(
            "Would you like to play again? [y]es/[n]o: ")
        if new_game.lower() not in ["n", "y"]:
            print('Wrong entry please use y or n')
            continue
        else:
            break

    return new_game.lower()

def start_game():
    """This is the main loop that runs the app.
    """
    highscore = 0

    while True:
        print_header()
        number_to_guess = generate_number_to_guess(LOWER_NUMBER,
                                                   HIGHEST_NUMBER)
        guess = 0
        count = 0

        while guess != number_to_guess:
            guess = user_input()
            count += 1
            if guess < number_to_guess:
                print("It's higher")
            elif guess > number_to_guess:
                print("It's lower")
        else:
            print(
                f'\nYou geussed the right number and needed {count} tries')
            if count < highscore or highscore == 0:
                highscore = count

            # validate the input for a new game
            another_game = play_again()
            if another_game == 'y':
                print(f"\n\nThe HIGHSCORE is {highscore}")
                continue
            elif another_game == 'n':
                print("\n Thanks for playing, see you next time!")
                break

if __name__ == "__main__":
    start_game()


texts: jQuery form preview using the Instagram plugin

texts:
How can I improve my jQuery form preview implementation? I'm currently using the jQuery Instagram Plugin to get the hashtag from Instagram.

var timeoutReference;
var element;
var tagsa;

$(document).ready(function() {
  $('input#instagram_hashtag_hashtag').keypress(function() {
    if (timeoutReference) clearTimeout(timeoutReference);

      timeoutReference = setTimeout(function() {
        doneTyping($('input#instagram_hashtag_hashtag').val());
      }, 350);

    });
    $('input#instagram_hashtag_hashtag').blur(function(){
        doneTyping($('input#instagram_hashtag_hashtag').val());
    });
});

function doneTyping(tags){
  if (!timeoutReference){
    return;
  }

  tagsa = null;
  tagsa = tags.match(/(^#|\s#)([a-z0-9]+)/gi);

  timeoutReference = null;

  var length = tagsa.length,
    element = null;
  for (var i = 0; i < length; i++) {
    element = tagsa[i];
    $(function(){
      var
        insta_container = $(".instagram")
      , insta_next_url

      insta_container.instagram({
        hash: element.replace("#", "")
      , clientId: 'instagramclientid'
      , show : 4
      })
    });
  }
}


texts: Enumerating processes without enumerating flaws of the API

texts:
This arose out of the incident where it was realized that WMI could not be expected to be reliable across all various computers. The next thing I looked at was API which was positively awful to work with. Based on a suggestion, I decided to try and use tasklist. Note that efforts was made to ensure there are no disk I/Os, which avoids getting into the messy realms of file management. The only annoyance is that the WshExec will pop open a window but that can be managed and is beyond the scope of the question.

The question is - can we make the process more reliable and failsafe? The idea is that it must be consistent across several computer systems, Windows versions, and so on. This makes uses of Windows Host Scripting Model and ADODB recordset. The application already requires ADODB anyway and the code can be updated to be late-bound as well. For testing/development, I left this in early-bound state.

Public Function EnumProcesses() As ADODB.Recordset
    Dim WshShell As IWshRuntimeLibrary.WshShell
    Dim WshExec As IWshRuntimeLibrary.WshExec
    Dim StdOut As IWshRuntimeLibrary.TextStream
    Dim Data As ADODB.Recordset
    Dim Output As String
    Dim ColumnLengths() As Long

    Set Data = New ADODB.Recordset
    Data.Fields.Append "ImageName", adVarChar, 255
    Data.Fields.Append "PID", adInteger, , adFldKeyColumn
    Data.Open

    Set WshShell = CreateObject("WScript.Shell")
    Set WshExec = WshShell.Exec("tasklist")
    Set StdOut = WshExec.StdOut

    Do While WshExec.Status = WshRunning
        If Not StdOut.AtEndOfStream Then
            Output = StdOut.ReadLine
            Select Case True
                Case Len(Output) = 0, _
                     Output Like "Image Name*"
                    'Skip
                Case Output Like "====*"
                    Dim SplitColumns As Variant
                    SplitColumns = Split(Output, " ")
                    ReDim ColumnLengths(UBound(SplitColumns))

                    Dim i As Long
                    For i = 0 To UBound(SplitColumns)
                        ColumnLengths(i) = Len(SplitColumns(i))
                    Next
                Case Else
                    Data.AddNew
                    Data.Fields("ImageName").Value = Mid$(Output, 1, ColumnLengths(0))
                    Data.Fields("PID").Value = Trim$(Mid$(Output, ColumnLengths(0) + 2, ColumnLengths(1)))
                    Data.Update
            End Select
        End If
    Loop

    Set EnumProcesses = Data
End Function


texts: Call method if child implements interface vs override

texts:
I have a hierarchy like next:

 AbstractRequestWs
   |- CreatorRequestWs
   |- CheckRequestWs
   |- GetRequestWs
   |- DeleteRequestWs

In this implementation I process ws calls with common code. So I've created an Abstract class which contains some common logic and structure.

So I've created a class like next:

public abstract class AbstractRequestWs {

    protected Entity itemMapped;
    protected final EntityToMap entityToMap;

    public AbstractRequestWs(EntityToMap entityToMap) {
        this.entityToMap = entityToMap;
    }

    public Entity map() {
        doSometing();
        //Do this?? or instead override this method on childs
        if (this instanceof StatusUpdatable) {
            ((StatusUpdatable) this).calcualteStatus();
        }
        return mapToEntity();
    }

    protected abstract void doSometing();

    private Entity mapToEntity() {
       //common impl
    }

}

Then some childs need to update a status (which has a large calculation) and some others not, and I've got the idea to create an Interface StatusUpdatable whith a calcualteStatus method so if a child implements this interface the calculateStatus will be called in the Abstract parent class.

For example creator implements StatusUpdatable, so the method calculateStatus will be called.

 public CreatorRequestWs implements StatusUpdatable {
   //....
     public void calculateStatus() {
        //
     }
 }

Otherwise GetRequestWs doesn't implements StatusUpdatable, so the method calculateStatus won't be called.

public GetRequestWs {
   //....
}

So is this a good idea? Check if a child implements some interface and call a method of this interface, or otherwise override the public method and do it directly?

Otherwise I would have to override the map() method in the classes which is need to calculate status:

public CreatorRequestWs  {

   //....

   @Override
   public Entity map() {
       doSometing();
       calcualteStatus();
       return mapToEntity();
   }

   public void calculateStatus() {
      //...
   }
}

I see is more difficult to read than override the map because how the method calculateStatus is call is hide by the parent classes, but otherwise I don't repeat code.

What do you think?


texts: Parallel Multiplier: an implementation of `RecursiveTask`

texts:
This class is my attempt at creating a re-usable class that simplifies the parallel calculation of products. I would appreciate hints on all aspects especially the value of the threshold for which the best performance is obtained.

import java.math.BigInteger;
import java.util.concurrent.RecursiveTask;

import static java.math.BigInteger.ONE;

/**
 * Utility class that uses recursion and multi-threading to compute the
 * product of all the (Big)Integers from a given lower limit (inclusive) to a
 * given upper limit (exclusive). This is useful in calculating the factorial
 * of numbers, or the number of combinations and permutations.
 *
 * @author Subhomoy Haldar
 * @version 1.0
 */
public class ParallelMultiplier extends RecursiveTask<BigInteger> {

    /**
     * The threshold beyond which recursion and multithreading starts.
     */
    private static final BigInteger THRESHOLD = BigInteger.valueOf(500);

    private final BigInteger upper;
    private final BigInteger lower;

    /**
     * Creates a new instance of ParallelMultiplier with the desired limits.
     *
     * @param lowerLimit The inclusive lower limit.
     * @param upperLimit The exclusive upper limit.
     */
    public ParallelMultiplier(final BigInteger lowerLimit,
                              final BigInteger upperLimit) {
        if (lowerLimit.compareTo(upperLimit) >= 0) {
            throw new IllegalArgumentException("Lower limit >= upper limit : "
                    + upperLimit + " >= " + lowerLimit);
        }
        upper = upperLimit;
        lower = lowerLimit;
    }

    /**
     * Returns the required product.
     *
     * @return The required product.
     */
    @Override
    protected BigInteger compute() {
        if (upper.subtract(lower).compareTo(THRESHOLD) <= 0) {
            // perform sequential multiplication
            BigInteger product = ONE;
            for (BigInteger i = lower; i.compareTo(upper) < 0; i = i.add(ONE))
                product = product.multiply(i);
            return product;
        }
        BigInteger mid = upper.add(lower).shiftRight(1);

        ParallelMultiplier multiplier1 = new ParallelMultiplier(lower, mid);
        ParallelMultiplier multiplier2 = new ParallelMultiplier(mid, upper);

        multiplier1.fork(); // On a (hopefully) separate thread

        // combine and return result
        return multiplier2.compute().multiply(multiplier1.join());
    }
}

Just to show that my approach actually has some benefits:

I have a Dual Core, Intel Pentium B950 processor of frequency 2.10 GHz. I have tested this on a 64-bit Ubuntu system. I realized that the threshold value was too low, so it set it to 10_000. After that, I wrote some test code to time the sequential and the parallel approaches to calculate the factorial of 100_000.

The sequential approach:

// ... The limit defined, timer set up...
BigInteger i = ONE, product = ONE;
for (; i.compareTo(limit) <= 0; i = i.add(ONE))
    product = product.multiply(i);
System.out.println(product.toString().length());

The parallel approach:

// ... The limit defined, timer set up...
ParallelMultiplier multiplier = new ParallelMultiplier(ONE, limit.add(ONE));
BigInteger product = multiplier.compute();
System.out.println(product.toString().length());

The number of digits produced in each case is same (=456574), therefore, verifying that the code for the ParallelMultiplier works correctly. But there was a major difference in the time interval:

Sequential: ~5.9 seconds (average)
Parallel  : ~1.2 seconds (average)

Any suggestions to further improve the performance are welcome.


texts:
The string I'd like to check is something like "abcSun24def". If any valid "xxxyy" (xxx = weekday and yy = day) is found, return the position inside the string. If "xxxyy" is not found, return -1.

The code works as desired, but I think it can be optimized.

/* -------------------------------------------------------------
FUNC    : findxy (find pattern xxxyy)
          xxx = weekday (e.g. "Mon01")
          yy = day
          roster specific formatting
PARAMS  : c (char *), pointer to string
RETURNS : (int), if pattern found, pointer to found pattern in string c
          -1 if pattern not found
REMARKS :
---------------------------------------------------------------- */
int findxy(char *c) {
    const char *days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    int i, j;
    char bufw[4];
    char bufd[3];

    /* check if c is at least 5 chars long */
    if (strlen(c) < 5)
        return -1;

    for (i = 0; i <= (int)strlen(c)-5; i++) {
        memcpy(bufw, c+i, 3);
        bufw[3]='\0';
        /* check all 7 weekdays */
        for (j = 0; j < 7; j++) {
            /* find weekday matches */
            if (!strcmp(bufw, days[j])) {
                /* check if both chars following weekday are numerical */
                if (isdigit(c[i+3]) && isdigit(c[i+4])) {
                    memcpy(bufd, c+i+3, 2);
                    bufd[2]='\0';
                    /* check if number after weekday is a valid day */
                    if (atoi(bufd) >= 1 && atoi(bufd) <= 31) {
                        return i;
                    }
                }
            }
        }
    }
    return -1;
}


texts:
The task

  You are given two non-empty arrays representing two non-negative
  integers. The digits are stored in reverse order and each of their
  items contain a single digit. Add the two numbers and return it as an
  array.

  You may assume the two numbers do not contain any leading zero, except
  the number 0 itself.

  Example: Input: [2,4,3] + [5,6,4] Output: [7,0,8]

const a1 = [2,4,3];
const a2 = [5,6,4];

My imperative solution

function addTwoNumbers(a1, a2) {
  const len = a1.length > a2.length ? a1.length : a2.length;
  const res = [];
  let memo = 0;

  const sanitize = n => n ? n : 0;
  for (let i = 0; i < len; i++) {
      let sum = sanitize(a1[i]) + sanitize(a2[i]) + memo;
      memo = sum > 9 ? sum % 9 : 0;
      sum = sum > 9 ? sum % 10 : sum;
      res.push(sum);
  }
  return res;
}

console.log(addTwoNumbers(a1, a2));

My functional solution

const range = num => Array.from(new Array(num), (_, i) => i);

const addTwoNumbers2 = (a1, a2) => {
  const sanitize = n => n ? n : 0;
  const len = a1.length > a2.length ? a1.length : a2.length;
  const {res} = range(len)
  .reduce((acc,i) => {
    let sum = sanitize(a1[i]) + sanitize(a2[i]) + acc.memo;
    acc.memo = sum > 9 ? sum % 9 : 0;
    sum = sum > 9 ? sum % 10 : sum;
    acc.res.push(sum);
    return acc;
  }, {res: [], memo: 0,});
  return res;
};

console.log(addTwoNumbers2(a1, a2));


texts: Counting letter frequencies from an input file

texts:
Out of pure curiosity, I decided to create a short F# script to calculate the letter frequencies based on the input file. Everything works smoothly and as I would expect. My questions regarding my code are as follows:

Does it conform to formal F# standards?

I have done my best to keep it as functional as possible while maintaining a style similar to the most common one I've seen in example programs, but I am unsure if it is up to par.
Does it maximize F#'s capabilities while maintaining readability?

This is as it seems, I am curious as to whether or not I have used all relevant and applicable F# functions inside the program (e.g. map). The portion I am most concerned about is this bit:

Array.map (fun z ->
               let e, f = z
               match count |> Array.tryFind (fun a -> let f,s = a
                                                      (e = f)) with
               | Some x -> (e, Convert.ToInt64(snd x) + f)
               | None -> z)

I am unsure if my approach is proper, that Array.tryFind bit is especially horrendous, but I can't think of a better way to approach this. In addition, instead of the tuple type, should I  instead go for records or is there some other, more appropriate, solution that I am missing?
Are there any ways to optimize or simplify the program I have written?

I have a decently powerful machine (i5 6600, 16GB RAM) and per FSI's #time directive, the program has the following footprint when processing ~10.1gb of text Real: 00:14:30.479, CPU: 00:14:21.421, GC gen0: 208720, gen1: 96, gen2: 8. I have had very little optimization experience whatsoever, so I am unsure if (by my calculations) 11.89mb/s is a good speed for such a relatively simple program.

#if INTERACTIVE
#time
#else
module LetterFreqCalc
#endif

open System
open System.IO

let explode (x:string) = [|for c in x -> c|]

let ToUpper (x:string) = x.ToUpper()

let numLetterInWord word =
    word
    |> ToUpper
    |> explode
    |> Array.countBy id

let sumTupArray (tupArr:(char*int64)[]) =
    tupArr
    |> Array.sumBy snd

let div (x:float) (y:float) = y/x

let mul (x:float) (y:float) = x*y

let rec CalcNextLine (reader:StreamReader) accumulator =
    match reader.EndOfStream with
    | true -> accumulator
    | false ->
               let line = reader.ReadLine()
               let count = numLetterInWord line
               accumulator
               |> Array.map (fun z ->
                                     let e, f = z
                                     match count |> Array.tryFind (fun a -> let f,s = a
                                                                            (e = f)) with
                                     | Some x -> (e, Convert.ToInt64(snd x) + f)
                                     | None -> z)
               |> CalcNextLine reader

let CalcLetterFreqOfFile (path:string) =
    let reader = new StreamReader(path)
    let start = [|for c in [|'A'..'Z'|] -> (c,0L)|]
    CalcNextLine reader start

[<EntryPoint>]
let main argv =
    let occurences = @"dictionary.txt"
                     |> CalcLetterFreqOfFile

    let total = occurences
                |> Array.sumBy snd
                |> float

    let freqs =  occurences
                 |> Array.map (fun x -> (fst x, (let percentage = snd x
                                                                  |> float
                                                                  |> div total
                                                                  |> mul 100.0
                                                 Math.Round(percentage, 2))))

    printfn "%A" freqs
    printfn "%A" (freqs |> Array.sortByDescending snd)
    printfn "%A" argv
    0 // return an integer exit code


texts:
I have just finished working on a problem on hackerrank dealing with time conversion in C++.

I'm still fairly new to programming as I only have a few semesters of programming classes under my belt and had a pretty challenging time with this program.

Below is a link to the problem itself and my code.
I solved the problem but I feel like my time complexity is unnecessarily high.  It works to solve all the test cases the site provides but I am looking to become a better developer so I want to learn to write more efficient and effective code.

Input Format

  A single string containing a time in 12-hour clock format (i.e.:hh:mm:ssAM  or hh:mm:ssPM), where 01 <= hh <= 12.

Output Format

  Convert and print the given time in 24-hour format, where 00 <= hh <= 23.

Please tell show me how I can optimize this code for a better run time.

Link to the problem

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include<iomanip>
using namespace std;

int main(){
    string time;
    cin >> time;
    char delim = ':'; // delimiter for extracting colons from input
    stringstream newTime; // stream to read string that holds time info
    newTime << time;
    int hours,minutes,seconds; // variables to hold data
    string ampm;
    newTime >> hours;
    newTime >> delim;
    newTime>> minutes;
    newTime >> delim;
    newTime>> seconds;
    newTime>> ampm;
    if(ampm == "PM"){ // for changing hours to 0-23 scale
        switch(hours){
            case 1:hours = 13;
            break;
            case 2:hours = 14;
            break;
            case 3:hours = 15;
            break;
            case 4:hours = 16;
            break;
            case 5:hours = 17;
            break;
            case 6:hours = 18;
            break;
            case 7:hours = 19;
            break;
            case 8:hours = 20;
            break;
            case 9:hours = 21;
            break;
            case 10:hours = 22;
            break;
            case 11:hours = 23;
            break;
        }
    }
    else if(ampm == "AM" && hours == 12 ){ // for changing 12am to 00am
        hours = 0;

    }
      //use of iomanip functions below to received desired output
    cout <<  setw(2)<< setfill('0') << hours << ":" << setw(2)<< setfill('0') << minutes << ":" << setw(2)<< setfill('0') << seconds << endl;
    return 0;
}


texts:
I have this method:

    public async Task<ActionResult> Index()
    {
        var orders = await db.Orders.AsNoTracking().GroupBy(x => x.Status).Select(g => new { Status = g.Key, Count = g.Count() }).ToDictionaryAsync(x => x.Status, x => x.Count);
        ViewBag.InWork = orders[WebApplication.Models.Order.OrderStatus.InWork];
        ViewBag.InProcess = orders[WebApplication.Models.Order.OrderStatus.InProcess];
        ViewBag.Accepted = orders[WebApplication.Models.Order.OrderStatus.Accepted];
        ViewBag.Deleted = orders[WebApplication.Models.Order.OrderStatus.Deleted];

        return View();
    }

and it's generated this SQL:

SELECT
    [GroupBy1].[K1] AS [Status],
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT
        [Extent1].[Status] AS [K1],
        COUNT(1) AS [A1]
        FROM [dbo].[Orders] AS [Extent1]
        GROUP BY [Extent1].[Status]
    )  AS [GroupBy1]

How can I escape from SELECT FROM SELECT and optimize this query?


texts:
I've written some code using python. My goal was to harvest name, phone, and web address from extracting all the links available in that webpage. The scraper  is so far following the instructions nicely and harvesting data as it is supposed to.

The logic I applied here is crystal and easy to maintain. If any flaw is found in it's basic design,  It is my incapability I could not shake that off. Hope I'll have any suggestion to improve the design. Thanks a lot for going it through.

The complete code:

import requests
from lxml import html

class HouzzParser:
    main_url = "https://www.houzz.com/professionals/"

    def __init__(self):
        self.keeper = []
        self.session = requests.Session()

    def Scrape(self):
        self.receiver(self.main_url)

    def receiver(self, link):
        # Collecting side-bar links.
        response = self.session.get(link)
        tree = html.fromstring(response.text)

        for item in tree.xpath("//a[@class='sidebar-item-label']"):
            itm_lnks = item.xpath(".//@href")
            for page in itm_lnks:
                self.profile_links(page)     # Sending links to create new hrefs for getting to each profile of first page
                self.pagination_links(page)  # Sending links to process hrefs to the next page

    def pagination_links(self, link):
        # Creating links for the next page
        response = self.session.get(link)
        tree = html.fromstring(response.text)

        for n_url in tree.xpath("//ul[@class='pagination']"):
            items = n_url.xpath(".//a[@class='pageNumber']/@href")
            for item in items:
                self.profile_links(item)

    def profile_links(self, links):
        # Creating links for the profile page
        response = self.session.get(links)
        tree = html.fromstring(response.text)
        for titles in tree.xpath("//div[@class='name-info']"):
            links = titles.xpath(".//a[@class='pro-title']/@href")
            for doc in links:
                self.target_page(doc)

    def target_page(self, urls):
        # Extracting necessary docs from here
        response = self.session.get(urls)
        tree = html.fromstring(response.text)

        for titles in tree.xpath("//div[@class='profile-cover']"):
            name = titles.findtext(".//a[@class='profile-full-name']")
            phone = titles.xpath(".//a[contains(concat(' ', @class, ' '), ' click-to-call-link ')]/@phone")[0] if titles.xpath(".//a[contains(concat(' ', @class, ' '), ' click-to-call-link ')]/@phone") else ""
            web = titles.xpath(".//a[@class='proWebsiteLink']/@href")[0] if titles.xpath(".//a[@class='proWebsiteLink']/@href") else ""
            print(name, phone, web)
            data = name, phone, web
            if data not in self.keeper:
                self.keeper.append(data)

    def __str__(self):
        return self.keeper

if __name__ == '__main__':
    scraper = HouzzParser()
    scraper.Scrape()
    for item in scraper.keeper:
        print(item)


texts: Getting a set of subscribers from a subscriberMap

texts:
In my Java event bus project, I have a private generic method that retrieves a Set<Subscriber<E>> from a private Map<Class<? extends Event>, Set<Subscriber<? extends Event>>> (the subscriberMap).

/**
 * A map of Event types and Subscriber Sets.
 *
 * That is, the Set of Subscribers set to an Event type
 * is assumed to be used for that Event type.
 */
private final Map<Class<? extends Event>, Set<Subscriber<? extends Event>>> subscriberMap = new ConcurrentHashMap<>();

private <E extends Event> void checkSubscriberMap(Class<E> type)
{
    if (!subscriberMap.containsKey(type))
    {
        subscriberMap.put(type, new HashSet<>());
    }
}

/**
 * Gets a Set of Subscribers by an Event.
 *
 * @param event the event
 * @param <E> the type of event
 * @return a Set of Subscribers
 */
@SuppressWarnings("unchecked")
private <E extends Event> Set<Subscriber<E>> getSubscribers(E event)
{
    return (Set<Subscriber<E>>) (Object) getSubscribers(event.getClass());
}

/**
 * Gets a Set of Subscribers by an Event type.
 *
 * @param type the event class
 * @param <E> the type of event
 * @return a Set of Subscribers
 */
@SuppressWarnings("unchecked")
private <E extends Event> Set<Subscriber<E>> getSubscribers(Class<E> type)
{
    checkSubscriberMap(type); // checks if subscriberMap.get(type) is null

    return (Set<Subscriber<E>>) (Object) subscriberMap.get(type);
}

Assuming nobody uses reflection to modify subscriberMap, the public methods that modify subscriberMap only work if the Subscriber<? extends Event> is the same type as the Class<? extends Event>. Therefore, I can be sure that getSubscribers() will always return a Set of the same type that you give it.

/**
 * Registers a single event handler under an explicit Event type.
 * Returns true if the handler was added.
 *
 * @param subscriber the Subscriber
 * @param type the type of Event
 */
public <E extends Event> boolean register(Subscriber<E> subscriber, Class<E> type)
{
    if(type == Event.class)
    {
        throw new IllegalArgumentException("The provided type is not a subclass of Event.");
    }

    return getSubscribers(type).add(subscriber);
}

However, it's bothering me how getSubscribers() looks. Why does it look I'm doing a hacky workaround? Is it necessary that I have to cast subscriberMap.get(type) twice? Is this the right way to go about what I'm trying to do?


texts: Find amounts that cannot be composed using the given coins

texts:
I need to make a program that receives a set of currencies and tests which values between 1 and 10,000 units can not be produced with these currencies.

The program must have 2 input data:

  The number n of existing coin values, with n between 1 and 10.
  The values a1, a2, ..., an of these currencies.

The program should read this data and determine how many values between 1 and 10000 currency units can not be achieved using these currencies.

For example, if we wanted to provide the data on some existing currencies we would have the following entry:

  1

  5

  10

  25

  50

  100

Of course, since this system supplies one cent, all values can be obtained.

I would like to know how I can improve the performance of my code or some part that is poorly written.

import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Vector;

public class CoinChallange {

    private static int [] coins = {5, 11, 13, 23, 29};
    private static int [] numbers;
    private static int [] quantity = { 0, 0, 0, 0, 0};
    private static int i, n, a, b, c, d, e, sum;

    public static void main(String[] args)
    {

        long start = System.currentTimeMillis();

        numbers = new int[10001];
        i = 0;

        for (n = 0; n <= 10000; n++) {
            numbers[n] = n;
        }

        for ( quantity[0] = 0; quantity[ 0 ] <= 2000; quantity[0]++ ) {
            for ( quantity[1] = 0; quantity[ 1 ] <= 2000; quantity[1]++ ) {
                for ( quantity[2] = 0; quantity[ 2 ] <= 2000; quantity[2]++ ) {
                    for ( quantity[3] = 0; quantity[ 3 ] <= 2000; quantity[3]++ ) {
                        for ( quantity[4] = 0; quantity[ 4 ] <= 2000; quantity[4]++ ) {
                            System.out.println( " " + quantity[0] + " " + quantity[1] + " " + quantity[2] + " " + quantity[3] + " " + quantity[4] );
                            sum = quantity[0]*coins[0]+
                                   quantity[1]*coins[1]+
                                   quantity[2]*coins[2]+
                                   quantity[3]*coins[3]+
                                   quantity[4]*coins[4];
                            if ( sum <= 10000 ) {
                                numbers[ sum ] = -1;
                            }
                        }
                    }
                }
            }
        }

        for (n = 1; n <= 10000; n++) {
            if ( numbers[n] > 0 ) {
                System.out.println( numbers[n] );
            }
        }

        long end  = System.currentTimeMillis();
        System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(end - start)));

    }

}

I get to the right result, but it is taking a long time, I believe my logic is very bad.


texts: Print out a student's former name if it is not empty

texts:
(!empty($student->former_name) ? print $student->former_name : '');

I only want to print out the former name if it is not empty, nothing else.

I imagine I do not need the else part of it, but I do not know how to do it like that without the else.

I want to shorthand this:

if(!empty($student->former_name))
 print $student->former_name;


texts: Trying to speed up VBA macro to generate viable Daily Fantasy Sports lineups

texts:
I have created the code below to generate daily fantasy sports lineups from a pool of players that have been entered in my excel file. Right now the code can run through about 16,500 combinations per minute. It takes too long to run through all possible lineups given the large amount of possible combinations. I'm hoping for someone to give me some advice on how to improve the code and/or cut down the run time. Also I am not looking to get a more powerful computer to run this code right now.
'Declare Array
Dim Results
Sheets(1).Activate

'Declare Number of Positions and Players and Assign
Dim QB As Byte, RB As Byte, WR As Byte, TE As Byte, Flex As Byte, Defense As Byte, Players As Long
QB = Sheets("Chosen Player Pool").Range("A27")
RB = Sheets("Chosen Player Pool").Range("F27")
WR = Sheets("Chosen Player Pool").Range("K27")
TE = Sheets("Chosen Player Pool").Range("P27")
Flex = Sheets("Chosen Player Pool").Range("U36")
Defense = Sheets("Chosen Player Pool").Range("Z27")
Players = Sheets("Lineup").Range("B20")

'Create Results Array
ReDim Results(1 To 50000, 1 To 9)

'Clear Lineups Sheet
Sheets("Generated").Activate
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents

'Declare Counters
Dim Rw As Single, i As Byte, j As Byte, k As Byte, l As Byte, m As Byte, n As Byte, o As Byte, p As Byte, q As Byte

'Start Counting, comment out For and next lines then set value to lock
Sheets("Lineup").Activate
ActiveSheet.Range("A2").Select
'QB
For i = 1 To QB
Range("A2").Value = i
'RB1
   For j = 1 To RB
   Range("H3").Value = j
'RB2
      For k = 1 To RB
      Range("H4").Value = k
'WR1
         For l = 1 To WR
         Range("H5").Value = l
'WR2
            For m = 1 To WR
            Range("H6").Value = m
'WR3
               For n = 1 To WR
               Range("H7").Value = n
'TE
                  For o = 1 To TE
                  Range("A8").Value = o
'Flex
                     For p = 1 To Flex
                     Range("A9").Value = p
'Defense
                        For q = 1 To Defense
                        Range("A10").Value = q

'Salary Cap Check
If Range("D15") = "No" Then GoTo SkipPaste

'Duplicates Check
If Range("D18") = "No" Then GoTo SkipPaste
If Rw = 50000 Then GoTo PasteResults
Rw = Rw + 1

'Create Vector Array, Places Player into appropriate column
Results(Rw, 1) = Range("C2"): Results(Rw, 2) = Range("C3"): Results(Rw, 3) = Range("C4"):
Results(Rw, 4) = Range("C5"): Results(Rw, 5) = Range("C6"): Results(Rw, 6) = Range("C7"):
Results(Rw, 7) = Range("C8"): Results(Rw, 8) = Range("C9"): Results(Rw, 9) = Range("C10")

SkipPaste:

'Defense
                        Next q

'Flex
                     Next p

'TE
                  Next o

'WR3
               Next n

'WR2
            Next m

'WR1
         Next l

'RB2
      Next k

'RB1
   Next j

'QB
Next i

'Paste Results
PasteResults:
Sheets("Generated").Cells(1).Resize(UBound(Results, 1), UBound(Results, 2)) = Results
Sheets("Generated").Activate

To add some more background on what is going on in the excel file... On the first sheet of the file ("Lineup", where most of the work is being done), I have Index(Match()) functions to look up the player, salary and team information based on the iteration of the loop. I then have a check to make sure that the salary fits into the constraints of the rules (Cell D15). I then make sure that players are not repeated as they could be shown to repeat due to the nature of my loops (Cell D18). Please let me know if there are any additional questions you need to help me out. TIA!


texts:
import itertools
import os
import re
from typing import List

class Command:
    """Base command class which all commands inherit from.

    Command class implements all common functions and utilities
    between commands, like file and directories handling, and specific
    commands like arbitrary, text, or picture commands inherit it.
    """

    def __init__(self, args):
        """Instantiate an object with the files/directory to work on."""
        self.dir_path = args.dir_path
        self._extract_files(args)
        self._files_paths = None

    def _extract_files(self, args):
        """
        Returns the files specified by the user, if any.
        Throws exception if no file matches user input.
        """
        self.files_list = None
        if args.name is not None:
            self.files_list = self._file_from_name(args.name)
        elif args.names_file is not None:
            self.files_list = self._names_from_file(args.names_file)
        elif args.rgx is not None:
            self.files_list = self._files_from_rgx(args.rgx)
        elif args.rgx_file is not None:
            self.files_list = self._rgx_from_file(args.rgx_file)
        else:
            self.files_list = self._extract_all_files()

        if len(self.files_list) == 0:
            raise FileNotFoundError("No files match")

    def _files_from_rgx(self, rgx):
        """
        Looks for files in the directory `self.dir_path` with names
        matched to the provided regex and returns those files names.
        """
        f = []
        for (dir_path, dirnames, filenames) in os.walk(self.dir_path):
            f.extend(filenames)
            break
        prog = re.compile(rgx)
        m = []
        for file_name in f:
            matched = prog.match(file_name)
            # matched.span() => (match start index, match end index)
            # Check that the file name is matched as a whole
            if matched and matched.span()[1] == len(file_name):
                m.append(file_name)
        return m

import collections
import os
import pytest

from fipy.parser import parser
from fipy.commands.command import Command

class TestCommand:
    """Tests for the command class."""

    def _populate_tmp_dir(self, tmpdir, dirs, files):
        dirs = [tmpdir.mkdir(x) for x in dirs]
        files = [tmpdir.join(x).write('') for x in files]

    def test_files_from_rgx_no_match(self, tmpdir):
        dirs = ['abc', '1abc', 'x1.txt']
        files = ['x.txt', 'x.tsf', '1abc.png']
        self._populate_tmp_dir(tmpdir, dirs, files)
        args = parser.parse_args(
            ['-p', str(tmpdir), '-r', 's[0-9]*.txt',
            'any', 'rename', '-asc']
        )
        with pytest.raises(FileNotFoundError):
            command = Command(args)

First of all, is it a good practice to set self.dir_path and make the function use it, or pass it to the function as a parameter? (_files_from_rgx function)

And if I want to write unit tests, should I test write a test for the function and another for the constructor, or write tests for the constructor, which implicitly will enter the function which I have done in the test above?


texts:
/**
 * Execute an external program, display raw output in real-time, and buffer output pipes (stdout, stderr) for further processing.
 *
 * @param string|array $cmd Command to execute (not escaped)
 * @param string[] $output_buffers Buffers to capture
 * @return int Exit status code
 */
function tee($cmd, &...$output_buffers) {
    $proc = proc_open($cmd, array_fill(1, count($output_buffers), ['pipe', 'w']), $pipes);
    if($pipes) {
        $filePointers = [];
        foreach($pipes as $p => $pipe) {
            stream_set_blocking($pipe, 0);
            $filePointers[$p] = fopen("php://fd/$p", 'w');
        }
        foreach(array_keys($output_buffers) as $b) {
            $output_buffers[$b] = '';
        }
        $sleep = 10*1000;
        while($output_buffers) {
            $readSuccess = false;
            foreach(array_keys($output_buffers) as $b) {
                $p = $b+1;
                if(feof($pipes[$p])) {
                    fclose($pipes[$p]);
                    unset($pipes[$p]);
                    unset($output_buffers[$b]);
                } else {
                    $line = fgets($pipes[$b + 1]);
                    if(strlen($line)) {
                        $readSuccess = true;
                        fwrite($filePointers[$p], $line);
                        $output_buffers[$b] .= $line;
                    }
                }
            }
            if($readSuccess) {
                $sleep = 10*1000;
            } else {
                usleep($sleep);
                if($sleep < 150*1000) {
                    $sleep *= 2;
                }
            }
        }

        foreach($filePointers as $fp) {
            fclose($fp);
        }
    }
    return proc_close($proc);
}

I wrote this function because I write a lot of PHP-CLI scripts that interface with other shell programs. Often passthru works well for this, but sometimes you also want to capture STDERR in the event that the status code doesn't give enough information. This function lets you do that.

This commenter says that we have to put the pipes into non-blocking mode or the process can hang while it's waiting for you to read the other pipes, so that's what I've done.

Example usage:

tee("echo 'hello'; (>&2 echo \"error\"); echo 'world'", $stdout, $stderr);
dump($stdout);
dump($stderr);

Output:

hello
error
world
"""
hello\n
world\n
"""
"error\n"


texts:
The requirement is to iterate over a list of Foos, and when 2 Foos have the same id merge their list of inputs together and obtain a new object.

I have achieved this with 2 streams and a private method to do this:

import java.util.HashSet;
import java.util.Set;

class Foo {
    private String id;
    private Set<String> inputs = new HashSet<>();

    String getId() {
        return id;
    }

    void setId(String id) {

        this.id = id;
    }

    Set<String> getInputs() {
        return inputs;

    }
}

and the GetMatchingFoos class:

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;

import java.util.List;
import java.util.Map;

public class GetMatchingFoos {

    public List<Foo> call(List<Foo> matchedFoos) {
        Map<String, List<Foo>> idToMatchedFooMap = matchedFoos.stream()
                .collect(groupingBy(Foo::getId, toList()));

        List<Foo> mergedAndMatchedFoos = idToMatchedFooMap.values().stream()
                .map(this::mergeFoos)
                .collect(toList());

        return mergedAndMatchedFoos;
    }

    private Foo mergeFoos(List<Foo> matchedFoos) {
        Foo result = new Foo();
        for(Foo matchedFoo : matchedFoos) {
            result.setId(matchedFoo.getId());
            result.getInputs().addAll(matchedFoo.getInputs());
        }
        return result;
    }

}

Can I obtain the same result by using only a single lambda operation that is more elegant than the above? I have looked into reducing but it was not very trivial.


texts:
I implemented a simple queuing system for my Node.JS app and wanted a critique on it's structure.

const TPS = 20;
const Queue = {
    counter: 1,
    items: {},
    /**
     * Add an item to the queue, with the given func to call
     * @param {Function} func
     * @param {Boolean} repeating
     * @return {Number}
     */
    add(func, repeating = false) {
        const id = this.counter++;
        this.items[id] = {func, repeating, id};
        return id;
    },
    /**
     * Remove an item from the queue with the given id
     * @param {Number} id
     */
    remove(id) {
        if (this.items.hasOwnProperty(id)) {
            delete this.items[id];
        }
    },
    /**
     * Process items in the queue
     */
    process() {
        for (let id in this.items) {
            // Prevent this item from being processed again
            if (!this.items.hasOwnProperty(id) || this.items[id].processing) {
                continue;
            }

            // Delete this item when it's scheduled for deletion
            if (this.items[id].scheduledForDeletion) {
                delete this.items[id];
                continue;
            }

            // Let the queue know this item is being processed and
            // it's scheduled deletion status
            this.items[id].processing = true;
            this.items[id].scheduledForDeletion = !this.items[id].repeating;

            // Don't wait for item's promise to resolve, since this
            // will create a backlog on the queue
            (async () => {
                try {
                    await this.items[id].func.call(null);
                } catch (err) {
                    // TODO: Handle errors.
                    console.error(err);
                }

                this.items[id].processing = false;
            })();
        }
    }
};

(function tick() {
    setTimeout(tick, 1000 / TPS);
    Queue.process();
})();

This is an example of how it's implemented.

// Add three items to the queue: 1 normal, 1 async and 1 repeating
Queue.add(() => console.info(`[tick] -> ${Date.now()}`));
Queue.add(async () => setTimeout(() => console.info(`[async] -> ${Date.now()}`), 100));
const timeLoop = Queue.add(() => console.info(`[loop] time (loop) -> ${Date.now()}`), true);

// Remove the looping item from the queue
setTimeout(() => Queue.remove(timeLoop), 500);

The idea is to have this run when the server starts and continually process the queue items. Queue is in it's own file and exported. I import this file into my controllers and call (for example) Queue.add('function to add user to DB and send out email').


texts:
I am trying to implement Dijkstra without writing lot of code for the Graph class itself. I have implemented it from Wikipedia. However, I am not fond of the way I have handled the minimum distance calculation. I would like to have some improvement on that.

graph = {'s': {'v':1,'w':4 },
         'v': {'w':2,'t':6},
         'w': {'t':3},
         't': {'': None}
         }
def dj(graph, start):
    Q = []# queue to hold all the vertices
    dist = {} #dictionary to hold all the distance
    prev = {} #dictionary to hold all the previous node visited

    for key in graph.keys():
        dist[key] = 1000
        prev[key] = ""
        Q.append(key)

    dist[start] = 0

    #I had to have another distance data structure dst
    # to store all the distance covered
    # I am not fond of it
    dst = []

    while Q:
        # Here I get the minimum distance
        u = min(dist, key = dist.get)
        # remove the min one from Q
        Q.remove(u)
        for v in graph[u]:
            #I also want to improvise this condition block
            #It is because of 't': {'': None}
            if graph[u][v] is None:
                continue
            alt = dist[u] + graph[u][v]
            if alt < dist[v]:
                dist[v] = alt
                prev[v] = u
        #I have to discard the minimum key from dist dictionary
        d = (dist.pop(u))
        # I then have to append the discarded one to dst dictionary
        # Redundant work
        dst.append(d)

    return dst,prev

print(dj(graph,'s'))


texts:
Just wanted to post this here to see if anyone has any critiques of my code, if I'm drawing the background image most efficiently, or if I'm doing anything which could benefit from obvious improvements.

RectangleMover

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class RectangleMover {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                final JFrame frame = new JFrame();

                frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new JPanel(new BorderLayout()) {
                    /**
                     *
                     */
                    private static final long serialVersionUID = 1L;

                    public void paintComponent(Graphics g) {
                        try {
                            super.paintComponent(g);
                            final Image backgroundImage = javax.imageio.ImageIO
                                    .read(new File(
                                            "/Users/langer/Desktop/7923.jpg"));
                            g.drawImage(backgroundImage, 0, 0, FRAME_WIDTH,
                                    FRAME_HEIGHT, null);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
                frame.setVisible(true);

                frame.setLocationRelativeTo(null);

                final RectangleComponent b = new RectangleComponent();
                frame.add(b);
                frame.addMouseMotionListener(new MouseMotionListener() {

                    public void mouseDragged(MouseEvent e) {
                        b.addRect(e.getX(), e.getY());

                        frame.setVisible(true);
                    }

                    public void mouseMoved(MouseEvent e) {
                    }

                });

            }
        });
    }

    private static final int FRAME_WIDTH = 800;
    private static final int FRAME_HEIGHT = 1000;
}

RectangleComponent

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;

import javax.swing.JComponent;

/**
 * This component displays a rectangle that can be moved.
 */
public class RectangleComponent extends JComponent {

    private static final long serialVersionUID = 6596614645871812990L;
    private ArrayList<Rectangle> boxes = new ArrayList<Rectangle>();

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        super.paintComponent(g);

        for (int i = 0; i < boxes.size(); i++) {
            float thickness = 2;
            g2.setStroke(new BasicStroke(thickness));
            g2.drawRect(boxes.get(i).x, boxes.get(i).y - 29,
                    boxes.get(i).width, boxes.get(i).height);
        }
    }

    public void addRect(int x, int y) {
        boxes.add(new Rectangle(x, y, BOX_WIDTH, BOX_HEIGHT));
        repaint();
    }

    private static final int BOX_WIDTH = 42;
    private static final int BOX_HEIGHT = 60;
}


texts: Vectorize pairwise edit distance computation

texts:
How can I vectorize this function? It takes an array of array of tuples as input and computes the distance between elements using Levenshtein's method. I found some simpler examples but they weren't of much use for me since I couldn't apply the same logic for my problem. Any help with making this code more efficient will be appreciated!

def sim_mat(sequence):
    sim_mat = np.empty(sequence.shape[0], sequence.shape[0])
    for i in range(sequence.shape[0]):
        for j in range(i, sequence.shape[0]):
            distance = levenshtein(sequence[i], sequence[j])
            sim_mat [i, j] = sim_mat [j, i] = distance
    return sim_mat

EDIT: Here is the levenshtein function that we use to compute the distance:

def levenshtein(seq1, seq2):
    m = len(seq1)
    n = len(seq2)
    dp = [[0]*(n + 1)]*(m + 1))
    for i in range(1, m + 1):
        dp[i][0] = get_sequence_length(seq1[:i])
    for j in range(1, n + 1):
        dp[0][j] = get_sequence_length(seq2[:j])
    for i in range(m + 1):
        for j in range(n + 1):
            if seq1[i - 1] == seq2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = min(dp[i][j - 1] + len(seq2[j - 1]),  # Insert
                               dp[i - 1][j] + len(seq1[i - 1]),  # Remove
                               dp[i - 1][j - 1] + max(len(sets_difference(seq1[i - 1], seq2[j - 1])),
                                                      len(sets_difference(seq2[j - 1], seq1[i - 1]))))
    return dp[m][n]

and get_sequence_length:

def get_sequence_length(sequence):
    return sum(map(len, sequence))

EDIT2: sets_difference

def sets_difference(set1, set2):
    return list(set(set1).difference(set2))

An example sequence would look like this:

[[('a', 'b', 'c'), ('c', 'd')], [('b', 'd', 'f')]]


texts:
I need a concurrent data structure with the following properties:

Low overhead for enumeration
Insert only at end.
Removal from any point.
Enumeration should be safe with concurrent writing
Enumeration does not require the list to be in a constant state
Not a problem if I enumerate over removed items

I have designed the following linked list class which should meet my requirements.

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

internal class ConcurrentLinkedList<T> : IEnumerable<Node<T>> {
    private readonly BaseNode<T> _root;
    private BaseNode<T> _end;
    public ConcurrentLinkedList() {
        _end = _root = new BaseNode<T>();
    }

    public Node<T> Insert(T value) {
        var node = new Node<T>(value);
        lock (node) {
            lock (_end) {
                node.Previous = _end;
                _end = _end.Next = node;
                return node;
            }
        }
    }

    public void Remove(Node<T> node) {
        lock (node.Previous) {
            lock (node) {
                if (node.Next == null) {
                    if (node.Previous.Next != node) return;
                    node.Previous.Next = null;
                    if (_end == node) _end = node.Previous;
                } else {
                    lock (node.Next) {
                        if (node.Previous.Next == node) node.Previous.Next = node.Next;
                        if (node.Next.Previous == node) node.Next.Previous = node.Previous;
                    }
                }
            }
        }
    }

    public IEnumerator<Node<T>> GetEnumerator() {
        for (var current = _root.Next; current != null; current = current.Next) {
            yield return current;
        }
    }

    IEnumerator IEnumerable.GetEnumerator() {
        return GetEnumerator();
    }
}

internal class BaseNode<T> {
    internal volatile Node<T> Next;
}

internal class Node<T> : BaseNode<T> {
    internal BaseNode<T> Previous;

    public T Value { get; }

    public Node(T value) {
        Value = value;
    }
}

I am aware the calls is vary easy to misuse but as it is only for internal use i am not concerned about this. I am considering making the all the class private subclass to ensure that there is no accidental misuse.

In the code all the writing is in a lock but there are shared volatile which are read out of lock. Apart from the possibility of enumerating deleted nodes, is there any other danger with this?

For the locking, I lock no all the node being changed. This should allow other parts of the list to be concurrency modified, the list can get long. Is this sufficient?

To avoid deadlock I always lock from the lowest node to the last.

Is the provided locking sufficient to protect the _end field? I believe that according to the logic used the current _end will always be locked when changing the value of _end. Is this sufficient?

Is this code trying to be too clever and would it better to either:

have one write lock and continue using the volatile for reading.
use a standard ReadWriteLock for the whole list.


texts:
This program converts a decimal number to a binary number. This is one of my first C programs and I am wondering if I have used the elements of this language properly. Suggestions for improvement are welcome.

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

void print_out_reversed(char string[])
{
    int index = strlen(string);

    while (string[index] != '\0')
        index--;

    for (int i = index; i >= 0; i--)
        putchar(string[i]);
    putchar('\n');
}

void print_decimal_number_binary(int number)
{
    if (number == 0)
    {
        printf("0\n");
        return;
    }

    char bits[sizeof(int) * 8 + 1] = {0};
    int index = 0;

    while (number > 0)
    {
        if (number % 2 == 0)
        {
            bits[index] = '0';
        }
        else
        {
            bits[index] = '1';
        }
        number = number / 2;
        index++;
    }

    print_out_reversed(bits);
}

int main()
{
    printf("enter number: ");
    int number;
    scanf("%i", &number);
    print_decimal_number_binary(number);
}


texts: Attempting a Strategy design pattern in JS

texts:
I'm going through the Head First Design Patterns book and I want to check whether I'm understanding some aspects of the first chapter. Does the code below program correctly to interfaces, encapsulate changeable behavior, and employ composition in a reasonable manner?

// trying to enforce some design pattern habits

// create a duck, that prints a line to the page as text
class DuckAbilities {
    constructor() {
        this.flying = new FlyBehavior()
    }
    addToPage() {
        this.statement = document.createElement("p")
        this.statement.innerHTML=this.flying.fly()
        document.body.append(this.statement)
    }
}
//interface for behaviors
class FlyBehavior {
    fly() {
        null
    }
 }

class DoesFly{
    fly() {
        return "I'm flying"
    }
}
class DoesNotFly {
    fly() {
        return "not flying"
    }
}

class Mallard {
    constructor() {
        this.abilities = new DuckAbilities()
        this.abilities.flying = new DoesFly()
    }

}

class Rubber{
    constructor() {
        this.abilities = new DuckAbilities()
        this.abilities.flying = new DoesNotFly()
    }
}

window.onload = ()=> {
    let mallard = new Mallard()
    mallard.abilities.addToPage()
    let rubber = new Rubber()
    rubber.abilities.addToPage()
}


texts:
Is there a more concise way of doing this?

const string TOTAL_COUNT_KEY = "totalCount";
private int TotalCount
{
    get
    {
        int safeInt = 0;
        if (ViewState[TOTAL_COUNT_KEY] != null)
            safeInt = (int)ViewState[TOTAL_COUNT_KEY];
        return safeInt;
    }
    set { ViewState[TOTAL_COUNT_KEY] = value; }
}


texts:
I am trying to write a script to securely delete a file. What I am intending to do is to pad the file with /dev/zero once, and then with /dev/urandom three times and then delete the file.

For now the user only accepts one file at a time and the functionality is limited, if I am on the right track then I'll add more options later for recursive, verbose mode off/on, etc.  Is this a good way of doing the thing I want to do? Both from performance aspect and the security.

#! /bin/bash

if [ "$#" -eq 0 ]; then
    echo "ERR: Arguement is not supplied." 1>&2
    exit 1
elif [ "$#" -gt 1 ]; then
    echo "Too many arguments have been provided." 1>&2
    exit 1
fi

if [ ! -f "$1" ]; then
    echo "File $1 is not found" 1>&2
    exit 2
fi

filesize=$(stat -c "%s" "$1")
if [ "$filesize" -eq 0 ]; then
    filesize=1
fi

echo "Padding file with zeros"
dd if=/dev/zero of=$1 bs=$filesize count=1

echo "Padding file with randoms, first time"
dd if=/dev/urandom of=$1 bs=$filesize count=1

echo "Padding fxile with randoms, second time"
dd if=/dev/urandom of=$1 bs=$filesize count=1

echo "Padding file with randoms, third time"
dd if=/dev/urandom of=$1 bs=$filesize count=1

echo "Deleting the file"
rm -f -- $1

echo "File is securely deleted, or at least we think so."


texts:
Following advice to "Make good use of toString() for all Domain classes",  I made what I thought was the most useful toString for my class.  I found that certain operations happen before there are values for the components of the toString.  I wonder if there is a cleaner way to check for nulls or even if I need to approach things differently.  As I'm writing, it occurs to me that depending on other objects in a toString is probably a bad idea.

class AssessmentStep {
    String hours
    Date assStepDate
    Assessment ass
    Step step
    Integer assStepProgress
    static hasMany =[stepNotes:StepNote]

    @Override
    String toString(){
        String stepString = "null"
        String appString = ""
        if (step != null && step.stepName != null){
            stepString = step.stepName
        }
        if (ass !=null && ass.app != null && ass.app.appName != null){
            appString = ass.app.appName
        }

        return appString + " " + stepString
    }


texts: Turning a grayscale image into a histogram of the intensity of the pixels of that image

texts:
This is exercise 3.1.4. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Write a program that takes the name of a grayscale image file as a command-line argument and uses StdDraw to plot a histogram of the frequency of occurrence of each of the 256 grayscale intensities.
Here is my program:
import java.awt.Color;

public class ImageToHistogram
{
    public static double getIntensity(Color color) // this method produces monochrome luminance
    {
        int r = color.getRed();
        int g = color.getGreen();
        int b = color.getBlue();
        return 0.299*r + 0.587*g + 0.114*b;
    }
    public static double[][] convertPictureToArray(Picture picture)
    {
        int width = picture.width();
        int height = picture.height();
        double[][] pixels = new double[width][height];
        for (int col = 0; col < width; col++)
        {
            for (int row = 0; row < height; row++)
            {
                Color color = picture.get(col,row);
                pixels[col][row] = getIntensity(color);
            }
        }
        return pixels;
    }
    public static void drawHistogram(double[][] a)
    {
        int m = a.length;
        int n = a[0].length;
        int pixels = m*n;
        int[] histogram = new int[256];
        StdDraw.setPenColor(StdDraw.BOOK_BLUE);
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                int intensity = (int) a[i][j];
                histogram[intensity]++;
            }
        }
        StdDraw.setXscale(0,256);
        StdDraw.setYscale(0,pixels/20); // obtained "20" by experimentation
        StdDraw.enableDoubleBuffering();
        for (int i = 0; i < 256; i++)
        {
            StdDraw.filledRectangle(i+0.5,histogram[i]/2,0.5,histogram[i]/2);
        }
        StdDraw.show();
    }
    public static void main(String[] args)
    {
        Picture picture = new Picture(args[0]);
        double[][] a = convertPictureToArray(picture);
        drawHistogram(a);
    }
}

StdDraw and Picture are simple APIs written by the authors of the book. I checked my program and it works. Here is one instance of it:
Input (Grayscale picture of Coleen Gray taken from Wikipedia):

Output:

I also tested the extreme cases of pure black and pure white images.
Is there any way that I can improve my program?
Thanks for your attention.
Clarification:
I used the preview of the image provided by Wikipedia with resolution of 800 by 933 and not the original image with resolution of 2000 by 2333.


texts: Returning matching substrings, of n length, at the beginning and end of a string

texts:
I am going through the Java CodingBat exercises. Here is the one I have just completed:

  Given a string, return the longest substring that appears at both the beginning and end of the string without overlapping. For example, sameEnds("abXab") is "ab".]

Here is my code:

public String sameEnds(String string) {

    int strLength = string.length();

    if (string.substring(0, strLength/2).equals(string.substring(strLength/2, strLength))) {
        return string.substring(0, strLength/2);
    }

    for (int i = 1; i < strLength; i++) {
        if (string.substring(0, i).equals(string.substring(strLength-i, strLength) )) {
            return string.substring(0, i);
        }
    }
    return "";
}

The code passes the majority of the tests without the first if statement, so that was included to ensure it passes circumstances such as an input of xxxx. Without this statement, xxxx returns x, which is incorrect.

My questions are:

Is it acceptable/correct to use this 'cautionary' if statement, or should I somehow be incorporating it into the for loop?
Would it make sense, for readability and conciseness, to be creating some variables for things like string.substring(), as I did with strLength?
Would it make sense to use a StringBuilder? I can't really see how it could be used in this particular case.
Does it make sense to use separate return statements, or would it be more useful to assign the outcome to a resultant string, and use only one return statement at the end of the method? i.e.:

Separate statements of String result = "result here";.

One statement at the bottom of return result;.


texts: Putting read data into a combined file based on certain attributes

texts:
I have a pretty big method where I read data from files and then put them into a combined file in a specific format based on an ID, first and end timestamp.

I already refactored some of my code to reduce the code complexity of my method, but it's still over 11 right now. So I was wondering if I should leave the method as is or try to find other ways to make it less complex.

This code will run on hardware which is designed by the company I work for so it's important to be as efficient with memory usage as possible.

Can you have a look at the code and help me out with reducing the code complexity by extracting pieces of code and putting them into separate methods?

protected File getSensorData(String sensorId, long first, long end) throws IOException, NumberFormatException {
  /*
   * This method gets data collected from files named after timestamps in seconds
   */
  String[] idArray = new String[0];
  String[] valArray = new String[0];
  long timestamp = 0;
  File formatFile = File.createTempFile("temp", "bufferedsensordata");
  PrintWriter formatPWriter = getFilePrintWriter(formatFile);

  // This sorts numerical instead of alphabetical
  File[] fileArray = sortFiles(file.listFiles());

  for(File f : fileArray) {
    long longTimestamp = getFileTimestamp(f); // Converts filename into timestamp
    if(longTimestamp >= first && longTimestamp <= end) {
      BufferedReader br = new BufferedReader(new FileReader(f));
      String line;
      while(null != (line = br.readLine())) {
        StringTokenizer tokens = new StringTokenizer(line, ";");
        String timestampString = tokens.nextToken();
        String id = tokens.nextToken();
        String val = tokens.nextToken();
        boolean foundId = false;
        int index = 0;

        if(id.startsWith(sensorId) && (Long.parseLong(timestampString) >= first && Long.parseLong(timestampString) <= end)) {
          // id should be used and timestamp falls between the requested range
          if(!Arrays.asList(idArray).contains(id)) {
            idArray = growArray(idArray); // Increases the array size by 1 to make room for missing id
            valArray = growArray(valArray);
          } else {
            foundId = true;
            index = getIdIndex(idArray, id); // Returns location of the id in the array
          }

          if(foundId) {
            valArray[index] = val; // Puts value in valArray at same spot as id in idArray
          } else {
            idArray[idArray.length -1] = id; // Adds new id & val to end of both arrays
            valArray[valArray.length -1] = val;
          }

          // Timestamps are based on seconds so data should only be written if more than a second has passed
          // But data is recorded per millisecond so there can be multiple pieces of data per second
          if(timestamp != Long.parseLong(timestampString)) {
            if(timestamp != 0) {
              String dataLine = String.valueOf(timestamp);
              for(int i = 0; i < valArray.length; i++) {
                dataLine = dataLine + ";" + valArray[i];
                valArray[i] = "";
              }
              formatPWriter.println(dataLine);
            }

            // Timestamp is update to the next second
            timestamp = Long.parseLong(timestampString);
          }
        }
      }
    }
  }

  File finalFile = newFinalFile();
  PrintWriter finalPWriter = getFilePrintWriter(finalFile);
  // Write idArray as first line (header)
  writeHeader(idArray, finalPWriter);
  // Write valArray as the rest of the file (body)
  writeContent(formatFile, finalPWriter);

  formatFile.delete();

  return finalFile;
}


texts: K&R Exercise 2-6 : Inserting part of a bitset into another

texts:
"Inserting" part of a bitset into another

This is Exercise 2-6 on the K&R book, 2nd edition. The reader is asked to:

  Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

Parameters Description

Here's what each parameter does informally:

x -> serves as the "destination" bitset
y -> serves as the "source" bitset
p -> serves as the insertion point for the bits from y to be inserted on x
n -> serves as the length of the segment to "cut" from y and replace in x

Special Notes

I've tested with a number of different scenarios, and this code has passed all of them.
At the bottom of the question there's an outline of a test-case and my logic behind solving the problem

Code

#include <stdio.h>

//setbits: returns x with n bits that begin at p set to the rightmost n bits of y
//informally: "chop" n bits right->left from y, insert on x at position p
unsigned setbits(unsigned x, int p, int n, unsigned y)
{
    return ((~(~0 << n) & y) << p) | ((~(~(~0 << n) << p)) & x);
}

int main(void) {
    // Example test cases:
    // First scenario:
    // x = 100 ->           0110 0100
    // y = 5 ->             0000 0101
    // p = 4
    // n = 3
    // Expected outcome:    0101 0100  (84)
    // Second scenario:
    // x = 94 ->            0101 1110
    // y = 195 ->           1100 0011
    // p = 0
    // n = 3
    // Expected outcome:    0101 1011  (91)
    // Third scenario:
    // x = 94 ->            0101 1110
    // y = 195 ->           1100 0011
    // p = 6
    // n = 4
    // Expected outcome:    1101 1110  (222)

    printf("%d\n", setbits(100, 4, 3, 5));
    printf("%d\n", setbits(94, 0, 3, 195));
    printf("%d\n", setbits(94, 6, 4, 195));

    return 0;
}

Outline

 Click for full-size image


texts: Awaiting the completion of a server request

texts:
I faced the following problem.

I have a Server object server which exposes TriggerStateChangeAsync() which return an Task<bool> this task finished with true as soon the request for the state changed is send off to the server and with false if the request could not be send to the server. The object also exposses the event StateChanged which will be raised if the server reports that the state has changed.

What I now wanted to do is to write a wrapper Methode which will finishes (async) if after the state has changed or the request could not be send to the server.

It looks like:

public static async Task<boo> TriggerStateChangeAndWaitAsync(this Server server, int stateId)
{
    var stateChanged = new TaskCompletionSource<bool>();

    // local methode
    void handler(object sender, StateEventArgs e)
    {
        // this handels that the state has now actually changed
        if (e.StateId = id)
        {
            server.StateChanged -= handler;
            stateChanged.SetResult(true);
        }
    }

    try
    {
        server.StateChanged += handler;

        // this task finishes when the request is send off to the server
        bool sendToServer = await server.TriggerStateChangeAsync(id);

        if (sendToServer)
        {
            await stateChanged.Task.WithTimeout(1000);
        }

        return sendToServer;
    }
    finally
    {
        server.StateChanged -= handler;
    }
}

Is this an good approch for that? And is it okay to leave the TaskCompletionSource uncompleted in the case that the request could not be sent?

The method WithTimeout(1000) is just an extension methode for Taskthat is just

public static async Task<R> WithTimeout<R>(this Task<R> task, int timeout)
{
    using (var timeoutCancellationTokenSource = new CancellationTokenSource())
    {
        var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
        if (completedTask == task)
        {
            timeoutCancellationTokenSource.Cancel();
            return await task;

        }
        else
        {
            throw new TimeoutException("The operation has timed out.");
        }
    }
}