texts:
I am relatively new to C# and would like to see if what I have been using for my exception handling, message and logging is along industry standards. I have created a simple class for the Error Handler and for the logging I use Log4Net. After reading Clean Code, I was thinking about separating DisplayMessage into 2 different procedures for the message and logging. The log file is usually written to a file server so multiple users can access it; I have enabled MinimalLock for this purpose. For my example, I have changed the log path to C:\Temp\. An example of a project I use the Error Handler class and logging in is on GitHub. For reference, I am using Visual Studio 2017 Community.

ErrorHandler.cs

using System;
using System.Windows.Forms;
using log4net;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

/// <summary>
/// Used to handle exceptions
/// </summary>
public class ErrorHandler
{
    private static readonly ILog log = LogManager.GetLogger(typeof(ErrorHandler));

    /// <summary>
    /// Used to produce an error message and create a log record
    /// <example>
    /// <code lang="C#">
    /// ErrorHandler.DisplayMessage(ex);
    /// </code>
    /// </example>
    /// </summary>
    /// <param name="ex">Represents errors that occur during application execution.</param>
    /// <remarks></remarks>
    public static void DisplayMessage(Exception ex)
    {
        System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(1);
        System.Reflection.MethodBase caller = sf.GetMethod();
        string currentProcedure = (caller.Name).Trim();
        string errorMessageDescription = ex.ToString();
        errorMessageDescription = System.Text.RegularExpressions.Regex.Replace(errorMessageDescription, @"\r\n+", " "); //the carriage returns were messing up my log file
        string msg = "Contact your system administrator. A record has been created in the log file." + Environment.NewLine;
        msg += "Procedure: " + currentProcedure + Environment.NewLine;
        msg += "Description: " + ex.ToString() + Environment.NewLine;
        log.Error("[PROCEDURE]=|" + currentProcedure + "|[USER NAME]=|" + Environment.UserName + "|[MACHINE NAME]=|" + Environment.MachineName + "|[DESCRIPTION]=|" + errorMessageDescription);
        MessageBox.Show(msg, "Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

}

Usage Example:

/// <summary>
/// Return the count of items in a delimited list
/// </summary>
/// <param name="valueList">Represents the list of values in a string </param>
/// <param name="delimiter">Represents the list delimiter </param>
/// <returns>the number of values in a delimited string</returns>
public int GetListItemCount(string valueList, string delimiter)
{
    try
    {
        string[] comboList = valueList.Split((delimiter).ToCharArray());
        return comboList.GetUpperBound(0) + 1;

    }
    catch (Exception ex)
    {
        ErrorHandler.DisplayMessage(ex);
        return 0;
    }
}

Log4Net

app.config

<log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline"/>
        </layout>
    </appender>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
        <file value="C:\Temp\MyLogFile.log"/>
        <appendToFile value="true"/>
        <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date|%-5level|%message%newline"/>
        </layout>
    </appender>
    <root>
        <level value="ALL"/>
        <appender-ref ref="FileAppender"/>
    </root>
</log4net>


texts: Generating a random number of progress bars

texts:
I have this JSFiddle that generates a random number of progress bars then assigns a random number and percent to them.

I am wondering if you know how to better optimize this code to have better run-time.

/*Creates a random amount of bars*/

function runBars() {
    var start = new Date().getTime();
    /*Sets the maximuim amount of bars, 10 if NaN or less than 1*/
    var max_bars = parseInt($('#max_bars').val());
    if (isNaN(max_bars) || max_bars < 1) {
        max_bars = 10;
    }
    /*Grabs a random number of bars*/
    var bars = getRandom(max_bars);
    /*clears bars container*/
    $('#bars-container').html('');
    /*Appends progress bars.*/
    for (var i = 0; i < bars; i++) {
        var element = $('Number ' + (i + 1) + '

');
        $('#bars-container').append(element);
    }
    var end = new Date().getTime();
    var time = end - start;
    $('#bar_time').text(time);
    $('#bar_amount').text(bars);
    /*Populates bars with percents*/
    runPercent();
}

/*Random int with max*/
function getRandom(max) {
    return Math.floor((Math.random() * max) + 1);
}

/*Gets percent based on maxium number, making the percent scale */
function getPercent(x, total, biggest) {
    return Math.floor(x / biggest * 100) + '%';
}

/*Populates percent in each progress bar*/
function runPercent() {
    var start = new Date().getTime();
    var length = $('.progress-bar').size();
    var data = [];
    var total = 0;
    var biggest = 0;
    /*pushes random ints to array*/
    for (var i = 0; i < length; i++) {
        var temp = getRandom(50);
        data.push(temp);
        total += temp;
        if (biggest < temp) {
            biggest = temp
        }
    }
    /*Each progress bar gets a width percentage and sets the text.*/
    $('.progress-bar').each(function (index) {
        $(this).width(getPercent(data[index], total, biggest));
        $(this).text(data[index] + ' / ' + total);
    });
    var end = new Date().getTime();
    var time = end - start;
    $('#percent_time').text(time);
}
/*handles button events*/
$('#percent').click(runPercent);
$('#bars').click(runBars);

/*initiates on page load*/
runBars();
.float {
    position:fixed;
    right:0px;
    text-align:right;
}

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>

    <button id='percent'>Randomize %</button>
    <button id='bars'>Randomize Bars</button>

    <input id='max_bars' type='number' placeholder='Max Number of Bars' />

Result:

Amount of Bars:

In Miliseconds:

Bar Time:
Percent Time:


texts:
Here's my implementation of State Monad in TypeScript, based on a canonical Haskell implementation.
I would like it to get code reviewed.

class StateMonad<S, A> {
  constructor(public runState: (s: S) => ({ s: S, a: A })) {
  }

  static return_<S, A>(a: A): StateMonad<S, A> {
    return new StateMonad(s => ({ s, a }));
  }

  bind<B>(func: (a: A) => StateMonad<S, B>): StateMonad<S, B> {
    return new StateMonad<S, B>((s: S) => {
      const { s: s_, a } = this.runState(s);
      return func(a).runState(s_);
    });
  }
}

// aux monad factory
const createCounter = (regex: RegExp) => new StateMonad((s: string) =>
  s.split('')
    .reduce((acc, c) =>
      (regex.test(c)) ? { s: acc.s.replace(c, ''), a: acc.a + 1 } : acc,
      { s, a: 0 })
);

const countLowerCase = createCounter(/[a-z]/);
const countDigits = createCounter(/[0-9]/);

// usage example
const { a } = countLowerCase   /* -- haskell equivalent   */
  .bind(n1 => countDigits      /* do n1 <- countLowerCase */
    .bind(n2 => StateMonad     /*    n2 <- countDigits    */
      .return_(n1 + n2)))      /*    return n1 + n2       */
  .runState("abc123ABC");


texts: Retrieving three separate sorted lists of items

texts:
I need to search for records based on their area, postcode, city and sort each group separately based on the value of their code field.

Table is as follows:

ID   Code Name    Area        PostCode   City
1    15    BV     Shore        343444    Toronto
2    2     BB     North        545555    London
3    3     AA     North        343444    Munich
4    4     KH     South Shore  959595    London
5    1     XX     North Shore  343444    Toronto

I want to show following list against 'North 343444 London':

2  BB   North         545555       London
3  AA   North         343444       Munich
--------------------------------------------
1  XX   North Shore   343444       Toronto
15 BV   Shore         343444       Toronto
--------------------------------------------
4  KH   South Shore   959595       London

BB and AA will be returned and sorted for matched area (PostCode and City are ignored)
XX, BV will be returned and sorted for matched postcode. (Area and City are ignored)
KH will be returned for matched city. (Area and Postcode are ignored)

As you can see code of XX is 1 but in result list it comes up after BB and AA because it is sorted in its own group (XX and BV).

In controller I have:

List<Area> matchedArea = searchService.findAreaMatches(area);
List<Area> matchedPostcode = searchService.findPostcodeMatches(area);
List<Area> matchedCity = searchService.findCityMatches(area);

In the Service class I have:

@Override
@Transactional(readOnly = true)
public List<Area> findAreaMatches(String area){
     return searchRep.findAreaMatches(area);
}

@Override
@Transactional(readOnly = true)
public List<Area> findPostcodeMatches(int postcode){
     return searchRep.findPostcodeMatches(postcode);
}

@Override
@Transactional(readOnly = true)
public List<Area> findCityMatches(String city){
     return searchRep.findCityMatches(city);
}

Is there any better approach to this? Is that fine to have three different methods in which each has its own @Transactional annotation?


texts: Asking the user to select a test subject and difficulty level

texts:
I'm currently in the early stages of a Python project, and the program (so far) asks the user what test they would like to take and what difficulty they would like it to be, and I'd like to know if there're any optimisations that I could make.

class NotWork(Exception): pass
class DoWork(Exception): pass

def which_test(real_dif, real_test, give_test):
    if difficulty == real_dif and test == real_test:
        give_test()

def is_it_correct(variable, subdif1, subdif2, subdif3, message):
    if variable != subdif1 and variable != subdif2 and variable != subdif3:
        print(message)
        raise NotWork
    else:
        raise DoWork

while True:
    try:
        test = str(input("What test do you want to take? Computer Science, History or Music? ").strip().lower())
        is_it_correct(test, "computer science", "history", "music", """\nSorry, you didn’t input valid settings. Please enter (without the quotes) either "Computer Science", "History", or "Music".\n""")
    except NotWork:
        continue
    except DoWork:
        break

while True:
    try:
        difficulty = str(input("Do you want to take the test in easy, medium or hard? ").strip().lower())
        is_it_correct(difficulty, "easy", "medium", "hard", """\nSorry, you didn't input valid settings. Please enter (without the quotes) either "Easy", "Medium", or "Hard".\n""")
    except NotWork:
        continue
    except DoWork:
        break

which_test("easy", "computer science", easy_CS)
which_test("medium", "computer science", medium_CS)
which_test("hard", "computer science", hard_CS)
which_test("easy", "history", easy_history)
which_test("medium", "history", medium_history)
which_test("hard", "history", hard_history)
which_test("easy", "music", easy_music)
which_test("medium", "music", medium_music)
which_test("hard", "music", hard_music)


texts: Using  instead of other tag types (, , etc)

texts:
Is it considered bad style to always use
 instead of using, say, ? I know that using specific tags like span better convey the purpose of the node, but is it actually frowned upon to always use div instead?

For example, if I were to have an inline style:

Hello, my name is
John Doe

Hello, my name is John Doe

Where the name-div class would have display: inline set. Is either way considered fine or is there a commonly accepted preference?

Edit:

Here is an actual example so that maybe this won't be off-topic:

You have been online for 30 days.

Where the desired output is something like:

You have been online for 30 days.

(i.e. the 30 has some special styling).

In this case, is it really considered "bad" to use a div with inline styling rather than span? I feel that arguments can be made either way in that span is obviously more accurately describing the function of that node, but you could also say it's preferable to minimize the variety of tags for the sake of consistency across browsers (and choose not to use things like em or strong in lieu of special styling on a div).


texts: Implementing a generic DropDownList attribute and templating solution

texts:
My goal was to be able to render my view models using a standard Object.cshtml editor and display template. In order to do so I needed to be able to always call Html.Editor(propertyName) or Html.Display(propertyName) in order to render the HTML element.

There were plenty of resources for creating custom attributes and custom editor templates. However I ran into a wall when creating the DropDownListAttribute and template since I needed to obtain the values for the select list as well as set the selected item based on the current instance of the view model.

Here is the reference I used to create the custom ModelMetadataProvider and custom attributes.

Here is the problem I ran into with getting the current instance of the view model.

It turns out using reflection here to access the view model is not safe. Depending on how you iterate over the property metadata the view model can sometimes be null.

Here is my implementation using the resource referenced above. This is a simple version that only uses a List<string> for the DropDownList. Using this example it would be trivial to use dictionaries and set the text/value properties:

View Model:

public class PhoneNumberViewModel
{
    // ... normal properties and attributes
    [DropDownList("ContactTypes")]  // <-- This is the important one!
    public string ContactType { get; set; }
    public static IEnumerable<string> ContactTypes
    {
        get
        {
            return new List<string>()
            {
                "Home", "Work", "Mobile"
            }
        }
    }
}

DropDownListAttribute Implementation

public class DropDownListAttribute : MetadataAttribute
{
    private string _items;

    public DropDownListAttribute(string items)
    {
        _items = items;
    }

    public override void Process(System.Web.Mvc.ModelMetadata modelMetaData)
    {
        modelMetaData.AdditionalValues.Add("Items", _items);
        modelMetaData.TemplateHint = TemplateHints.DropDownList; // Just a const string
    }
}

Custom HTML Helper used to render elements that need access to the view model instance

@Html.ContextualEditor(propertyName)

ContextualEditor HTML Helper Implementation

public static MvcHtmlString ContextualEditor(this HtmlHelper html, string expression)
{
    var model = html.ViewData.Model;
    var propertyMetadata = html.ViewData.ModelMetadata.Properties.Where(x => x.PropertyName == expression).Single();
    switch (propertyMetadata.TemplateHint)
    {
        case TemplateHints.DropDownList:
            var items = (IEnumerable<string>)model.GetType().GetProperty((string)propertyMetadata.AdditionalValues["Items"]).GetValue(model, null);
            var selectedValue = (string)model.GetType().GetProperty(expression).GetValue(model, null);
            var selectList = new TagBuilder("select");
            selectList.MergeAttribute("id", expression);
            selectList.MergeAttribute("name", expression);
            var options = new StringBuilder();
            foreach (var item in items)
            {
                var option = new TagBuilder("option");
                option.InnerHtml = item;
                if (item == selectedValue)
                    option.MergeAttribute("selected", "selected");
                options.Append(option.ToString());
            }
            selectList.InnerHtml = options.ToString();
            return MvcHtmlString.Create(selectList.ToString());
        default:
            return System.Web.Mvc.Html.EditorExtensions.Editor(html, expression);
    }
}

Please let me know what you think of the implementation. I'd be interested to know if anyone has found a more elegant way of achieving this result.


texts: Best approach on handling function that returns either a promise or just synchronous code

texts:
I wrote some code and I'm trying to get some feedback on it. I'll try to summerize the essential only. I have a function that based on a condition returns a promise or something else:

this.isActive = function(){
  if(this.disableApplePay && window.ApplePaySession){
    return window.ApplePaySession.canMakePaymentsWithActiveCard(this.merchantId).then(function(response){
      return response;
    });
  }
  return !!(window.ApplePaySession && window.ApplePaySession.canMakePayments() &&
    window.ApplePaySession.supportsVersion(3));
}

Then I call this function to check isActive() in another few methods like this:

Promise.resolve(this.isActive()).then(function(response){
  if(response){
    //execute code here
  }
});

Is the Promise.resolve() in this case following best practice? Is there a better way to deal with the isActive() function?

PS: Let's exclude the async await for the sake of the above example please.


texts: Are there any memory issues with this Eigen QR wrapper?

texts:
I am writing a wrapper to Eigen QR for my personal use and I am wondering if there are any memory leaks or undocumented behavior in my implementation, especially in the function get_QR().

The answer is as expected. This is related to my previous question here.

using std::cout;
using std::endl;
using namespace Eigen;

/*!
 Obtains the QR decomposition as A=QR, where all the matrices are in Eigen MatrixXd format.
 */
void get_QR(MatrixXd A, MatrixXd& Q, MatrixXd& R) {

        int m           =       A.rows();
        int n           =       A.cols();
        int minmn       =       min(m,n);

        //      A_E     =       Q_E*R_E.
        HouseholderQR<MatrixXd> qr(A);
        Q  =   qr.householderQ()*(MatrixXd::Identity(m, minmn));
        R  =   qr.matrixQR().block(0, 0, minmn, n).triangularView<Upper>();
}

/*!
 Obtains the QR decomposition as A=QR, where all the matrices are in double format.
 */
void get_QR(double* A, int m, int n, double*& Q, double*& R) {
        MatrixXd Q_E, R_E;
        int minmn       =       min(m,n);

        //      Maps the double to MatrixXd.
        Map<MatrixXd> A_E(A, m, n);

        get_QR(A_E, Q_E, R_E);

        Q       =       (double*)realloc(Q_E.data(), m*minmn*sizeof(double));
        R       =       (double*)realloc(R_E.data(), minmn*n*sizeof(double));
}

int main(int argc, char* argv[]) {
        srand(time(NULL));

        int m   =       atoi(argv[1]);
        int n   =       atoi(argv[2]);

//      Check the double version.
        int minmn       =       min(m,n);
        double* A       =       (double*)malloc(m*n*sizeof(double));
        double* Q       =       (double*)malloc(m*minmn*sizeof(double));
        double* R       =       (double*)malloc(minmn*n*sizeof(double));

        double RANDMAX  =       double(RAND_MAX);
        //      Initialize A as a random matrix.
        for (int index=0; index<m*n; ++index) {
                A[index]        =       rand()/RANDMAX;
        }

        get_QR(A, m, n, Q, R);
        std::cout << Q[0] << std::endl;

//      Check the MatrixXd version.
        Map<MatrixXd> A_E(A, m, n);
        MatrixXd Q_E, R_E;
        get_QR(A_E, Q_E, R_E);

        cout << Q[0] << endl;
        cout << Q_E(0,0) << endl;

        free(A);
        free(Q);
        free(R);
}

For instance, I get the output as

-0.360995
-0.360995
-0.360995


texts: SQL query for monthly bills with amounts paid

texts:
The idea is to get a listing of monthly bills with amounts paid. The subquery does a total through a group by using bill_id and party_id.

I wish to know how it can be improved. I'm not comfortable with JOINs and am willing to learn.

SELECT
    bill.id as bill_id,
    master.id as party_id,
    master.name as party_name,
    `amountExcVat`,
    bill.vat,
    amountExcVat + bill.vat as 'amtIncVat',
    `purchasedDate`,
    (SELECT SUM( cashPaid ) + SUM( chequePaid )
     FROM  `partypayment`
     WHERE party_id = partyId AND bill_id = partyBillId
     GROUP BY partyId, partyBillId)
    as 'Amount Paid(cash+chq)',
    bill.status
FROM `partybill` as bill, `partymaster` as master, partypayment as payment
WHERE
    bill.partyId = master.id
    AND
    bill.partyId = payment.id
    AND
    UPPER(MONTHNAME(`purchasedDate`)) = 'OCTOBER'
    AND
    YEAR(`purchasedDate`) = '2013'

Tables are as follows. They provided by a third party so I can't modify them.

create table partymaster (
id INT(4)
,name varchar(100) PRIMARY KEY
,address varchar(200)
,contactNo1 BIGINT(14)
,contactNo2 BIGINT(14)
);

create table partypurchase (
id  INT(10)
,partyId INT(4) references partymaster(id)
,head varchar(100)
,brand varchar(100)
,size varchar(10)
,costPrice INT(6)
,sellingPrice INT(6)
,quantity INT(4)
,totalCost INT(10)
,purchasedDate date
);

create table partybill (
id INT(10) PRIMARY KEY
,partyId INT(4) references partymaster(id)
,amountExcVat INT(10)
,vat INT(10)
,amountIncVat INT(10)
,purchasedDate date
,expectedPaymentDate date
,status varchar(10)
);

create table partypayment (
id INT(10) PRIMARY KEY
,partyId INT(4) references partymaster(id)
,partyBillId INT(10) references partybill(id)
,cashPaid INT(10)
,chequePaid INT(10)
,chequeBankName varchar(50)
,chequeNumber INT(10)
,chequeDate date
,paymentDate date
);


texts: Emulating the React.js createElement function

texts:
I am trying to create a helper function for myself, and this helper should do the following:

Create an element
Add properties to the element
Set values to the element (this is the concern of my question)
Add children nodes to the element

I am trying to emulate the React.js createElement function.

Here's what I have so far--and it works (by the way, I'm using ES6):

createElement: (type, props, children) => {
    let el = document.createElement(type),
        key;

    for (key in props) {
        if (props.hasOwnProperty(key)) {
            if (helpers.shouldAssignVal(key)) {
                el[key] = props[key];
            } else {
                let attr = helpers.camelCaseToDash(key),
                    i = 0;

                if (helpers.isArray(props[key])) {
                    for (i; i < props[key].length; i++) {
                        el.setAttribute(attr, props[key][i]);
                    }
                } else {
                    el.setAttribute(attr, props[key]);
                }
            }
        }
    }

    if (typeof children !== 'undefined') {
        if (helpers.isArray(children)) {
            for (let y = 0; y < children.length; y++) {
                if (children[y].nodeType) {
                    el.appendChild(children[y]);
                }
            }
        } else {
            el.appendChild(children);
        }
    }

    return el;
}

In practice:

let h1 = helpers.createElement('h1', {
    class: 'title',
    id:'title,
    innerText: 'This is a title' // This part will NOT set an attribute, but will set the value of the innerText property of this node.
});

The above renders:

This is a title

Now to my question...

I know that when creating elements in JavaScript, some properties are assigned as some kind of a value, whereas others are assigned as a property on the element.

A classic example of this is innerText and id, as used in our example. If I tried to do h1.setAttribute('innerText', 'foo'), the
 tag would render with a innerText attribute, which I don't want.

I have watched for this case in my code, and I handle it accordingly.

The only problem is that I don't know of all the scenarios in which this applies. The only ones I can think of and have in my code (in the helpers.shouldAssignVal() call above), is what's in that function here:

shouldAssignVal: key => {
    return key === 'value' || key === 'innerText' || key === 'innerHtml';
}

What are all of the keys on a JavaScript node that are assigned like node.key = 'foo', as opposed to node.setAttribute(key, 'foo')?


texts:
This program will filter the input by replacing matching bad words with "Bleep!". I'd like the code to be more concise and C++ style where possible. One thing that bugs me is the was_bad flag I think is needed to skip printing a word that has matched one of my bad words - if there was some better way to skip the rest of the while loop upon encountering a bad word so I don't print Bleep! poop, for instance.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main(void)
{
    int i, was_bad = false;
    string input, bad[] = {"poop", "balls"};
    vector <string> badwords(bad, bad + sizeof(bad) / sizeof(string));

    while (cin >> input)
    {
        for (i = 0; i < badwords.size(); ++i)
            if (badwords[i] == input)
            {
                cout << "Bleep! ";
                was_bad = true;
                break;
            }

        if (!was_bad)
            cout << input << " ";

        was_bad = false;
    }

    return 0;
}

One thing that did strike me was to use a ternary operator:

while (cin >> input)
{
    for (i = 0; i < badwords.size(); ++i)
        if (badwords[i] == input)
        {
            is_bad = true;
            break;
        }

    cout << (is_bad ? "Bleep! " : input + " ");

    is_bad = false;
}


texts:
/**
 *    View_message
 *    Object Model
 */

var View_message = function(div)
{
    this.div = document.getElementById(div);
};

View_message.prototype.messages =
{
    empty: 'Please complete all fields',
    empty_bm: 'Please enter both a title and url',
    name: 'Only letters or dashes for the name field',
    email: 'Please enter a valid email',
    same: 'Please make emails equal',
    taken: 'Sorry that email is taken',
    pass: 'Please enter a valid password, 6-40 characters',
    validate: 'Please contact support to reset your password',
    url:  'Pleae enter a valid url'
};

View_message.prototype.display = function(type)
{
    this.div.innerHTML = this.messages[type];
};

And the Call

obj_view = new View_message('test_id');
obj_view.display('empty');


texts: Java util to compare if time beyond cutoff

texts:
I have a to write a simple utility function that given a time in CST and a date in PST, tells if the date is today and if the current time is less than the cutoff (post converting cutoff to PST).

This is my attempt (highly childish but I seriously don't get Java date-time at all). If anyone could help me improve this code, I would be highly grateful.

  /**
   * Returns true if:
   *   - availableDate is today
   *   - currentTime is less than cutoff time
   * False otherwise
   *
   * @param cutoffTimeStr HH:mm format, CST timezone
   * @param availableDate YYYYMMDD format, PST timezone
   * @return true/false
   */
  public Boolean test(String cutoffTimeStr, String availableDate) throws ParseException{
    DateFormat availableDateFormat = new SimpleDateFormat("YYYYMMDD", Locale.ENGLISH);
    Date avlDate = availableDateFormat.parse(availableDate);
    avlDate.setHours(new Date().getHours());
    avlDate.setMinutes(new Date().getMinutes());
    //Compose current time with the given date

    DateFormat cutOffFormat = new SimpleDateFormat("HH:mm");
    cutOffFormat.setTimeZone(TimeZone.getTimeZone("CST"));
    Time cutOffTime = new java.sql.Time(cutOffFormat.parse(cutoffTimeStr).getTime());
    //cutOffTime is PST version of given CST time

    Date currentDateWithCutoffTime = new Date();
    currentDateWithCutoffTime.setHours(cutOffTime.getHours());
    currentDateWithCutoffTime.setMinutes(cutOffTime.getMinutes());
    //Today's date with time as cutoff

    if(avlDate.before(currentDateWithCutoffTime)){
      return true;
    } else{
      return false;
    }
  }

I have assumed that the availableDate will always be today or greater than today and thus, if its before the currentDateWithCutoffTime, we can return true.


texts: Optimizations for this user-account HTML structure?

texts:
I need a valid and semantic HTML structure for the user-account (user-panel) section of the overall layout of my web application.

What I saw in other web apps include:

User title (or email, or username)
A thumbnail (on which you can click to change your picture)
A notifications icon (with the number of notifications in red)
An arrow besides the whole area (which shows a menu to have further options for your user account settings)

Here is the HTML I've come up with:

    Saeed Neamati

Current User

        2

First Notification

Second Notification

Change your password

Subscription settings

Payments


texts:
Remove an event listener after firing once or any number of times

This is what I have:

/*jslint browser: true, vars: true, white: true, maxerr: 50, indent: 4 */
(function ()
{
    "use strict";

    function removeEventListenerAfterFiring(numberOfTimes, callback, useCapture)
    {
        var count = 0;
        return function listener(event)
        {
            count += 1;

            if (count >= numberOfTimes)
            {
                event.target.removeEventListener(event.type, listener, useCapture);
            }

            callback();
        };
    }

    function functionName()
    {
        // Code here.
    }

    window.addEventListener("DOMContentLoaded", removeEventListenerAfterFiring(1, functionName, false), false);
}());

Is there anything that could be improved, or is there a better way to do this?

Is it acceptable to specify useCapture twice? Is there a way to detect if useCapture has been specified so that I don't have to pass it to the removeEventListenerAfterFiring function?


texts:
Please review and suggest improvements for my isPrefixOf implementation.

isPrefixOf' :: (Eq a) => [a] -> [a] -> Bool
isPrefixOf' [] _ = False
isPrefixOf' _ [] = False
isPrefixOf' (x:xs) (y:ys)
  | null xs && x == y = True
  | x == y            = isPrefixOf' xs ys
  | otherwise         = False

Also, I wrote isSuffixOf baesd on isPrefixOf. It seems debatable to me whether it's clear to understand. Is it idiomatic?

isSuffixOf' :: (Eq a) => [a] -> [a] -> Bool
isSuffixOf' xs ys = isPrefixOf' (reverse xs) (reverse ys)

--isSuffixOf "foobar" "bar" == isPrefixOf "raboof" "rab"


texts:
Input :

{translate} Dear Atteck {/translate}

{translate}Please complete registration
 {/translate}

Output :

 Дeaр Аттeҗк
Плeaсe җомплeтe</һ5>

Main code:

private static readonly Dictionary<string, IOrderedEnumerable<KeyValuePair<string, string>>> TransliterationMaps = new Dictionary<string, IOrderedEnumerable<KeyValuePair<string, string>>>();

static void Main(string[] args)
{
    Transliterate();

    const string source = "
{translate} Dear Atteck {/translate}

{translate}Please complete
 {/translate} ";

    var splitData = Regex.Split(source, "{/");
    string alldata = string.Empty;

    foreach (var splt in splitData)
    {
        var data = splt.Split(new[] { "{translate}" }, StringSplitOptions.None);

        if (data.Count() > 1)
        {
            data[0] = Regex.Replace(data[0], "[translate}]", string.Empty);
            var result = TransliterationMaps["tatartocyrillic"].Aggregate(data[1], (current, map) => current.Replace(map.Key, map.Value));
            alldata += data[0] + result;
        }
    }
    Console.WriteLine(alldata);
}

Transliterate() method

public static void Transliterate()
{
    var tatarToCyrillicMap = new Dictionary<string, string>();
    tatarToCyrillicMap.Add(('\u0079' + "" + '\u0075').ToString(CultureInfo.InvariantCulture), '\u044e'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add(('\u0059' + "" + '\u0075').ToString(CultureInfo.InvariantCulture), '\u042e'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add("YU", '\u042e'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add("yü", '\u044e'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add("Yü", '\u042e'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add("YÜ", '\u042e'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add(('\u0079' + "" + '\u0061').ToString(CultureInfo.InvariantCulture), '\u044f'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add("YA", '\u042f'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add(('\u0059' + "" + '\u0061').ToString(CultureInfo.InvariantCulture), '\u042f'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add("YO", '\u0451'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add(('\u0079' + "" + '\u006f').ToString(CultureInfo.InvariantCulture), '\u0451'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add(('\u0059' + "" + '\u006f').ToString(CultureInfo.InvariantCulture), '\u0401'.ToString(CultureInfo.InvariantCulture));
    tatarToCyrillicMap.Add(('\u0079' + "" + '\u00e4').ToString(CultureInfo.InvariantCulture), '\u044f'.ToString(CultureInfo.InvariantCulture));
    .......................
    ...................
    ...............
    .........

    TransliterationMaps.Add("tatartocyrillic", tatarToCyrillicMap.OrderByDescending(m => m.Key));
}

Can this code be optimized?


texts:
What my code does

I am building an Express API server with mongoDB as my database.

I have a list of players which must be added to 2 mongoDB collections (teamList and countryList).

The data schema is similar. My code is as follows.

Data Model model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var teamSchema = new Schema({
  teamid: {
    type: String,
    required: true
  },
  created: {
    type: Date
  },
  lastUpdated: {
    type: Date,
    default: Date.now,
    required: true
  },
  playerList: [{
    name: {
      type: String,
      required: true,
      unique: true
    },
    dateAdded: {
      type: Date,
      default: Date.now
    }
  }]
});

module.exports = mongoose.model('teamModel', teamSchema);

var countrySchema = new Schema({
  countryid: {
    type: String,
    required: true
  },
  created: {
    type: Date
  },
  lastUpdated: {
    type: Date,
    default: Date.now,
    required: true
  },
  playerList: [{
    name: {
      type: String,
      required: true,
      unique:true
    },
    dateAdded: {
      type: Date,
      required: true
    }
  }]
});
module.exports = mongoose.model('countryModel', countrySchema);

Router router.js

module.exports = function(app) {
  const teamControllerv1 = require('../v1/controller/teamController');
  const countryControllerv1 = require('../v1/controller/countryController');
  app.route('/v1/team').post(teamControllerv1.addPlayerToTeam);
  app.route('/v1/country').post(countryControllerv1.addPlayerToCountry);
};

Controllers
countryController.js

var mongoose = require('mongoose');
const countryModel = mongoose.model('countryModel');

exports.addPlayerToCountry = function (req, res) {
    countryModel.update({
        countryid: req.body.countryID
      }, {
        $addToSet: {
          countryList: {
            $each: req.body.playerList
          }
        }
      }, {
        upsert: true
      },
      function (err, data) {
        if (!err && data) {
          util.successResponder(res, successText);
        } else {
          util.serverErrorResponder(res, errorOccured);
        }
      });
}

teamController.js

var mongoose = require('mongoose');
const TeamModel = mongoose.model('teamModel');

exports.addPlayerToTeam = function (req, res) {
    teamModel.update({
        teamid: req.body.teamID
      }, {
        $addToSet: {
          teamList: {
            $each: req.body.playerList
          }
        }
      }, {
        upsert: true
      },
      function (err, data) {
        if (!err && data) {
          util.successResponder(res, successText);
        } else {
          util.serverErrorResponder(res, errorOccured);
        }
      });
}

Problem I am trying to solve

As you can see this code clearly violates DRY. Except the mongoose database connector, everything else in the 2 files is exactly the same. How can I write this in a cleaner way such that the db connector is abstracted away?


texts: Extract multiple attributes values in XML tags

texts:
I have a XML file (test.xml) that can be sum up as follow (I filtered it so it will be more readable):

<coverage complexity="0" line-rate="0.66" lines-covered="66" lines-valid="100">
    <packages>
        <package complexity="0" line-rate="0.66" name=".">
            <classes>
                <class complexity="0" name="file_a.py" line-rate="0.7674">
                <class complexity="0" name="file_b.py" line-rate="0.2727">
                <class complexity="0" name="file_c.py" line-rate="1">
            </classes>
        </package>
    </packages>
</coverage>

For each line, I want to extract both name and line-rate info, for example output could be:

. 0.66
file_a.py 0.7674
file_b.py 0.2727
file_c.py 1

Note that I'll like to skip the 1st line since it as no name field.

Right now I managed to get that output with the following bash script:

#!/bin/bash

# Extract info in lines containing either "<package " or "<class "
linerates=`grep '<package \|<class ' test.xml | awk -F "line-rate=" '{print $2}' | awk -F '"' '{$
names=`grep '<package \|<class ' test.xml | awk -F "name=" '{print $2}' | awk -F '"' '{print $2}$

# Transform to array
linerates=(${linerates// / })
names=(${names// / })

# Print table
for i in "${!names[@]}"
do
        echo ${names[$i]} ${linerates[i]}
done

Since the code is quite ugly, I wonder if there is a way to extract those two informations in a more elegant way, let say in one command line / without the need to use a for loop

Edit

I switch to python and got this:

from bs4 import BeautifulSoup as bs

with open('test.xml', 'r') as file:
    content = file.readlines()
    content = "".join(content)
    bs_content = bs(content, 'lxml')

list_ = list(bs_content.find('classes').children)
list_ = list(filter(lambda a: a != '\n', list_))

for c in list_:
    print(c.get('name'), c.get('line-rate'))

The output is a bit reduced (but I'm OK with it)

file_a.py 0.7674
file_b.py 0.2727
file_c.py 1

I am still looking to do it using a single command line but for now I will go with the python version

Edit (following greybeard's comment)

I filtered my XML file to remove all unnecessary lines (none of them have attributes name nor line-rate). E.g of removed lines:

<lines>
     <line hits="1" number="1"/>
</lines>

Not much complications my file is generated so the attributes should always be in the same order. Coverage, package and class have more attributes. E.g. for "coverage" also has a timestamp and a version attributes ; "class" has a filename attribute which is the same as name

Feel free to ask if I forgot some other information


texts:
Brevity is for kings as it requires context and context is for kings. Me.

GitHub and NuGet

How many times you have been writing something like this passing those tedious logger/token parameters?

interface IMyService
{
    void Method1(…, ILogger logger, CancellationToken token);
    void Method2(…, ILogger logger, CancellationToken token);
    …
}

Enough is enough. Please see here about ambient logging. Below is about ambient cancellation.

What we are about to do is to use a special Cancellation helper class like this:

    static void Main(string[] args)
    {
        using (new Cancellation())
        {
            Task.Run(PingAsync);
            ReadLine();
            Cancellation.Request();
            ReadLine();
        }
    }

    static async Task PingAsync()
    {
        try
        {
            while (!Cancellation.Requested)
            {
                await Task.Delay(100, Cancellation.Token);
                WriteLine("Ping");
            }

            Cancellation.ThrowIfRequested();
        }
        catch(OperationCanceledException)
        {
            WriteLine("Ping cancelled");
        }
    }

Where Cancellation is defined as:

public class Cancellation : IDisposable
{
    static AsyncLocal<CancellationTokenSource> Context { get; } =
        new AsyncLocal<CancellationTokenSource>();

    public Cancellation()
        : this(CancellationToken.None)
    {
    }

    public Cancellation(CancellationToken cancellationToken)
        : this(cancellationToken, Timeout.InfiniteTimeSpan)
    {
    }

    public Cancellation(int timeout)
        : this(TimeSpan.FromMilliseconds(timeout))
    {
    }

    public Cancellation(TimeSpan timeout)
        : this(CancellationToken.None, timeout)
    {
    }

    public Cancellation(CancellationToken cancellationToken, int timeout)
        : this(cancellationToken, TimeSpan.FromMilliseconds(timeout))
    {
    }

    public Cancellation(CancellationToken cancellationToken, TimeSpan timeout)
    {
        Parent = Context.Value;
        Context.Value = CancellationTokenSource
            .CreateLinkedTokenSource(cancellationToken);

        Context.Value.CancelAfter(timeout);
    }

    public void Dispose()
    {
        var cts = Context.Value;
        Context.Value = Parent;
        cts.Dispose();
    }

    CancellationTokenSource Parent { get; }
    public static CancellationToken Token =>
         Context.Value?.Token ?? CancellationToken.None;

    public static void Request() => Context.Value?.Cancel();
    public static bool Requested => Token.IsCancellationRequested;
    public static void ThrowIfRequested() => Token.ThrowIfCancellationRequested();
}


texts: duplicated operator(or attribute) on the same input control - v-model and @change

texts:
I wrote a code like below - It is nuxt.js, which is one of the Vue frameworks. This code will be expected to

When change event triggered, update data value. There would be some logic to alter passed data
At the same time, it connected with data value to apply input box changing

<template>
  <div>
    <!-- I got question here -->
    <input type="text" ref="receiver" @change="applyData('receiver')" v-model="deliveryInfo.receiver" />
    <button type="button" @click="test">TEST</button>
  </div>
</template>
<script>
  export default {
    data: function () {
      return {
        deliveryInfo: {
          receiver: ''
        }
      }
    },
    methods: {
      applyData: function (refName) {
        let ref = this.$refs[refName];
        if (ref) {
          let temp = {};
          temp[refName] = ref.value;
          this.applyAddress(temp);
        } else {
          console.log("There is no " + refName + " in this.$refs");
        }
      },
      applyAddress: function (options) {
        this.deliveryInfo = Object.assign({}, this.deliveryInfo, options);
        this.$emit('applyChildData', this.deliveryInfo);
      },

      test: function () {
          console.log('set John Doe');
        this.deliveryInfo = Object.assign({}, this.deliveryInfo, {receiver: 'John Doe'});
        console.log('After change ', this.deliveryInfo);
        // It triggers applyData method and change input element value
        // But when I remove v-model in input value, it is not working
      }
    }
  }
</script>

And it works as expected.

However, using v-model and @change at the same tag looks weird to me since both of tag manipulates the connected value(in this case, it would be deliveryInfo.receiver)

Is this code OK to use in production project?
Thanks!

FYI, in my real case, it applied to a phone number. I want to show a phone number without dashes in a browser, but data should be saved with dashes.

So when people type in the input, @change alter data to insert dashes.


texts: Breadth First Search implementation in Python 3 to find path between two given nodes

texts:
This is my Breadth First Search implementation in Python 3 that assumes cycles and finds and prints path from start to goal.

Some background - Recently I've been preparing for interviews and am really focussing on writing clear and efficient code, rather than just hacking something up like I used to do.

This is another step in that direction when I'm revisiting some basic algorithms and trying to write best implementations of them as I can from my knowledge and obviously some help and explanations from internet. Any criticism would be helpful. I've tried to make the code as readable and efficient as I could.

from collections import deque

def bfs(graph, start, goal):
    if start == goal:
        print([start])
        return

    queue = deque([start])

    # dict which holds parents, later helpful to retreive path.
    # Also useful to keep track of visited node
    parent = {}
    parent[start] = start

    while queue:
        currNode = queue.popleft()
        for neighbor in graph[currNode]:
            # goal found
            if neighbor == goal:
                parent[neighbor] = currNode
                print_path(parent, neighbor, start)
                return
            # check if neighbor already seen
            if neighbor not in parent:
                parent[neighbor] = currNode
                queue.append(neighbor)
    print("No path found.")

def print_path(parent, goal, start):
    path = [goal]
    # trace the path back till we reach start
    while goal != start:
        goal = parent[goal]
        path.insert(0, goal)
    print(path)

if __name__ == '__main__':
    graph = {'A': set(['B', 'C']),
             'B': set(['A', 'D', 'E']),
             'C': set(['A', 'F']),
             'D': set(['B']),
             'E': set(['B', 'F']),
             'F': set(['C', 'E'])}

    bfs(graph, 'D', 'F')


texts:
In one of my object I needed a sequence I would use to increment an Id field just like we often do with classical databases. As I have not found a suitable solution, I wrote one. This solution uses objectify.

The first approach I came with was to have a class with a static AtomicInteger field like this:

public class MySequence {
  static AtomicInteger sequence = new AtomicInteger(0);
}

I would then just call it each time I need it.

Problem:

Every time the server is restarted, the sequence is too. So we need to persist the last value.

Second approach:

Persist the last value with objectify:

 public class MySequence {
        private static AtomicInteger sequence = new AtomicInteger(0);

        private static List<PersistSequence> l = null;

private static PersistSequence newPs = null;
    /**
     * @param user_id the id of the user we want to get the last value of the sequence
     * @return last value of PersistSequence
     */
    public static int getNextValue( String user_id){
        if( sequence.get() == 0){//first time we run it or it has been restarted
            l = ofy().load().type( PersistSequence.class).filter("user_id", user_id).limit(1).list();//grabs PersistSequence object bounded to user_id
            if( l != null){
                int dataStoreSeq = -1;
                if ( l.size() > 0) dataStoreSeq = l.get(0).getLastId();
                if ( dataStoreSeq > sequence.get()) sequence.set( dataStoreSeq);
                persistCounter( user_id, sequence.incrementAndGet());
                return sequence.get();
            }else{
                persistCounter( user_id, sequence.incrementAndGet());
                return sequence.get();
            }
        }else{
            persistCounter( user_id, sequence.incrementAndGet());
            return sequence.get();
        }
    }

    /**
     * @param user_id the id of the user
     * @param lastId last used Id
     */
    private static void persistCounter( String user_id, int lastId){
        //we only want one PersistSequence object per user so we delete the previous one before saving the new PersistSequence object
        List<Key<PersistSequence>> keys = ofy().load().type(PersistSequence.class).filter("user_id", user_id).keys().list();
        ofy().delete().keys(keys).now();
        //save the new one
        newPs = new PersistSequence();
        newPs.setLastId(lastId);
        newPs.setUserId(user_id);
        ofy().save().entities( newPs).now();
        }
    }

I am happy with this code as it works well. However, I wonder if it still will rock if there is a high volume of users calling it.


texts: Disabling the delete() method in Django managers and querysets

texts:
I had problems with related objects not deleted when deleting objects in bulk in Django, so I disabled the delete() method in Django managers and querysets. I also disabled bulk_create().
from django.contrib.auth import models as django_auth_models
from django.db import models

class QuerySet(models.query.QuerySet):
    def delete(self):
        raise NotImplementedError("delete is not implemented.")

class ManagerMixin(object):
    def bulk_create(self, *args, **kwargs):
        raise NotImplementedError("bulk_create is not implemented.")

    def delete(self):
        raise NotImplementedError("delete is not implemented.")

    def get_queryset(self):
        """
        Use our own QuerySet model without method .delete().
        """
        return QuerySet(model=self.model, using=self._db, hints=self._hints)

class BaseManager(ManagerMixin, models.Manager):
    pass

class BaseUserManager(ManagerMixin, django_auth_models.BaseUserManager):
    pass

These classes (BaseManager and BaseUserManager) are used for managers or base classes to inherit for managers in my models (one of them, not both). For example, UserManager is defined like this:
class UserManager(BaseUserManager):

I added tests to the models to test it works:
def test_cannot_create_users_with_bulk_create(self):
    user_1 = User(slug='zzzzzz')
    user_2 = User(slug='ZZZ-ZZZ')
    with self.assertRaises(NotImplementedError) as cm:
        User.objects.bulk_create([user_1, user_2])
    self.assertEqual(first=str(cm.exception), second="bulk_create is not implemented.")

def test_cannot_delete_users_with_queryset_delete(self):
    with self.assertRaises(NotImplementedError) as cm:
        User.objects.delete()
    self.assertEqual(first=str(cm.exception), second="delete is not implemented.")
    with self.assertRaises(NotImplementedError) as cm:
        User.objects.all().delete()
    self.assertEqual(first=str(cm.exception), second="delete is not implemented.")
    with self.assertRaises(NotImplementedError) as cm:
        User.objects.filter(pk=1).delete()
    self.assertEqual(first=str(cm.exception), second="delete is not implemented.")
    with self.assertRaises(NotImplementedError) as cm:
        User.objects.all().exclude(pk=2).delete()
    self.assertEqual(first=str(cm.exception), second="delete is not implemented.")

What do you think about this solution?


texts:
I created this basic metaball visualization in JavaScript. While it does look nice, it is very slow if you increase number of balls and/or make drawing area larger. I think that the performance is so bad because it iterates through every pixel every time the frame is updated but I cannot think anyway how I could update only those pixels where something has actually happened.

Here's the code:

// canvas

var c = document.getElementById("canvas");
width = c.width = /*window.innerWidth;*/1280;
height = c.height = /*window.innerHeight;*/720;
var ctx = c.getContext("2d");

// imagedata

var imageData = ctx.createImageData(width,height);
var data = imageData.data;

// array for balls

var balls = [];
var num = 20;

// random number generation

function random(min, max){
 var num = Math.floor(Math.random()*(max-min+1)+min);
 return num;
}

// metaball

function ball() {
 this.posX = random(0, width);
 this.posY = random(0, height);
 this.dx = random(-4,4);
 this.dy = random(-4,4);
 this.radius = random(10, 100);
}

// ball movement

ball.prototype.move = function() {

 if (this.posX > width || this.posX < 0) { // change direction if edge is encountered, x-axis
  this.dx = -(this.dx);
 }

 if (this.posY > height || this.posY < 0 ) { // change direction if edge is encountered, y-axis
  this.dy = -(this.dy);
 }

 this.posX += this.dx; // move balls, x-axis
 this.posY += this.dy; // move balls, y-axis

}

// create balls and put them into an array

for (i=0; i<num;i++) {
 var metaball = new ball();
 balls.push(metaball);
}

// draw and move metaballs

function Loop(){

 for (var y=0; y<height; y++) {  // loop through draw area pixels, height
  for (var x=0; x<width; x++) { // loop through draw area pixels, width
   var index = (x+y*width)*4; // pixel index
   var color = 0;    // pixel color

   for (i=0; i<balls.length; i++) {
    color += balls[i].radius * 10000 / (Math.pow((x - balls[i].posX),2) + Math.pow((y - balls[i].posY),2)); // metaball calculation formula
   }

    // assign color to pixel based on previous formula
    data[index+0] = color*1.05; // r
    data[index+1] = color;  // g
    data[index+2] = color*1.4; // b
    data[index+3] = 255;  // a
   }
 }

 // move balls

 for (i=0; i<balls.length; i++) {
  balls[i].move();
 }

 // put imagedata on canvas

 ctx.putImageData(imageData, 0,0);

 // animate

 requestAnimationFrame(Loop);
}

// call loop function

Loop();
<!DOCTYPE html>
<html>
<head>
 <title>metaballs</title>

<style type="text/css">

 body {
  padding: 0px;
  margin: 0px;
 }

</style>

</head>
<body>

<div>
 <canvas id="canvas">
 </canvas>
</div>

<script type="text/javascript" src="metaballs.js">
</script>

</body>
</html>

Is there anything I can do to optimize this?

Since I'm a total beginner in JavaScript and programming in general, I would be very happy to hear if there are better practices than what I've used here :)


texts:
Problem:

  Source (with example): https://leetcode.com/problems/island-perimeter/

  You are given a map in form of a two-dimensional integer grid where 1
  represents land and 0 represents water.

  Grid cells are connected horizontally/vertically (not diagonally). The
  grid is completely surrounded by water, and there is exactly one
  island (i.e., one or more connected land cells).

  The island doesn't have "lakes" (water inside that isn't connected to
  the water around the island). One cell is a square with side length 1.
  The grid is rectangular, width and height don't exceed 100. Determine
  the perimeter of the island.

Below is my solution. I haven't coded in Java since college and I'm trying to pick it up again. How is my style and is there any new Java features I can apply to the method to make it more concise? Thank you in advance!

Code:

class Solution {
    private int m;
    private int n;

    public int islandPerimeter(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        int perimeter = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    perimeter += getPerimeter(i, j, grid);
                }
            }
        }
        return perimeter;
    }

    private int getPerimeter(int i, int j, int[][] grid) {
        int perimeter = 0;
        if (i == 0 || grid[i-1][j] == 0) {
            perimeter++;
        }
        if (j == 0 || grid[i][j-1] == 0) {
            perimeter++;
        }
        if (i == m-1 || grid[i+1][j] == 0) {
            perimeter++;
        }
        if (j == n-1 || grid[i][j+1] == 0) {
            perimeter++;
        }
        return perimeter;
    }
}


texts:
The createReport method takes around 30 seconds to execute and I was wondering how I could optimize it. I'm using the Interop.Excel class and the workbook I'm importing to is very formula intensive.

Dim UserDate As New Data_Entry_Form.UserDate
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim xlSourceRange, xlDestRange As Excel.Range
Dim path As String = Application.StartupPath
Dim dt As New DataTable
Public Sub New()

End Sub
Sub createReport(dt As DataTable) ' this procedure determines the flow of the excel manipulation'
    openfile("2012 Master.xlsx")
    debugging(False)
    putfilesIntoYTD(dt)
    save("test.xlsx")
    closexl()
    cleanup()
    MsgBox("fin")
End Sub
Sub closexl()
    xlWorkBook.Close()
    xlApp.Quit()
End Sub
Sub cleanup() ' Releases all of the com objects to object not have excel running as a process after this method finishes'
    GC.Collect()
    GC.WaitForPendingFinalizers()
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSourceRange)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
    xlApp = Nothing
End Sub
Sub debugging(mode As Boolean) 'Determines if we want to display anything during the dubugging process'
    If mode = True Then
        xlApp.DisplayAlerts = True
        xlApp.Visible = True
    Else
        xlApp.DisplayAlerts = False
        xlApp.Visible = False

    End If
End Sub
Sub putfilesIntoYTD(dt As DataTable)
    'dt = CType(dbTools.getYTD(startDate, endDate), DataTable)'
    Dim fileNum() As String = convertColumntoArray(dt, 0)
    Dim dateRecorded() As String = convertColumntoArray(dt, 1)
    Dim closerAndTypeCode() As String = convertColumntoArray(dt, 2)
    xlSourceRange = xlWorkSheet.Range("N2:N" & fileNum.Length)
    xlSourceRange.Value = fileNum
    xlSourceRange = xlWorkSheet.Range("O2:O" & dateRecorded.Length)
    xlSourceRange.Value = dateRecorded
    xlSourceRange = xlWorkSheet.Range("P2:P" & closerAndTypeCode.Length)
    xlSourceRange.Value = closerAndTypeCode

End Sub

Function convertColumntoArray(dt As DataTable, columnIndex As Integer) As String() ' Converts a single column of an datatable into an array of strings'
    Dim array(dt.Rows.Count) As String
    If columnIndex = 1 Then
        For i As Integer = 0 To dt.Rows.Count - 1
            array(i) = CDate(dt.Rows(i)(columnIndex).ToString()).Date
        Next
    Else
        For i As Integer = 0 To dt.Rows.Count - 1
            array(i) = dt.Rows(i)(columnIndex).ToString()
        Next
    End If
    Return array
End Function

Sub save(filename As String) ' Saves the sheet under a specfic name'
    xlWorkSheet.SaveAs(path & "/" & filename)
End Sub

Sub openfile(filename As String) ' opens the excel file under a specfic type'
    xlApp = New Excel.Application()
    xlWorkBook = xlApp.Workbooks.Open(path & "/" & filename)
    xlWorkSheet = CType(xlWorkBook.Sheets("1"), Excel.Worksheet)
    'xlWorkSheet.Activate()
End Sub


texts:
The parser below is not designed for every single US address.  I am parsing through a file where each line may or may not be an address.  I am more focused on speed rather than robustness.

state-abbreviation-lookup and street-suffix-lookup are booth used for consistency (addresses will always be "ST" instead of "STREET" or "STR")
find-last-occurence-index-of searches through a list of string and finds the last string that matches a key in a hash-map.  This is used with state-abbreviation-lookup and street-suffix-lookup to find where in the address the state and or street is.
split-string removes commas, capitalizes everything and then splits on whitespace.

Next in the code is some checks for invalid values.  I finally have to split the address into the appropriate parts: street, city, state, zipcode.

Overall, it feels like too much is going on, but I'm not sure how best to make it the most Clojure-like.

(def
 ^{:const true
   :source "https://www.usps.com/send/official-abbreviations.htm"}
  state-abbreviation-lookup
  (hash-map
    "AL" "AL"
    "ALABAMA" "AL"
    "AK" "AK"
    "ALASKA" "AK"
    ;... removed for brevity
    ))

(def
 ^{:const true
   :source "https://www.usps.com/send/official-abbreviations.htm"}
  street-suffix-lookup
  (hash-map
    ;... removed for brevity
    "STREET" "ST"
    "ST" "ST"
    "STR" "ST"
    "STRT" "ST"
    ;... removed for brevity
    ))

(defrecord UsAddress [street city state zipcode])

(letfn
  [(find-last-occurence-index-of [lookup-map coll]
    (last (keep-indexed #(when (contains? lookup-map %2) %1) coll)))
   (split-string [s]
    ((comp #(clojure.string/split % #"\s+")
                     clojure.string/upper-case
                     #(clojure.string/replace % #"," ""))
     s))]
(defn extract-us-address [s]
  (let [parts (split-string s)]
    (when (re-matches #"^\d{5}$" (last parts))
      (let [state-index (find-last-occurence-index-of state-abbreviation-lookup parts)
            street-index (find-last-occurence-index-of street-suffix-lookup parts)]
        (when (and state-index street-index)
          (UsAddress.
            (clojure.string/join " " (take (inc street-index) parts))
            (clojure.string/join " " (drop (inc street-index) (take state-index parts)))
            (state-abbreviation-lookup (nth parts state-index))
            (last parts))))))))

Tests:

(deftest extract-us-address-test
  (testing "extract-us-address"
    (testing "should determine if string is a US address"
      (are [i o] (= (extract-us-address i) o)
        "3526 HIGH ST SACRAMENTO CA 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 HIGH ST SACRAMENTO, CA 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 HIGH ST SACRAMENTO California 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 HIGH ST SACRAMENTO, California 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 high st sacramento ca 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 high st sacramento, ca 95838"  (UsAddress. "3526 HIGH ST" "SACRAMENTO" "CA" "95838")
        "3526 CALIFORNIA ST SACRAMENTO CA 95838"  (UsAddress. "3526 CALIFORNIA ST" "SACRAMENTO" "CA" "95838")
        "3526 CALIFORNIA ST SACRAMENTO, CA 95838"  (UsAddress. "3526 CALIFORNIA ST" "SACRAMENTO" "CA" "95838")
        "3526 AVENUE ST SACRAMENTO CA 95838"  (UsAddress. "3526 AVENUE ST" "SACRAMENTO" "CA" "95838")
        "3526 AVENUE ST SACRAMENTO, CA 95838"  (UsAddress. "3526 AVENUE ST" "SACRAMENTO" "CA" "95838")
        "California"  nil
        "CA"  nil
        ""  nil
        "SACRAMENTO"  nil
        "95838"  nil
        "3526 HIGH STREET"  nil
        "304 867 5309" nil))))


texts: Using an IEnumerator without a foreach loop in order to simulate a state machine

texts:
I am working with an object that needs to run an ExecuteEffect() method. Sometimes, the ExecuteEffect() only needs to run once, while in other cases, the ExecuteEffect() needs to keep running once / frame until some criteria is met (in my example, a real-time delay).

To solve this, I used an IEnumerator:

public override IEnumerator<bool> ExecuteEffect()
    {
        if(delay > 0)
        {
            if(executionStart == -1m)
            {
                executionStart = GetRealTime();
                yield return false;
            }
            if(GetRealTime() > executionStart + delay)
            {
                DealDamage();
                yield return true;
            }
            else
            {
                yield return false;
            }
        }
        else
        {
            DealDamage();
            yield return true;
        }
  }

Then, when I'm running ExecuteEffect(), if the IEnumerator<bool> returns false, it gets added to a list of objects that is continuously checked until their ExecuteEffect() method returns true.

GenericEffect ge = GetEffect();
IEnumerator<bool> temp = ge.ExecuteEffect();
temp.MoveNext();
if(!temp.Current)
{
    //Foo not finished, add to list of active Foo
    activeEffects.Add(ge);
}

and, elsewhere:

activeEffects.RemoveAll( s =>
                         {
                               IEnumerator<bool> temp = s.ExecuteEffect();
                               temp.MoveNext();
                               if(temp.Current)
                               {
                                   return true;
                               }
                               else
                               {
                                  return false;
                               }
                          });

This all feels very wordy, especially the temp variable to hold the IEnumerator<bool> and the explicit call to GetNext(). And, of course, I have no idea if this is an utter butchering of the intended uses of IEnumerator<T>.

Is there a better way to get this kind of effect? Or is this just an unconventional (albeit valid) use of IEnumerator<T>?


texts:
I would like to get some feedback on my AS3 code below. It's for an Adobe Air mobile app to preload a website in a StageWebView container.
That container will be moved on screen later in the app process. My goal is to show the website content to the user as fast as possible.

// OFF SCREEN - PRELOAD
var webView:StageWebView = new StageWebView();
webView.stage = this.stage;
webView.viewPort = new Rectangle( -5000, 0, stage.stageWidth, stage.stageHeight);
webView.loadURL("http://www.example.com/foobar.php");

// ONSCREEN
function showWeb(e:Event=null){
webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight);
}

btn.addEventListener(MouseEvent.CLICK,  showWeb)

Is there something I could do better?
I'm using Adobe Air 3.6 and Flash CS6.

Thank yoo


texts:
I created a simple todo kind of app using JavaScript. It is working fine but the code which I wrote is not proper. Please review my code and improve it if it is needed.

$(function () {
    var todo = new Todo('contents');

    $('.addBtn').on('click', function() {
        var name = $(this).parent().find('input[type="text"]').val();
        todo.add(name);
    });

    $('.contents').on('click', '.remove', function() {
        var el = $(this).parent();
        todo.remove(el);
    });

    $('.contents').on('click', '.update', function() {
        var dom = $(this);
        todo.addUpdateField(dom);
    });

    $('.contents').on('click', '.updateBtn', function() {
        var el = $(this);
        todo.update(el);
    });
});

Here is my todo.js file

var Todo = function(c) {
    var contents = $('.' + c),
    name;

    add = function (name) {
        if(name != "") {
            var div = $('

');
            div.append('' + name + '');
            div.append("<button class='update' class='update'>Edit</button>");
            div.append("<button class='remove' name='remove'>Remove</button>");
            contents.prepend(div);
            $('.name').val('').focus();
        }
        return;
    },

    addUpdateField = function (dom) {
        var name = dom.parent().find('span').text(),
            field = $('<input type="text" value="' + name + '" />'),
            update = $('<button class="updateBtn">Update</button>');

        return dom.parent().html('').append(field).append(update);
    },

    update = function(el) {
        var val = el.parent().find('input').val();
        el.parent().html('' + val + '')
        .append('<button class="update" class="update">Edit</button>')
        .append('<button class="remove" class="remove">Remove</button>');
    },

    remove = function (el) {
        return el.remove();
    };

    return {
        add             : add,
        update          : update,
        remove          : remove,
        addUpdateField  : addUpdateField
    };
};


texts:
To do password exchange on the SQL server I need to use SHA-1 to generate a hash (no plain password exchange).
This is done differently on Linux/Mac so I abstracted it slightly.
ThorCryptWrapper.h
#ifndef THORS_ANVIL_MYSQL_DETAILS_THOR_CRYPTO_WRAPPER_H
#define THORS_ANVIL_MYSQL_DETAILS_THOR_CRYPTO_WRAPPER_H

#ifdef  __APPLE__
#define COMMON_DIGEST_FOR_OPENSSL
#include <CommonCrypto/CommonDigest.h>
#define THOR_SHA1(data, len, dst)   CC_SHA1(data, len, dst)
#else
#include <openssl/sha.h>
#define THOR_SHA1(data, len, dst)   SHA1(data, len, dst)
#endif

namespace ThorsAnvil
{
    namespace MySQL
    {

typedef unsigned char           ThorSHADigestStore[SHA_DIGEST_LENGTH];

inline void thorSHA1(ThorSHADigestStore& dest, ThorSHADigestStore& src)
{
    THOR_SHA1(src, SHA_DIGEST_LENGTH, dest);
}

inline void thorSHA1(ThorSHADigestStore& dest, std::string const& src)
{
    THOR_SHA1(reinterpret_cast<const unsigned char*>(&src[0]), src.length(), dest);
}

    }
}

#endif


texts: Inserting filename, reading data, inserting regex, and testing if each line matches - version 2

texts:
This is a improved version of the program seen in my older question.

This program first displays a menu which shows some options that the user can select. Each option will the respective functions which do some things.

The user can insert a filename, read data from it, enter a regex pattern, test if each line of the file matches the given regex pattern.

Please provide feedback on how I can improve my program.

import re

def test_data(readData, regex):
    '''Checks if each line of data matches the regex'''

    if not regex:
        print('Empty regex')
        print('')
        return

    try:
        pattern = re.compile(regex)
    except:
        print('Invalid regex')
        print('')
        return

    if not readData:
        print('Read data is empty')
        print('')
        return

    for i, line in enumerate(readData, 1):
        line = line.strip()  #Strip off the newline character from each line
        if pattern.match(line):
            print(' Line ', i, ':"', line,'"', ' matches current regex', sep='')
        else:
            print(' Line ', i, ':"', line,'"', ' does not match current regex', sep='')
    print('')

def change_regex(regex):
    '''Sets the regex variable'''

    regex = '"%s"' % regex if regex else 'empty'
    print('Current regex is', regex)

    regex = input('Enter new regex: ')
    print('')
    return regex

def read_file(filename):
    '''Reads data from file if possible'''

    try:
        with open(filename, "r") as file:
            readData = file.readlines()
            print('Data read successfully!')
            return readData
    except TypeError:
        print('filename is empty!')
    except FileNotFoundError:
        print('File not found!')

    print('')

def change_filename(filename):
    '''Sets the filename variable'''

    filename = '"%s"' % filename if filename else 'empty'
    print('Current filename is', filename)

    filename = input('Enter new filename (with extension): ')
    print('')
    return filename

def main():
    filename = regex = readData = None
    while True:
        print('Enter 1 to change filename')
        print('Enter 2 to read file')
        print('Enter 3 to change regex')
        print('Enter 4 to test if read data matches given regex')
        print('Enter 5 to exit')

        try:
            option = int(input('Option: '))
        except:
            print('Invalid input')
            print('Please enter a valid option')
            print('')
            continue

        if option == 1:
            filename = change_filename(filename)
        elif option == 2:
            readData = read_file(filename)
        elif option == 3:
            regex = change_regex(regex)
        elif option == 4:
            test_data(readData, regex)
        elif option == 5:
            break
        else:
            print('Invalid input')
            print('Please enter a valid option')
            print('')

if __name__ == "__main__":
    main()


texts: An extension method to get the current user

texts:
I think that everyone is familiar with the concept of a context (such as HttpContext in ASP.NET) where you can put some shared resources and take them back later in another module (I think the most used scenario is current/logged in user information).

Well it's obvious that usually these contexts are generic (and in a strong typed languages such as C# you should access their members using keys) and thus we have to write codes like this al the time :

var user=(User)HttpContext.Current.Items["CurrentUser"];

This code has some problems in my opinion:

Use of magic keys (we should always use constants instead of in-line strings)
Possible null reference exception (either by misspelling the key or a missing key)
Value always should cast to original value

In other words a developer should know a lot of things in order to write this line of code.

There's no doubt that we should re-factor our code so we can prevent upcoming problems.

One solution might be having a static member of a common class that every other module can call such as:

public class UserController
{
       public static User GetCurrentUser()
       {
             return (User)HttpContext.Current.Items["CurrentUser"];
       }
}

Actually we just move our repeated code to one single place as you can see therefore we can control all aspects of it (exception management and casting) in one place and now our fellow developers can write codes like this:

var user=UserController.GetCurrentUser();

Nice and easy, but is there any way to pretend that GetCurrentUser was a member of current module?

To do that we can have all our modules to be inherited from the same base class but I don't think that is a good idea because inheritance always makes a solution more complex specially in languages like C# with no multiple inheritance.

Then I thought: what if we could have an extension method that we could use in our modules? Something like this:

public static User GetCurrentUser(this IUserInfoConsumer self)
{
       return (User)HttpContext.Current.Items["CurrentUser"];
}

As you can see IUserInfoConsumer is a marker interface to mark our modules/components as a consumer of user information (it has no members) so that in every class that has this maker interface we can write a code like this:

var user=this.GetCurrentUser();

I would like to know what you think about this approach. Any other ideas?


texts:
Each client application would send a filepath and search term to the server. The server then takes that file path reads the file and returns any lines that contain the search term, the server then watches the file for any size increase and if the new lines contain wanted information it gets transmitted.

The first for loop is echoing the initial message to make sure that it is correct it also validates that the file path is a file.

There are some odd bits that are mostly for if a log gets rotated while a connection is active.

My planned upgrades will include better exception handling, I know there are a couple places where if something goes wrong, it'll just throw you into an infinite while loop. There is some other stuff I'll need to fix but you know I'm here for your perspective, not the other way.

import asyncio, socket, os
HOST = "127.0.0.1"
PORT = 65432

async def log_transmit(reader, writer):
    try:
        print('new connect')
        data, datval, fpath = '', '', ''
        #ensuring communication of filepath and search term
        while 1:
            data = (await reader.read(128))
            print(f'{fpath} {datval}')
            if data.decode('utf-8').strip() == 'recv' and os.path.isfile(fpath):
                break

            else:
                datval = data.decode('utf-8').strip()
                l = datval.split()
                if len(l) == 2:
                    fpath, datval = [x for x in l]
                writer.write(data)
                await writer.drain()

        file = open(fpath, 'r')
        line = file.readline()

        # reading to the end of the file
        while line != '':
            if datval in line:
                line += ' ' * (256 - len(line.encode()))
                writer.write(line.encode())
                await writer.drain()
            line = file.readline()

        size = os.path.getsize(fpath)
        # looking for new file entries
        while 1:
            await asyncio.sleep(0.1)
            try:
                newsize = os.path.getsize(fpath)
            # handling log rotation
            except FileNotFoundError:
                while os.path.isfile(fpath) == False:
                    pass
                file = open(fpath, 'r')
            if newsize > size: # new entries need to be examined
                file.seek(size)
                line = file.readline()
                while line != '':
                    size += len(line)
                    if datval in line:
                        line = line.strip()
                        line += ' ' * (256 - len(line))
                        writer.write(line.encode())
                        await writer.drain()

                    file.seek(size)
                    line = file.readline()

            elif newsize < size:
                # more log rotation handling
                await asyncio.sleep(2)
                file = open(fpath, 'r')
                size = newsize
          # else file hasn't changed nothing to be done

    except ConnectionResetError:
        print('client disconnected')
        file.close()
        writer.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.create_task(asyncio.start_server(log_transmit, HOST, PORT))
    loop.run_forever()


texts: ASP.NET Core singleton with a thread-safe property that can be changed

texts:
Thanks to ASP.NET Core dependency injection, there's no need to follow the Singleton pattern; any class will do.
What I want to do is to have a class that will store a value that'll be used by another methods inside the app. A specific class is in charge of updating this value. What I'm concerned is the problem of a thread reading the value while the specific class updates it, given that I haven't done enough concurrency to feel confident.
So I came up with this. Is it correct for what I want it to do?
public class DynamicValueStore
{
    private readonly object _lock_obj;

    private string _value;

    public string Value
    {
        get
        {
            lock (_lock_obj)
            {
                return _value;
            }
        }
    }

    public DynamicValueStore()
    {
        _lock_obj = new object();
        _value = string.Empty;
    }

    public void UpdateValue(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new ArgumentNullException(nameof(value));
        }
        lock (_lock_obj)
        {
            _value = value;
        }
    }
}
```


texts: Multiplication table using a list comprehension

texts:
I have just started reading through Learn you a Haskell I got up to list comprehension and started to play around in GHCi, my aim was to make a times table function that takes a number n and an upper limit upperLimit and return a nested list of all the 'tables' up to n for example

> timesTable 2 12
[[1,2..12],[2,4..24]]

the actual function/list comprehension I came up with is

> let timesTable n upperLimit = [[(n-y) * x | x <- [1..upperLimit]] | y <- reverse [0..(n-1)]]

Any feedback on the above would be greatly appreciated as this is the first time I have really used a functional language, so if there is a better way or something I have missed please let me know.


texts:
I am refactoring my controllers, trying to improve the way common data is loaded for the actions. Initially, I was using before_filter methods to do this but read that helper methods were preferred.

class CategoriesController < ApplicationController
  before_filter :authenticate_user!

  helper_method :category, :categories, :organisation

  # GET /categories
  def index
  end

  # GET /categories/new
  def new
  end

  # GET /categories/1/edit
  def edit
  end

  # POST /categories
  def create
    if category.save
      redirect_to(
        categories_path(oid: organisation.id),
        notice: I18n.t("category.create.success"))
    else
      render action: :new
    end
  end

  # PUT /categories/1
  def update
    if category.update_attributes(params[:category])
      redirect_to(
        categories_path(oid: organisation.id),
        notice: I18n.t("category.update.success"))
    else
      render action: :edit
    end
  end

  # DELETE /categories/1
  def destroy
    begin
      category.destroy
      redirect_to(
        categories_path(oid: organisation.id),
        notice: I18n.t("category.delete.success"))
    rescue ActiveRecord::DeleteRestrictionError
      redirect_to(
        categories_path(oid: organisation.id),
        alert: I18n.t("category.delete.failure.foreign_key"))
    end
  end

  private
  # Gets the category being operated on.
  #
  def category
    return @category unless @category.nil?

    if params[:id]
      @category = Category.find_by_id(params[:id])
    elsif params[:category]
      @category = Category.new(params[:category])
    else
      @category = Category.new({organisation_id: organisation.id})
    end
  end

  # Gets the organisation of the Category.
  #
  # If no Category exists (e.g. in the case of actions index
  # and new) there will be a querystring parameter 'oid' indicating the
  # Organisation.
  #
  def organisation
    return @organisation unless @organisation.nil?

    if params[:oid]
      @organisation = Organisation.find_by_id(params[:oid])
    elsif params[:category]
      @organisation = Organisation.find_by_id(
        params[:category][:organisation_id])
    elsif !category.nil?
      @organisation = category.organisation
    else
      @organisation = nil
    end
  end

  # Gets the existing Categories for the organisation.
  #
  def categories
    return @categories unless @categories.nil?

    if !organisation.nil?
      @categories = Category
        .where(organisation_id: organisation.id)
        .order(:name)
        .all
    else
      @categories = nil
    end
  end
end


texts:
I have a situation where I needed to convert NSNumber 2D array to Float 2D array, so I did it like this:

var numArr:[[NSNumber]]()
//fill values
let floatArr = numArr.map { $0.map { $0.floatValue} }

It's working fine, no issues!

But I wondering if there's any better way to handle this?


texts: Wrapping a CSV file for access and testing

texts:
I have a simple class that represents and accesses the data from a CSV file (using the CsvHelper library). I've tried restructuring the code to allow for better unit testing, but I'm sure the structure of the class could be better; both for testing and for using it (I'm not sure if there is any standard recommendations for these types of classes).

Here is the class code:

public class CsvCountFile
{
    public string AbsolutePath { get; }
    public string Delimiter { get; }

    public LocationDefinition LocationData { get; private set; }
    public List<CountDefinition> CountData { get; private set; }

    public CsvCountFile(string absolutePath, string delimiter = ",")
    {
        AbsolutePath = absolutePath;
        Delimiter = delimiter;
    }

    public void ReadCountData()
    {
        using (var fileReader = File.OpenText(AbsolutePath))
        {
            ReadCountData(fileReader);
        }
    }

    public void ReadCountData(TextReader fileReader)
    {
        CountData = new List<CountDefinition>();

        using (var csvReader = new CsvReader(fileReader))
        {
            csvReader.Configuration.HasHeaderRecord = false;
            csvReader.Configuration.RegisterClassMap<LocationMap>();
            csvReader.Configuration.RegisterClassMap<CountMap>();

            csvReader.Read(); // get header
            csvReader.Read(); // get first record
            LocationData = csvReader.GetRecord<LocationDefinition>();

            csvReader.Read(); // skip blank line
            csvReader.Read(); // skip second header section

            while (csvReader.Read())
            {
                var count = csvReader.GetRecord<CountDefinition>();
                CountData.Add(count);
            }
        }

    }
}

The ReadCountData was split into two so that the reading logic could be tested by forming a TextReader in memory, instead of needing an actual csv file. While this code works, I don't foresee any usage scenarios that would typically require reading the csv by passing in a TextReader.

Also, due to this structure, when CsvCountFile is constructed, the csv absolutePath is passed in, but testing using a TextReader doesn't require this, and it doesn't feel right instantiating it with an empty string.


texts:
I implemented sequenceA:

sequenceA :: Applicative f => [f a] -> f [a]
sequenceA []     = pure []
sequenceA (x:xs) = (++) <$> (fmap (\y -> [y]) x) <*> sequenceA xs

I don't like the fact that I'm making a new list, and then concatenating the result via ++.

However, I'm not sure how to make use of cons, i.e. :, in this function.

Please critique it.


texts: Gulp task to increment a major, minor, or patch level of the version number of the last build

texts:
Working codepen: http://codepen.io/leongaban/pen/oxwLzE?editors=1010

The function below takes in user entered text through the cli: V=patch gulp build

It then checks for the last version of the build folder, then iterates the appropriate version number.

Hoping to condense all the if/else into more functional code.

lastVersion starts as an empty string var lastVersion = '';

The ver value that is passed into this function from the user will be 1 of these commands:

V=major gulp build
V=minor gulp build
V=patch gulp build

So ver will be major, minor or patch...

function generateNextVersion(ver) {
    var major, minor, patch;
    var versionArray = lastVersion.split('.');

    major = parseInt(versionArray[0]);
    minor = parseInt(versionArray[1]);
    patch = parseInt(versionArray[2]);

    if (ver === 'major') {
        major = parseInt(versionArray[0]) + 1;
    }
    else if (ver === 'minor') {
        minor = parseInt(versionArray[1]) + 1;
    }
    else if (ver === 'patch') {
        patch = parseInt(versionArray[2]) + 1;
    }

    version = major + '.' + minor + '.' + patch;

    if (ver === '' || ver === undefined) {
        version = '0.0.0';
    }

    gutil.log(gutil.colors.blue.bold('##################################################'));
    gutil.log(gutil.colors.blue.bold('         Building Dashboard version '+version));
    gutil.log(gutil.colors.green.bold('~~           All change is detectable           ~~'));
    gutil.log(gutil.colors.blue.bold('##################################################'));
}


texts: Translate datetime format from one standard to another

texts:
In my python code, date formats are stored as "strftime and strptime syntax". For instance %d/%m/%Y %H:%M.

On the client side, I use pickadate.js which format is rather dd/mm/yyyy HH:i.

So I have to translate %d/%m/%Y %H:%M to dd/mm/yyyy HH:i before sending a datetime format to the client.

I first thought str.translate was the right tool for this. But actually, this is only for characters translation.

Then I thought about str.replace but it looks awful and inefficient to loop over str.replace:

def format_to_pickadate_format(fmt):
    trans_table = [
        ('%d', 'dd'),
        ('%a', 'ddd'),
        ('%A', 'dddd'),
        ('%m', 'mm'),
        ('%b', 'mmm'),
        ('%B', 'mmmm'),
        ('%y', 'yy'),
        ('%Y', 'yyyy'),
        ('%H', 'HH'),
        ('%M', 'i'),
        ('%p', 'A'),
    ]
    for trans in trans_table:
        fmt = fmt.replace(*trans)
    return fmt

So, to make it more elegant I used functools.reduce:

from functools import reduce

def format_to_pickadate_format(fmt):
    trans_table = [
        ('%d', 'dd'),
        ('%a', 'ddd'),
        ('%A', 'dddd'),
        ('%m', 'mm'),
        ('%b', 'mmm'),
        ('%B', 'mmmm'),
        ('%y', 'yy'),
        ('%Y', 'yyyy'),
        ('%H', 'HH'),
        ('%M', 'i'),
        ('%p', 'A'),
    ]
    return reduce(lambda x, y: x.replace(*y), trans_table, fmt)

But I think it still screams inefficiency. The string is browsed once for each sequence to replace if found.

Is there a way make it more efficient (ie. make the translation in only one iteration)?

  Note: This question is mainly for the sake of curiosity and learning. This is probably one of the least important thing I have to care about on my project, especially concerning performance.

  Obviously in this case, making it more efficient would be ridiculously imperceptible. If this helps you find an interest in this question, imagine another use case where I'd have a string of the size of an entire book, and a translation table of 10,000 or 100,000 entries. Doesn't it look dumb to read the book 10,000 or 100,000 times to make the translation?


texts: Servlet responses to upload/download requests

texts:
My task is to write a program to store files in object store. One of the subtasks requires to send json or xml format response to the file uploader/downloader as requested by client.
The following rules must be followed:

                         entry
               +-------------------------+
               v                         v
           upload                      download
       +-----------+              +--------------+
       v           v              v              v
    succ          err            succ           err
  +-----+       +-----+                       +-----+
  v     v       v     v                       v     v
json1  xml1    json2  xml2                  josn2  xml2

if user uploads file with success, return json/xml type 1
if user uploads file with error, return json/xml type 2
if user downloads file with success, don't change return object
if user downloads file with error, return json/xml type 2

I've managed to solve the task but I'm not satisfied with the class dependencies and nested if/else-s I have. I think mixture of abstract factory and strategy are suitable for the issue. Can you give me a hint on how I can deal with the problem?
My code snippet:
public Result upload(HttpServletRequest request) {
        UploadRequestParams uploadParams = UploadRequestParams.getObjectFrom(request);
        ... // create info object
        Result res = handleUploadRequest(uploadParams);

        Result result = jsonXml(info, res);
        return result;
    }

private Result jsonXml(RequestInfo info, Result result) {
        Serializer ser;
        if ("xml".equals(format)) {
            ser = new XmlSerializer();
        } else {
            ser = new JsonSerializer();
        }
        Result res = ser.serialize(info, result);

        return res;
    }

@Override
public Result serialize(RequestInfo info, Result result) { // json implementation
        GsonBuilder builder = new GsonBuilder();
        Gson g = builder.create();

        InputStream stream = null;
        InfoInterface wrap;
        if (info.isUpload()) {
            if (result.isValid()) {
                wrap = new InfoWrapperImpl1(info, result);
            } else {
                wrap = new InfoWrapperImpl2(info, result);
            }
        } else {
            wrap = new InfoWrapperImpl1(info, result);
        }
        String res = g.toJson(wrap);
        stream = new ByteArrayInputStream(res.getBytes(StandardCharsets.UTF_8));
        Result newRes = Result.getBuilder().setInputStream(stream).setResultCode(result.getResultCode()).build();
        return newRes;
    }

private class InfoWrapperImpl1 implements InfoInterface {
        private String fileName;
        private ResultCode code;

        public InfoWrapper1(RequestInfo info, Result res) {
            this.fileName = info.getUniqueName();
            this.code = res.getCode;
        }
    }

UML class diagram:

EDIT
I rewrote serialize method, but looks like to be bound to the parameters' implementation. Am I right? On the other, I got rid of the ugly nested classes.
@Override
    public Result serialize(RequestInfo info, Result result) {

        JsonObject body = new JsonObject();

        JsonObject resultCode = new JsonObject();
        resultCode.addProperty("code", result.getResultCode().getCode());
        resultCode.addProperty("value", result.getResultCode().getDescription());

        if (info.isUploadRequest() && result.isValid()) {
            body.addProperty(fileTag, info.getExtendedName());
            body.addProperty("checksum", result.getMySwiftObject().getEtag());
        }
        body.add(statusTag, resultCode);

        String jsonRes = body.toString();
        InputStream stream = new ByteArrayInputStream(jsonRes.getBytes(StandardCharsets.UTF_8));
        return Result.getBuilder().setInputStream(stream).setResultCode(result.getResultCode()).build();
    }


texts:
I want to limit the load so I rewrite the most expensive method and add caching, both memcache and cache-control:

class GeoRSS(webapp.RequestHandler):

    def get(self):
        start = datetime.datetime.now() - timedelta(days=60)
        count = (int(self.request.get('count'
                 )) if not self.request.get('count') == '' else 1000)
        memcache_key = 'ads'
        data = memcache.get(memcache_key)
        if data is None:
            a = Ad.all().filter('modified >',
                                start).filter('published =',
                    True).order('-modified').fetch(count)
            memcache.set('ads', a)
        else:
            a = data
        template_values = {'a': a, 'request': self.request,
                           'host': os.environ.get('HTTP_HOST',
                           os.environ['SERVER_NAME'])}
        dispatch = 'templates/georss.html'
        path = os.path.join(os.path.dirname(__file__), dispatch)
        output = template.render(path, template_values)
        self.response.headers["Cache-Control"] = "public,max-age=%s" % 86400
        self.response.headers['Content-Type'] = 'application/rss+xml'
        self.response.out.write(output)

Will this limit the load on my app? Did I prioritize correctly when I see the load on the app:


texts:
I know a module like this already exists on CPAN, but I wanted to write my own simplified version that accepts wildcards in the input.

I don't write many Perl modules so I figured I would post the code here and see if anyone could give me advice on how to make this code more efficient or user friendly.

I also included some POD documentation so you can use perldoc for usage information.

Please let me know what you think and leave some feedback on how this code could be improved!

package File::Copy::Recursive;

# Use statements
use File::Basename;
use File::Copy;
use File::Path qw(make_path remove_tree);
use strict;
use warnings;

# Link the version number with CVS
our ($VERSION) = (q$Revision: 1.1 $ =~ m{([0-9.]+)});

# Exporter
require Exporter;
our @ISA = qw(
    Exporter
);

# Declare exportable routines
our @EXPORT_OK = qw(
    recursive_copy rcopy
    recursive_move rmove
);

# Aliases to subroutines
sub rcopy { recursive_copy(@_); }
sub rmove { recursive_move(@_); }

# Recursive copy function
sub recursive_copy {
    my ($source, $destination) = @_;
    for my $path (glob $source) {
        if (-d $path) {
            make_path($destination.'/'.basename($path));
            recursive_copy($path.'/*', $destination.'/'.basename($path));
        }
        else {
            copy($path, $destination);
        }
    }
}

# Recursive move function
sub recursive_move {
    my ($source, $destination) = @_;
    for my $path (glob $source) {
        if (-d $path) {
            make_path($destination.'/'.basename($path));
            recursive_move($path.'/*', $destination.'/'.basename($path));
            remove_tree($path);
        }
        else {
            move($path, $destination);
        }
    }
}

1;

__END__

=head1 NAME

File::Copy::Recursive - Recursive copy and move functions.

=head1 VERSION

$Revision: 1.1 $

=head1 SYNOPSIS

  use File::Copy::Recursive;

  # Recursively copy a directory
  recursive_copy('input', 'output');

  # Recursively copy all contents of a directory
  recursive_copy('input/*', 'output');

  # Recursively move a directory
  recursive_move('input', 'output');

  # Recursively move all contents of a directory
  recursive_move('input/*', 'output');

=head1 DESCRIPTION

File::Copy::Recursive is designed to provide simple functions to recursively copy and move files.
These functions will accept wildcards (*) in the input.

=head1 SUBROUTINES/METHODS

=over

=item C<recursive_copy> or C<rcopy>

Recursive copy function.

  # Recursively copy a directory
  recursive_copy('input', 'output');

  # Recursively copy all contents of a directory
  recursive_copy('input/*', 'output');

=item C<recursive_move> or <rmove>

Recursive move function.

  # Recursively move a directory
  recursive_move('input', 'output');

  # Recursively move all contents of a directory
  recursive_move('input/*', 'output');

=back


texts: ForEach Methods Implementation for Multidimensional Array in C#

texts:
I am working with System.Array and I found that the input parameter of ForEach method public static void ForEach<T>(T[] array, Action<T> action); is specified on one dimensional array case. I am trying to generalize this to multidimensional array.
The experimental implementation
Here's the experimental implementation of generalized ForEach method.
class ArrayHelpers
{
    public static void ForEach<T>(Array array, in Action<T> action)
        where T : unmanaged
    {
        if (ReferenceEquals(array, null))
        {
            throw new ArgumentNullException(nameof(array));
        }

        if (ReferenceEquals(action, null))
        {
            throw new ArgumentNullException(nameof(action));
        }

        foreach (T item in array)
        {
            action.Invoke(item);
        }
        return;
    }
}

Test cases
The Test cases for one dimensional case, two dimensional case and three dimensional case are as below.
//    One dimensional case
Console.WriteLine("One dimensional case");
int[] test = new int[] { 1, 2, 3, 4 };
ArrayHelpers.ForEach<int>(test, ShowSquares);

//    two dimensional case
Console.WriteLine("Two dimensional case");
int[,] test2 = { { 0, 1 }, { 2, 3 } };
ArrayHelpers.ForEach<int>(test2, ShowSquares);

//    three dimensional case
Console.WriteLine("Three dimensional case");
int[,,] test3 = { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } };
ArrayHelpers.ForEach<int>(test3, ShowSquares);

/// <summary>
/// Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.foreach?view=net-5.0
/// </summary>
/// <param name="val">The input value for displaying and calculating square result</param>
private static void ShowSquares(int val)
{
    Console.WriteLine("{0:d} squared = {1:d}", val, val * val);
}

The output of the above tests:
One dimensional case
1 squared = 1
2 squared = 4
3 squared = 9
4 squared = 16
Two dimensional case
0 squared = 0
1 squared = 1
2 squared = 4
3 squared = 9
Three dimensional case
0 squared = 0
1 squared = 1
2 squared = 4
3 squared = 9
0 squared = 0
1 squared = 1
2 squared = 4
3 squared = 9

I am wondering the things about the potential drawback or risks of this implementation.
All suggestions are welcome.