texts: Should a Factory ever be generated per request?

texts:
I'm working with AutoFac to do some DI. I think I've got a decent grip on things, but just ran into a question I had with my code and thought I'd check:

public class AutofacRegistrations
{
    public static void RegisterAndSetResolver()
    {
        // Create the container builder.
        var containerBuilder = new ContainerBuilder();

        // Register the Web API controllers.
        containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        //  Only generate one SessionFactory ever because it is expensive.
        containerBuilder.Register(x => new NHibernateConfiguration().Configure().BuildSessionFactory()).SingleInstance();

        //  Everything else wants an instance of Session per HTTP request, so indicate that:
        containerBuilder.Register(x => x.Resolve<ISessionFactory>().OpenSession()).InstancePerApiRequest();
        containerBuilder.Register(x => LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType)).InstancePerApiRequest();

        //  TODO: I don't THINK I should actually be making a DAO factory per API request. I think the whole point of a Factory is to make them once.
        containerBuilder.RegisterType<NHibernateDaoFactory>().As<IDaoFactory>().InstancePerApiRequest();
        containerBuilder.RegisterType<StreamusManagerFactory>().As<IManagerFactory>().InstancePerApiRequest();

        // Build the container.
        ILifetimeScope container = containerBuilder.Build();

        // Create the depenedency resolver.
        var dependencyResolver = new AutofacWebApiDependencyResolver(container);

        // Configure Web API with the dependency resolver.
        GlobalConfiguration.Configuration.DependencyResolver = dependencyResolver;
    }
}

You can see that I am registering an NHibernateDaoFactory and a StreamusManagerFactory as InstancePerApiRequest. This doesn't feel right to me because I think creating a Factory is supposed to be a relatively expensive endeavour and they should probably be .SingleInstance() similiar to the ISessionFactory.

However, my NHibernateDaoFactory has a dependency on Session:

...

public NHibernateDaoFactory(ISession session)
{
    if (session == null) throw new NullReferenceException("session");

    Session = session;
}

public IErrorDao GetErrorDao()
{
    return ErrorDao ?? (ErrorDao = new ErrorDao(Session));
}

....

and my ManagerFactory has a dependency on the DaoFactory:

...

public StreamusManagerFactory(ILog logger, IDaoFactory daoFactory)
{
    if (logger == null) throw new NullReferenceException("logger");
    if (daoFactory == null) throw new NullReferenceException("daoFactory");

    Logger = logger;
    DaoFactory = daoFactory;
}

public IErrorManager GetErrorManager()
{
    return ErrorManager ?? (ErrorManager = new ErrorManager(Logger, DaoFactory.GetErrorDao()));
}

...

This leaves me having to create new factories per request. Is this correct?


texts: Lazily load permissions from database in multithreading environment

texts:
I would like to get the feedback about this code:

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

public class Utils {

    private final Set<String> permissionsSet = new HashSet<String>(50);
    private PlatformModuleModelLocator modelLocator = Lookup.getDefault().lookup(PlatformModuleModelLocator.class);

    public Boolean hasUserPermission(String permission) {
        synchronized (permissionsSet) {
            if (permissionsSet.isEmpty() && modelLocator.getUserSession() != null) {
                Queue<String> userPermissions = modelLocator.getUserSession().getUserPermissionsFromDB();
                for (String userPermission : userPermissions) {
                    permissionsSet.add(userPermission);
                }
            }
        }
        return permissionsSet.contains(permission);
    }
}

I've tried to fill Set only after first call in multi-threading environment. Can i do it without synchronized block? Please suggest some variants.

PS:  It's not from Utils actually, i've just copied this method from application class. PlatformModuleModelLocator returns user permissions like Queue strings. It can have duplicates and i have to iterate over this queue when i need to check permissions. So i decided optimize this block and put this lines to Set.

But it not so matter I look for effective method for lazy initialization collections. How can i initialize my Set after first call?


texts: How to refactor this importer to handle validation errors?

texts:
This is my importer to database from excel file. I would like to handle situations when any error raise. To not breaks whole import when one errors occurs.

For example when there is duplicated record and I have uniqueness validations. I would like to store this row id in errors table and inform about that at the end.

class DDImporter
  attr_accessor :file

  def initialize(path)
    @path = path
  end

  def open
    @file = Roo::Excelx.new(@path)
  end

  def sheets
    @file.sheets
  end

  def extract_sheets
    sheets.each do |sheet|
      unless sheet == ("risks" || "allergies_symptoms")
        extract sheet
      end
    end
  end

  def extract sheet_name
    @file.default_sheet = sheet_name

    header = file.row 1
    2.upto(file.last_row) do |i|
      row = Hash[[header, file.row(i)].transpose]
      # row.delete "id"
      object = sheet_name.classify.constantize
      object.create!(row)
    end
  end
end


texts: Lazy lists with transformations, using generators & iterators

texts:
I built this very-basic lazy list (I'll add more methods as I need them). You provide it an array, a generator or any iterator. It creates a lazy list, which lets you run a pipeline of transformations in a lazy manner, meaning that they'll only be applied as you pull values out of the list.

Here's the class:

class List {
    static range(start, end) {
        return new List(function* () {
            while (start <= end) {
                yield start++;
            }
        });
    }

    constructor(source) {
        if (typeof source == 'function') {
            this.generator = source;
        } else {
            this.generator = function* () {
                yield* source;
            };
        }
    }

    filter(predicate) {
        return new List(function* () {
            for (const item of this) {
                if (predicate(item)) {
                    yield item;
                }
            }
        }.bind(this));
    }

    map(mapper) {
        return new List(function* () {
            for (const item of this) {
                yield mapper(item);
            }
        }.bind(this));
    }

    take(size) {
        return new List(function* () {
            for (const item of this) {
                if (size--) {
                    yield item;
                } else {
                    break;
                }
            }
        }.bind(this));
    }

    *[Symbol.iterator] () {
        yield* this.generator();
    }

    toArray() {
        return [...this];
    }
}

Here's a simple example of how to use it:

List.range(1, 10 ** 9)
    .filter(number => number % 10 == 0)
    .map(number => 'Item ' + number)
    .take(5)
    .toArray();

Trying the same with a regular array:

Array.from({ length: 10 ** 9 }, (v, i) => i + 1)
     .filter(number => number % 10 == 0)
     .map(number => 'Item ' + number)
     .slice(0, 5);

...will run out of memory before it completes.


texts: Join and pivot multiple tables of securities data in MySQL

texts:
I'm interested in a way to join three (or more) tables in a way that is more efficient (both in terms of conciseness of code and in terms of generating the results) than what I have currently.

Underlying tables:

table ISIN
+---------------+----+------+
| isin          | id | code |
+---------------+----+------+
| US0378331005  |  1 | NULL |
| AU0000XVGZA3  |  2 | z    |
| GB0002634946  |  3 | y    |
+---------------+----+------+

table additionalCredit
+------+----+
| code | id |
+------+----+
| h    |  1 |
| i    |  2 |
+------+----+

table codes
+--------+------+----------------------+
| codeId | code | description          |
+--------+------+----------------------+
|   9    | h    | ETM - Principal Only |
|   9    | i    | ETM - Waiting Close  |
|   8    | z    | No Redemption        |
|   8    | y    | Partially Prerefunded|
+--------+------+----------------------+

Expected results:

+---------------+-----------------------+----------------------+
| isin          | type8                 | type9                |
+---------------+-----------------------+----------------------+
| US0378331005  | null                  | ETM - Principal Only |
| AU0000XVGZA3  | No Redemption         | ETM - Waiting Close  |
| GB0002634946  | Partially Prerefunded | null                 |
+---------------+-----------------------+----------------------+

Working Code

select
ISIN.isin,
min(type8), min(type9)
from
(select
ISIN.isin,
case when codes.codeId=8 then codes.description end as type8,
case when codes.codeId=9 then codes.description end as type9
from ISIN
left join codes
on ISIN.code=codes.code

union
select
ISIN.isin,
case when codes.codeId=8 then codes.description end as type8,
case when codes.codeId=9 then codes.description end as type9
from ISIN
left join additionalCredit ac
on ac.id=isin.id
left join codes
on codes.code=ac.code) as n
group by n.name

Context

...from the original Q&A at Stack Overflow that gives my thought process and steps taken, where the first commenter suggested there could be a better answer. Here's a fiddle.

Can you help me find a better way than a union statement (in which nearly the entire query is duplicated)?


texts: Legibility of code with ternary operators in Python

texts:
My lead developer has commented that the code I write is hard to understand and that I "overcomplicate things". I'm willing to accept this and improve but I'm not sure if this is genuinely the case or if his personal preferences are seeping into his judgement.

A red flag for me was the following situation: We're receiving database entries in the form of an array of dictionaries called columns. We then make HTML templating decisions based on their contents. Note that "special" types such as files or map coordinates are really text fields with an additional type_[name] array field for validation.

columns = someDBData
for column in columns:
    column_type = column['data_type']
    isValid = Someclass.perform_some_validation(column_type) # returns a boolean
    isCalendar = Someclass.is_calendar(column_type) # returns true if it's a time, datetime or datetime-local data type
    isString = Someclass.is_string(column_type) # ditto but with text, mediumtext or varchar

    isHidden = True if column['hidden'] != 0 else False
    isReadOnly = True if (configuracion_open == "" and column['open_insert'] == 0) or (configuracion_open == "Editando_registro" and column['open_edit'] == 0) else False
    isFile = True if column_type == "text" and column['type_file'] is True else False
    isGeo = True if column_type == "text" and column['type_geo'] is True else False
    isGeneric = True if isCalendar or isString and not isFile else False

   # repeat for other validations and then do templating stuff

When reviewing my work, he claimed that using "long ternary operators such as these" would be confusing for other people maintaining the code in the future. It seems as if he'd prefer to use a more verbose if/elif/else structure for readability, even though giving the program unnecessary verticality will also result in a readability problem in the future, at least in my opinion. In summary, should I reserve ternary operators for short and simple validations?


texts: Extracting min and max salary from string

texts:
What I want is to do is to extract min/max range of salary from a text which contains either hourly or annual salary.
import re

# either of the following inputs should work
input1 = "$80,000 - $90,000 per annum"
input2 = "$20 - $24.99 per hour"

salary_text = re.findall("[\$0-9,\. ]*-[\$0-9,\. ]*", input1)

if salary_text and salary_text[0]:
    range_list = re.split("-", salary_text[0])

    if range_list and len(range_list) == 2:
        low = range_list[0].strip(' $').replace(',', '')
        high = range_list[1].strip(' $').replace(',', '')

````


texts: Testing out a program that calculates the days left in the month

texts:
I'm new to coding C++ and I want to get some insight on my progress. Can you guys take a look at my program and give me some feedback on it?

#include <iostream>
using namespace std;

int main(){

int day{};
int monthNum{};
cout << "Calculate how many days are left in the month. \nPlease enter the month number and the day, seperated by a space. ex 1 22 for Jan 22nd: ";
cin >> monthNum >> day;

if (monthNum < 1 || monthNum > 12 || day < 1 || day > 31 || (monthNum == 2 && (day < 1 || day > 29))){
    cout << "Error, not a valid input. \nPlease make sure you're month and day are valid." << endl;
    return 0;
}

int daysInCurrentMonth{};
char leapYear;
int doNothing{};  //Used to do nothing if certain conditions are false

if (monthNum == 2){
    cout << "\nIs it leap year? Type y for yes and n for no. ";
    cin >> leapYear;
    ((leapYear == 'y') ? daysInCurrentMonth = 29 : daysInCurrentMonth = 28);
    if (leapYear != 'y' && leapYear != 'n'){
        cout << "invalid input..." << endl << endl;
        return 0;
    }else{
        doNothing = 0;
    }
}

cout << "\nYou entered day " << day << " of month " << monthNum << endl;

((monthNum == 4 || monthNum == 6 || monthNum == 9 || monthNum == 11) ? daysInCurrentMonth = 30 : doNothing = 0);
((monthNum == 1 || monthNum == 3 || monthNum == 5 || monthNum == 7 || monthNum == 8 || monthNum == 10 || monthNum == 12) ? daysInCurrentMonth = 31 : doNothing = 0);

int daysLeftInMonth{daysInCurrentMonth - day};
cout << "\nThere are " << daysLeftInMonth << " days left in the month." << endl;

cout << endl;
return 0;
}

This is my third iteration of this program. This is the tutorial series that I've been watching. I'm currently on section 9 and just finished learning about conditional operators. I'm trying to refine the project as I go along. Also, I know it's pretty early to be thinking about this, but if anyone is able to, I'd like to know if the way I structure this is in the right direction for becoming a professional programmer, i.e. it's easy to follow and is readable, or it looks like garbage.


texts: Writing a Python class that provides default instance succinctly

texts:
I have a Python class for which I'm often going to want an instance with the default arguments, but I want the class to allow creation of instances. For brevity I'd prefer that the default instance be accessible as a property, so that it can be accessed without a method call. However, the code to achieve this in the way I know how is complicated (see below); it feels too complicated for such a simple task. The solution that suggests itself to me is to give up on using properties (in my context a multiton would even work), but I wonder: is there a better way?

# https://stackoverflow.com/a/1383402/2829764
class ClassProperty(property):
    def __get__(self, cls, owner):
        return self.fget.__get__(None, owner)()

class Example:
    _default_instance = None

    def __init__(self, customizable=0):
        self.customizable = customizable

    def get_default_instance(cls):
        if cls._default_instance is None:
            cls._default_instance = cls()
        return cls._default_instance
    def set_default_instance(cls):
        raise NotImplementedError("Can't do this")
    default_instance = ClassProperty(classmethod(get_default_instance), classmethod(set_default_instance))

    def do_something(self):
        print("*** {} ***".format(self.customizable*2))

foo = Example(10)
foo.do_something()

foo.default_instance.do_something()

Output:

*** 20 ***
*** 0 ***

NOTE: I don't care about default_instance being read-only; that was just a byproduct of the ClassProperty code I used from https://stackoverflow.com/a/1383402/2829764.


texts:
I have a record type which holds a list of table rows. Each row is also a list. The first row is assumed to be the header row. In addition the type optionally defines a filter - a list of columns (the actual string value of the column header).

Then the type have a member property FilteredRows. If no filter is defined, the property is the entire table. But if there is a filter, FilteredRows return the list of rows, but only with the columns defined by the filter.

I'm not interested in alternative ways to represent this. This is part of a bigger solution, it's working, and the design makes sense to me. What I believe I need however is some more eyes on the internals of FilteredRows. I'm looking for clever tricks on solving this problem in different ways, and other pointers on how I can improve the solution.

type Table =
    {
        Rows : string list list
        OnlyColumns : string list option
    }
    member internal x.FilteredRows =
        match x.OnlyColumns with
        | None -> x.Rows
        | Some xs ->
            let indexesToInclude = seq {
                let headers = List.head x.Rows
                for c in xs do
                    yield List.findIndex ((=) c) headers }
            x.Rows
            |> List.map
                (fun row ->
                    indexesToInclude
                    |> Seq.map (List.nth row)
                    |> List.ofSeq )

As you can see, what I've done is first to fetch all the column indexes using List.findIndex. And then for each row I map over the column indices and re-create the row using List.nth.


texts:
Got this question in a test.

  Display the following number pattern using Java.

  User inputs number of rows. For example 3

1112
3222
3334

  For 5

111112
322222
333334
544444
555556

  and so on.

This is the solution I came up with:

   public static void NumberPattern(int n) {

    int myarray[][] = new int[n][n + 1];
    int i;
    int j;
    for (i = 0; i < 1; i++) //first row
    {
        for (j = 0; j < n; j++)
        {
            myarray[i][j] = i + 1;
        }
        myarray[i][n] = i + 2;
    }
    for (i = 1; i < myarray.length; i++)
       {
        if (i % 2 != 0)    //odd rows
           {
            j = 1;
            myarray[i][0] = i + 2;
            while (j <= n)
             {
                myarray[i][j] = i + 1;
                j++;
            }
            j = 1;
        }
        if (i % 2 == 0)   //even rows
        {
            j = 0;
            while (j < n) {
                myarray[i][j] = i + 1;
                j++;
            }
            myarray[i][n] = i + 2;
            j = 0;
        }
    }
    printArray(myarray);

}
 public static void printArray(int n[][])
  {
    System.out.println("The Pattern is:");

    for (int[] array : n) {
        for (int v : array) {
            System.out.print("  " + v);
        }
        System.out.println();
    }
  }

Is there a better way of solving this problem with only one for loop?


texts:
I have started the Hackerrank interview preparation kit. The first problem I have solved with Swift is as follows:

  Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting position to the last cloud.

  For each game, Emma will get an array of clouds numbered 0 if they are safe or 1 if they must be avoided.

func jumpingOnClouds(c: [Int]) -> Int {
    var jump = 0
    var location = 0
    repeat {
        if (location + 2 < c.count) &&
        (c[location + 2] == 0) {
            location += 2
        } else {
            location += 1
        }
        if location >= c.count {
            break
        }
        jump += 1
    } while location < c.count
    return jump
}

It's time complexity is \$O(n)\$. Are there any ways I could reduce this? I am also interested in improving the code quality. Are there ways I can take better advantage of Swift to improve my code?


texts:
I've implemented a functional-style list structure in C++. It seems okay so far, and doing custom allocation for list nodes improves performance greatly. I omitted that part here for simplicity.

The mutability of the list is intentional, as the application I'm thinking of requires a lot of state updates. I wrote this code instead of using std::forward_list because

I need to instantiate the list with incomplete types.
The algorithm is recursive (some kind of tree search), so the code will look better with a functional data structure.

Any advice is welcome.

#include <cstdlib>
#include <iostream>
#include <memory>

template<typename T>
struct List
{
    T head;
    std::unique_ptr<List<T>> tail;
};

template<typename T>
std::unique_ptr<List<T>> add(const T &t, std::unique_ptr<List<T>> &&l)
{
    return std::unique_ptr<List<T>>(new List<T>{t, std::move(l)});
}

template<typename T>
std::unique_ptr<List<T>> list()
{
    return std::unique_ptr<List<T>>();
}

template<typename T, typename ...Ts>
std::unique_ptr<List<T>> list(const T &t, const Ts &...ts)
{
    return add(t, list<T>(ts...));
}

template<typename T>
std::unique_ptr<List<T>> copy(const std::unique_ptr<List<T>> &l)
{
    if (l == list<T>())
    {
        return list<T>();
    }
    else
    {
        return add(l->head, copy(l->tail));
    }
}

template<typename T>
std::unique_ptr<List<T>> merge(const std::unique_ptr<List<T>> &a, const std::unique_ptr<List<T>> &b)
{
    if (a == list<T>())
    {
        return copy(b);
    }
    else
    {
        return add(a->head, merge(a->tail, b));
    }
}

template<typename T, typename Filter>
std::unique_ptr<List<T>> filter(const std::unique_ptr<List<T>> &l, Filter f)
{
    if (l == list<T>())
    {
        return list<T>();
    }
    else if (f(l->head))
    {
        return add(l->head, filter(l->tail, f));
    }
    else
    {
        return filter(l->tail, f);
    }
}

template<typename T>
std::unique_ptr<List<T>> sort(const std::unique_ptr<List<T>> &l)
{
    if (l == list<T>())
    {
        return list<T>();
    }
    else
    {
        return merge(sort(filter(l->tail, [&](const T &t){return t < l->head;})), add(l->head, sort(filter(l->tail, [&](const T &t){return t >= l->head;}))));
    }
}

template<typename T>
std::ostream &operator<<(std::ostream &os, const std::unique_ptr<List<T>> &l)
{
    if (l == list<T>())
    {
        return os;
    }
    else
    {
        return os << l->head << ' ' << l->tail;
    }
}

std::unique_ptr<List<int>> randomList(int n)
{
    if (n == 0)
    {
        return list<int>();
    }
    else
    {
        return add(std::rand() % 100, randomList(n - 1));
    }
}

int main()
{
    auto r = randomList(100);
    std::cout << r << '\n' << sort(r) << '\n';
}


texts: Winform that exports a datagrid to Excel

texts:
I've just created a winform that exports a datagrid to Excel. Originally the file was never shown, but I was asked to give the option. So I put in a checkbox and modified the code.

Is my if/else statement at the end enough or should I go about it a different way?

private void buttonExport_Click(object sender, EventArgs e)
{
    try
    {
        //copy contents of grid into clipboard, open new instance of excel, a new workbook and sheet,
        //paste clipboard contents into new sheet.
        copyGrid();
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Microsoft.Office.Interop.Excel.Application();
        xlexcel.Visible = false;
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
        xlWorkBook.SaveAs("C:\\Temp\\ItemUpdate.xls", Excel.XlFileFormat.xlExcel5);
        MessageBox.Show("File Save Successfull", "Information", MessageBoxButtons.OK);
        //If box is checked, show the exported file. Otherwise quit Excel.
        if (checkBox1.Checked == true)
        {
            xlexcel.Visible = true;
        }
        else
        {
            xlexcel.Quit();
        }
    }
    catch (SystemException ex)
    {
        MessageBox.Show(ex.ToString());
    }
    //set the Selection Mode back to Cell Select to avoid conflict with sorting mode
    dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;


texts:
I'm looking for ways to make this calculator more efficient and/or make the code a little easier to read.

#include <iostream>
#include <cstdlib>
using namespace std;

// variables to be used in the program
double result, valueA, valueB, valA, valB;
int choice;
char cont;

//functions to perform the calculations

double mult(double valueA, double valueB) {
result = valueA * valueB;
return result;
}

double div(double valueA, double valueB) {
result = valueA / valueB;
return result;
}

// functions that prompt the user for values to be calculated

double getValueA(string unit) {
cout << "Enter " << unit << ": " << endl;
cin >> valA;
cout << endl;
return valA;
}

double getValueB(string unit) {
cout << "Enter " << unit << ": " << endl;
cin >> valB;
cout << endl;
return valB;
}

void title() {
cout << "**** NEO-VOLT ELECTRICAL CALCULATOR ****" << endl;
cout << "*   by *" << endl;
cout << "*Adam Pate *" << endl;
cout << "****************************************" << endl;
cout << endl << endl << endl;
}

void showMenu() {
cout << " Main Menu: " << endl;
cout << endl;
cout << "Ohm's Law" << endl;
cout << " 1. Voltage " << endl;
cout << " 2. Resistance " << endl;
cout << " 3. Current " << endl;
cout << "Power Law" << endl;
cout << " 4. Wattage " << endl;
cout << " 5. Voltage " << endl;
cout << " 6. Current " << endl;
cout << endl;
cout << " 0. Exit the program " << endl;

}
//Shows results of the calculation
void displayResult(string units) {
cout << result << " " << units;
cout << endl << endl;

}
// Takes the users choice and calls functions accordingly
void processMenu() {
cin >> choice;
switch(choice) {
case 0:
exit(0);
case 1:
getValueA("Amps");
getValueB("Ohms");
mult(valA, valB);
displayResult("Volts");
break;
case 2:
getValueA("Volts");
getValueB("Amps");
div(valA, valB);
displayResult("Ohms");
break;
case 3:
getValueA("Volts");
getValueB("Ohms");
div(valA, valB);
displayResult("Amps");
break;
case 4:
getValueA("Volts");
getValueB("Amps");
mult(valA, valB);
displayResult("Watts");
break;
case 5:
getValueA("Watts");
getValueB("Amps");
div(valA, valB);
displayResult("Volts");
break;
case 6:
getValueA("Watts");
getValueB("Volts");
div(valA, valB);
displayResult("Amps");
break;
default:
cout << "Invalid choice.";
}

}

int main()
{
title();
do {
showMenu();
processMenu();
cout << "Perform another calculation? (y or n)" << endl;
cin >> cont;
} while(cont != 'n');

return 0;
}


texts:
This is my 2nd program I wrote on my own, a pretty simple program consisting of two functions (those functions are not combined in any way yet though). The first function moves the display times of subtitles saved in .srt files by a specified amount of time.

The second function "warps" the display times by a specified multiplier to fix subtitles written on the base of sped up/slowed down versions of the video(which results in the subtitles syncing out after some time).

Everything works fine and as intended, but I'm pretty certain there are things I could have done more optimally.

For starters, the argument input could be improved, so that you can just input "+20" instead of "+20:00,000" to shift the subtitles by 20 seconds.

That's pretty much the only problem I can come up that I don't know how to solve right now. Of course there are probably more problems with the code I can't spot yet, so any input is appreciated.

import re; import datetime; import time

def timeChangeSRT(n, s):
    t = time.time()
    f, new = open(n, 'r'), open('new' + n, 'w')
    offset = re.search('([\+\-])?((\d{1,2})\:)?(\d+)(\,(\d{1,3}))?', s)
    offset = datetime.timedelta(minutes=int(s[1:3]), seconds=int(s[4:6]), milliseconds=int(s[7:10]))

    for line in f:
        parsed = re.search('(\d{2}:\d{2}:\d{2}.\d{3}) \-\-> (\d{2}:\d{2}:\d{2}.\d{3})', line)
        if parsed:
            start = datetime.timedelta(minutes=int(parsed.group(1)[3:5]), \
                                       seconds=int(parsed.group(1)[6:8]), \
                                       milliseconds=int(parsed.group(1)[9:12]))
            end = datetime.timedelta(minutes=int(parsed.group(2)[3:5]), \
                                       seconds=int(parsed.group(2)[6:8]), \
                                       milliseconds=int(parsed.group(2)[9:12]))
            if '-' in s:
                start -= offset
                end -= offset
                newline = '0' + str(start)[:11] + " --> " + '0' + str(end)[:11] + '\n'
                new.write(newline)
            else:
                start += offset
                end += offset
                newline = '0' + str(start)[:11] + " --> " + '0' + str(end)[:11] + '\n'
                new.write(newline)

        else:
            new.write(line)
    stop = time.time() - t
    print('The %s file has been updated. New .srt file named %s has been created. The process took %s seconds.' % (n, 'new' + n, stop))

def warpSRT(n, w):
    t = time.time()
    f, new = open(n, 'r'), open('new' + n, 'w')
    offset = w
    for line in f:
        parsed = re.search('(\d{2}:\d{2}:\d{2}.\d{3}) \-\-> (\d{2}:\d{2}:\d{2}.\d{3})', line)
        if parsed:
            start = datetime.timedelta(minutes=int(parsed.group(1)[3:5]), \
                                       seconds=int(parsed.group(1)[6:8]), \
                                       milliseconds=int(parsed.group(1)[9:12]))
            end = datetime.timedelta(minutes=int(parsed.group(2)[3:5]), \
                                       seconds=int(parsed.group(2)[6:8]), \
                                       milliseconds=int(parsed.group(2)[9:12]))
            start *= offset
            end *= offset
            newline = '0' + str(start)[:11] + " --> " + '0' + str(end)[:11] + '\n'
            new.write(newline)

        else:
            new.write(line)
    stop = time.time() - t
    print('The %s file has been updated. New .srt file named %s has been created. The process took %s seconds.' % (n, 'new' + n, stop))


texts: Frequency of words in all files of a directory using Future - Scala

texts:
I created a program to get frequency of word in all files in a directory using Future API

import java.io.File
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

class GetWordCount{

  def inFileCount(source: File):Future[Map[String,Int]]= {

    val futureMap:Future[Map[String,Int]]=Future {
      val wordList = scala.io.Source.fromFile(source.toString).getLines.flatMap(_.split("\\W+")).toList
      val wordMap = wordList.groupBy(a => a)
      wordMap.map { case (k, v) => (k, v.length) }
    }
    futureMap

  }

  def getWordCount(dir: String): Future[Map[String,Int]]= {

    val file = new File(dir)
    require(file.exists() && file.isDirectory)
    Future.sequence(file.listFiles.filter(_.isFile).map { a => inFileCount(a) }.toList) map{
      list => list.fold(Map())((a,b) =>a ++ b.map{ case (k,v) => k-> (v+a.getOrElse(k,0)) })
    }

  }

}

Please review this code and make suggestions.


texts:
I've written a simple asynchronous logger (playground):

mod logger {

    use std::sync::mpsc::{channel, Sender};
    use time::now;

    pub type LogError = std::sync::mpsc::SendError<String>;

    /// Runs a function that can logs asynchronously.
    pub fn log<F, T>(f: F) -> T
    where
        F: FnOnce(Logger) -> T,
    {
        let (sender, receiver) = channel();
        let handle = std::thread::spawn(move || {
            while let Ok(msg) = receiver.recv() {
                println!("{}", msg);
            }
            println!("LOG FINISHED");
        });
        let result = f(Logger { sender });

        handle.join().unwrap(); // Error handling?

        result
    }

    /// The actual logger.
    #[derive(Clone)]
    pub struct Logger {
        sender: Sender<String>,
    }

    impl Logger {
        /// Logs an information.
        pub fn info(&self, s: impl std::fmt::Display) -> Result<(), LogError> {
            let s = format!("[{}] [INFO ] {}", now().rfc3339(), s);

            self.sender.send(s)
        }

        /// Logs an error.
        pub fn error(&self, s: impl std::fmt::Display) -> Result<(), LogError> {
            let s = format!("[{}] [ERROR] {}", now().rfc3339(), s);

            self.sender.send(s)
        }
    }

}

// Demontration:
fn main() -> Result<(), logger::LogError> {
    logger::log(|logger| {
        logger.info("Hello world")?;

        // Cloning without overhead:
        logger.clone().error("Oops, error")
    })
}

The concept is simple: I spawn a thread with a receiver, and the logger sends the text to it.

To make this work, I was forced to use a callback to correctly join the thread when the user's code is done. Is there a better/prettier way to do that?

And also, is that pattern efficient? I know that I can buffer the lines inside the spawned thread, but I am talking about the whole pattern.


texts: jQuery on-change using multiple selectors

texts:
What is the best way to refactor the following code to avoid duplication?

    // JQuery FORM Functions
$(document).on('change','.submittable',function(){
     //save current input field into hidden input 'focus_field' if it exists
        if($('input#focus_field').length){
            var $focus_field = $(this).attr('id')
            $('input#focus_field').val($focus_field)
        }
    $('input[type=submit]').click();
    return false;
});

$(document).on('change','.submittable_wait',function(){
    $('#please_wait').show();
    $('input[type=submit]').click();
    return false;
});

$(document).on('change','.submittable_wait_bar',function(){
    $('#ajax_working').show();
    $('input[type=submit]').click();
    return false;
});

$(document).on('change','.submittable_wait_bar_single',function(){
    $('#ajax_working').show();
    $( this ).closest("form").submit();
    return false;
});

// nested_form - fields added
$(document).on('nested:fieldAdded', function(event) {
    $('#ajax_working').show();
    $('#reload_form').val('true');
    $('input[type=submit].btn-primary').click()
});

// nested_form - fields removed
$(document).on('nested:fieldRemoved', function(event) {
    $('#please_wait').show();
    $('#reload_form').val('true');
    $('input[type=submit].btn-primary').click()
});


texts: Steam Community Market Strange Part Scraper

texts:
A while back I wrote a simple little PHP script that searches the Steam community market for any TF2 strange weapons with strange parts on the first page of results for that weapon type. It works by retrieving the listings for each weapon using curl, runs a regex to retrieve the internal JS variable containing the item metadata, and parses the JSON and looks in the descriptions for any strange part strings:

#!/usr/bin/php

<?php

# list of weapon types to look for

$weapons = array(
  0 => "Scattergun",
  1 => "Pistol",
  2 => "Rocket%20Launcher",
  3 => "Direct%20Hit",
  4 => "Shotgun",
  5 => "Flame%20Thrower",
  6 => "Flare%20Gun",
  7 => "Reserve%20Shooter",
  8 => "Axtinguisher",
  9 => "Grenade%20Launcher",
  10 => "Loch-n-Load",
  11 => "Stickybomb%20Launcher",
  12 => "Eyelander",
  13 => "Minigun",
  14 => "Tomislav",
  15 => "Dalokohs%20Bar",
  16 => "Killing%20Gloves%20of%20Boxing",
  17 => "Pomson%206000",
  18 => "Widowmaker",
  19 => "Rescue%20Ranger",
  20 => "Frontier%20Justice",
  21 => "Wrangler",
  22 => "Sniper%20Rifle",
  23 => "Bazaar%20Bargain",
  24 => "SMG",
  25 => "Jarate",
  26 => "Bushwacka",
  27 => "Revolver",
  28 => "Ambassador",
  29 => "Knife",
);

for($wep_counter = 0; $wep_counter < count($weapons); $wep_counter++) {

  $url = "http://steamcommunity.com/market/listings/440/Strange%20". $weapons[$wep_counter];       # get listing for that weapon type

  $handle = curl_init($url);
  curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);

  $resultraw = curl_exec($handle);

  preg_match("/var g_rgAssets = (\{.*\});/", $resultraw, $resultsearch);                           # retrieve the JSON item metadata from the page

  $json_string = rtrim($resultsearch[1]);
  $json_data = json_decode($json_string,true);

  for($count = 0; $count < count($json_data["440"]["2"]); $count++) {                              # iterate through each item
    $item = array_values($json_data["440"]["2"])[$count];
    if(array_key_exists("descriptions",$item)) {                                                   # check for an item description; if it has a strange part it'll be listed in the description
      for($descriptions = 0; $descriptions < count($item["descriptions"]); $descriptions++) {
        $description = array_values($item["descriptions"])[$descriptions];
        if(array_key_exists("color", $description) && $description["color"] == "756b5e") {         # if any of the description strings have the color 756b5e (color of the strange part indicator)...
          print $url . ", ";                                                                       # output what item it is and the index on the page for easy retrieval
          print $count + 1 . "\n";
        }
      }
    }
  }

  print "Sleeping" . "\n";                                                                         # sleep for 15 seconds to avoid rate limiting
  sleep(15);
}

?>

I'd like to get some feedback on how I can make it cleaner/clearer/better. In particular, the big $weapons array at the beginning is super ugly; is there a way I could have that be more compact? Perhaps something with an explode?


texts: Java - propagating a threadlocal by wrapping a runnable

texts:
My aim is to use a thread pool together with a thread local. I cannot use InheritableThreadLocal because the thread data is different per user and there a couple of parallel users at any time.

So I need to push the thread local down from the mother thread to the children.

I use guava so I want to get listenable futures back. Below is my implementation. Please look at the execute function where the logic happens.

My question is what could go wrong here?

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import myorg.MyService;
import myorg.ThreadData;

import com.google.common.util.concurrent.AbstractListeningExecutorService;

public class ListeningDecorator extends AbstractListeningExecutorService {
    private final ExecutorService delegate;

    ListeningDecorator(final ExecutorService delegate) {
        this.delegate = checkNotNull(delegate);
    }

    @Override
    public final boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException {
        return this.delegate.awaitTermination(timeout, unit);
    }

    @Override
    public final boolean isShutdown() {
        return this.delegate.isShutdown();
    }

    @Override
    public final boolean isTerminated() {
        return this.delegate.isTerminated();
    }

    @Override
    public final void shutdown() {
        this.delegate.shutdown();
    }

    @Override
    public final List<Runnable> shutdownNow() {
        return this.delegate.shutdownNow();
    }

    @Override
    public final void execute(final Runnable command) {
        final ThreadData threadData = MyService.getThreadData();
        if (threadData == null) {
            throw new RuntimeException("threadData is null");
        }
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                MyService.setThreadData(threadData);
                command.run();

            }
        };

        this.delegate.execute(runnable);
    }
}


texts: Compact jQuery tool tip code, without jQueryUI

texts:
I have this tooltip code that I came up with, using jQuery:

$('div.a')
.bind('mousemove', function(e){
    $('#follow').css({
       left:  e.pageX + 20,
       top:   e.pageY
    });
})
.mouseenter(function() {
    $('#follow').css('display','block');
})
.mouseleave(function() {
    $('#follow').css('display','none');
})

I was wondering if there is anyway to compact it even more than it already is (ignore whitespace).

Here is a jsFiddle, if you'd like to test it.


texts:
I have a SQL update statement which does what it's supposed to. However, I have a feeling that the way I wrote it isn't the best. I am not highly experienced in SQL so any pointers or hints on how can I rewrite this statement and possibly get rid of the duplicate joins (joining on same tables again in the where statement is what bothers me about this update statement) would be helpful.

UPDATE Item SET AttachementID = NULL
    FROM Item i
    JOIN BidItem ebi ON i.BidItemID = ebi.BidItemID
    JOIN Group eg ON ebi.GroupID = eg.GroupID
    WHERE eg.EstimateID = @JobID and i.AttachementID NOT IN (
        SELECT i.ItemID FROM Item i
            JOIN BidItem ebi ON i.BidItemID = ebi.BidItemID
            JOIN Group eg ON ebi.GroupID = eg.GroupID
            WHERE eg.EstimateID = @JobID
    )


texts:
I have a few custom exception classes that I created simply for the sake of having my own exception message:

public class DivideByZeroException extends Exception
{
   @Override
   public String toString()
   {
       return "ERROR: Expression cannot divide by 0";
   }
}

I realize that this can be done by throwing an exception like:

throw new Exception("ERROR: Expression cannot divide by 0");

but this contains a prefix of java.lang.Exception: in the string.

I think it's a bit ugly to remove the unwanted prefix from the string, but creating a class just for the exception message seems a bit excessive to me. Is there a different way to do this?


texts:
What I'm trying to achieve

From a list of lists of elements (one element can be in multiple lists, but only once in each list), I want to generate a map whose keys are each elements and the values are the collection of elements that appear at least once with the key in the first lists.

Example

This is the input :

List<List<String>> input = Arrays.asList(
    Arrays.asList("calculating", "label", "farm", "anger", "able", "aboriginal"),
    Arrays.asList("injure", "label", "anger", "teeny-tiny", "able", "mindless", "teen"),
    Arrays.asList("injure", "calculating", "teeny-tiny", "mindless", "aboriginal")
);

I simplified the problem by using Strings but the elements could be any object. Please notice that:

some words appear in multiple lists
the list don't have any duplicates

The expected output should look like this:

{
     able=[teeny-tiny, farm, calculating, aboriginal, label, mindless, anger, injure, teen],
     teeny-tiny=[able, calculating, aboriginal, label, mindless, anger, injure, teen],
     farm=[able, calculating, aboriginal, label, anger],
     calculating=[able, teeny-tiny, farm, aboriginal, label, mindless, anger, injure],
     aboriginal=[able, teeny-tiny, farm, calculating, label, mindless, anger, injure],
     label=[able, teeny-tiny, farm, calculating, aboriginal, mindless, anger, injure, teen],
     mindless=[able, teeny-tiny, calculating, aboriginal, label, anger, injure, teen],
     anger=[able, teeny-tiny, farm, calculating, aboriginal, label, mindless, injure],
     injure=[able, teeny-tiny, calculating, aboriginal, label, mindless, anger]
}

So for example you see that the list associated with the value farm contains the value calculating because those two words were together in the first list of the input.

Also note that the resulting collections should not have duplicates: label and able are together in the first and second lists of the input, but the list associated to the key able (resp. label) in the result contains only one label (resp. able).

This is just an example. For my real problem, the input would not contain 3 lists of 5 or 6 elements, but a few thousand lists with hundreds of elements.

The language

I'm implementing this in Java.

My solution

This is what I could come up with and I'd like you to review:

Map<String, Set<String>> result = new HashMap<>();
for (List<String> values : input.values()) {
    for (String str : values) {
        Set<String> l = result.getOrDefault(str, new HashSet<>());
        l.addAll(values);
        l.remove(str);
        result.put(str, l);
    }
}

What I am going to use that for

It represents a simplification of a part of a problem I'm working with. I want to detect objects that are similar, but fully comparing two objects is computationally expensive. But I have a cheap way of grouping objects by characteristic. I want to use those characteristics to compare only objects that are potential matches.

For example, notice that, in the input of my example above, all the words of the first list  contain an a, all the words of the second list contain a e and an i for the third list. With the resulting map, I will be able to tell, for each of the keys, the list of words sharing one of those vowels. That way, I can avoid comparing farm and teen because they have nothing in common.


texts: Longest Substring Without Repeating Characters in JS

texts:
The task

is taken from leetcode

  Given a string, find the length of the longest substring without
  repeating characters.

  Example 1:

  Input: "abcabcbb"

  Output: 3

  Explanation: The answer is "abc", with the length of 3.

  Example 2:

  Input: "bbbbb"

  Output: 1

  Explanation: The answer is "b", with the length of 1.

  Example 3:

  Input: "pwwkew"

  Output: 3

  Explanation: The answer is "wke", with the length of 3.
               Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

My solution

var lengthOfLongestSubstring = function(s) {
    const len = s.length;
    if (len < 2) { return len; }
    let res = [];
    let tmp = [];
    [...s].forEach(x => {
      if (tmp.includes(x)) {
        tmp = [...tmp.slice(tmp.findIndex(y => y === x ) + 1)];
      }
      tmp.push(x);
      if (tmp.length > res.length) { res = tmp; }
    });
  return res.length;
};


texts: Tic Tac Toe engine in Python for Deep Learning

texts:
I'm implementing a Tic Tac Toe engine that will work with deep learning.  I'm using a 3x3 numpy array of floats to represent the board.  +1.0 represents an X, -1.0 represents an O, and 0.0 represents an empty square.

I'm wondering specifically:

Is there a better/more Pythonic way to enumerate the X/O values?
Is there a more efficient way to test whether there is a winner?

And more generally:

Are there any Tic Tac Toe-related issues I'm not thinking about?
What style/readability issues does my code have?

Here's the code:

import numpy as np

class TicTacToe(object):
    DIM = 3
    ROWS = [
        # Rows
        [(0, 0), (0, 1), (0, 2)],
        [(1, 0), (1, 1), (1, 2)],
        [(2, 0), (2, 1), (2, 2)],
        # Cols
        [(0, 0), (1, 0), (2, 0)],
        [(0, 1), (1, 1), (2, 1)],
        [(0, 2), (1, 2), (2, 2)],
        # Diagonals
        [(0, 0), (1, 1), (2, 2)],
        [(0, 2), (1, 1), (2, 0)],
    ]

    class Move(object):
        X = 1.0
        O = -1.0

    class Win(object):
        X = 1.0
        O = -1.0
        DRAW = 0.0

    X_ROW = Move.X * DIM
    O_ROW = Move.O * DIM
    EMPTY = 0.0

    def __init__(self):
        self.board = np.zeros((TicTacToe.DIM, TicTacToe.DIM))

    def winner(self):
        for row in TicTacToe.ROWS:
            tot = sum([self.board[index] for index in row])
            if tot == TicTacToe.X_ROW:
                return TicTacToe.Win.X
            elif tot == TicTacToe.O_ROW:
                return TicTacToe.Win.O
        if TicTacToe.EMPTY in self.board:
            return None
        return TicTacToe.Win.DRAW

    def game_over(self):
        if self.winner() is None:
            return False
        return True

    def whose_turn(self, pretty=False):
        if pretty:
            return self.display_move(self.whose_turn(pretty=False))
        if self.board.sum():
            return TicTacToe.Move.O
        return TicTacToe.Move.X

    def make_move(self, row, col, display_board=True):
        if self.winner() is not None:
            raise Exception("Game is over. No more moves.")
        elif self.board[row, col] != self.EMPTY:
            raise Exception("That space is taken!")
        self.board[row, col] = self.whose_turn()
        if display_board:
            self.print_board()

    def display_move(self, move):
        if move == TicTacToe.Move.X:
            return "X"
        elif move == TicTacToe.Move.O:
            return "O"
        return " "

    def print_board(self):
        move_chars = [self.display_move(move) for move in self.board.flatten()]
        print((
            " {} | {} | {} \n"
            "---|---|---\n"
            " {} | {} | {} \n"
            "---|---|---\n"
            " {} | {} | {} \n"
            ).format(*move_chars)
        )


texts:
I am using the following to validate my user which works but i wish to incoperate roles so I used the reg iis to add the standard tables aspnet_UsersInRoles.

What I basically want is the ability to have variables canView canDelete canEdit and that I can just access them when my dal is called.

protected void btnLogin_Click1(object sender, EventArgs e)
{
    Users _loginUser = _dal.VerifyPassword(txtUserName.Text, txtPassword.Text);

    if (failedLogin == false)
        lblerror.Text = "Invalid Login";
    else
    {

        UserData userData = new UserData
        {
            FirstName = _loginUser
        };
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
          1,                                     // ticket version
          _loginUser.UserName,                              // authenticated username
          DateTime.Now,                          // issueDate
          DateTime.Now.AddMinutes(30),           // expiryDate
          isPersistent,                          // true to persist across browser sessions
          userData,                              // can be used to store additional user data
          FormsAuthentication.FormsCookiePath);  // the path for the cookie

        // Encrypt the ticket using the machine key
        string encryptedTicket = FormsAuthentication.Encrypt(ticket);

        // Add the cookie to the request to save it
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        cookie.HttpOnly = true;
        Response.Cookies.Add(cookie);

        lblerror.Text = "Success!";

        Response.Redirect("default.aspx");
    }

}

My Question is how would i adapt the following routine to inlcude the roles aspnet_UsersInRoles table to check if has administrative privellages Of a guid type of ED85788D-72DA-4D0A-8D5E-B5378FC00592.

public Users VerifyPassword(string userName, string password)
{
    //The ".FirstOrDefault()" method will return either the first matched
    //result or null
    Users myUser = SoccerEntities.Users
        .FirstOrDefault(u => u.UserName == userName
                     && u.password == password);

    if (myUser == null)    //User was not found
    {
        //Proceed with your login process...
        return myUser;
    }
    else    //User was  found
    {
        if (isPlayerdb(userName))
            isPlayer = true;
        if (isAdmindb(userName))
            isAdmin = true;

        return myUser;
        //Do something to let them know that their credentials were not valid
    }
}

Cause at min im doing this setting the isAdmin variable on a other function isAdmindb so thats three hits to db which is not very effiecent

protected bool isAdmindb(string userName)
{

    try{
           Users adminUsers = (from users in SoccerEntities.Users
                       where users.roleId == new Guid("ED85788D-72DA-4D0A-8D5E-B5378FC00592") && users.UserName == userName
                       select users).FirstOrDefault();

        if (adminUsers != null)
            return true;
        else
            return false;

    }
    catch (Exception ex)
    {
        throw new EntityContextException("isAdmin failed.", ex);
    }
}

Edit a had a typo in my return !!!


texts: Monadic list for a more functional approach to C#

texts:
I am learning about monadic structures and have created a sort of monad list that implements the map and binding "operators" (or technically methods) in C#.

I understand that Linq already exists and would solve many of the problems that my solution solves (I am in fact already using linq to help in parts of my code) and that lists are technically already monads. However this is still a learning experience for me and so I want to make sure I have the right idea.

class ListMonad<T> : IEnumerable<T>
{
    private readonly List<T> items;
    private List<T> Items => items;

    public ListMonad(List<T> value)
    {
        this.items = new List<T>(value);
    }

    public ListMonad()
    {
        items = new List<T> { };
    }

    public ListMonad<TO> Bind<TO>(Func<T, ListMonad<TO>> func)
    {
        var lists = new List<ListMonad<TO>>();
        foreach(var el in Items)
            lists.Add(func(el));

        return new ListMonad<TO>(lists.SelectMany(x => x.Items).ToList());
    }

    public ListMonad<TO> Map<TO>(Func<T, TO> func)
    {
        var result = new ListMonad<TO>();
        foreach(var item in Items)
            result.Items.Add(func(item));

        return result;
    }

    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        foreach(var item in Items)
            yield return item;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable<T>)this).GetEnumerator();
    }

    public T this[int index] => Items[index];
}

Use:

class Program
{
    static void Main(string[] args)
    {
        var listMonad = new ListMonad<int>(new List<int> { 1, 2, 3, 4, 5, 6, 7 });

        var doubledAndSquared = Compose((int x) => x * x, (int x) => x * 2);
        Func<int, ListMonad<int>> zeroSeparated = x => new ListMonad<int>(new List<int> { x, 0 });

        listMonad = listMonad
            .Bind(zeroSeparated)
            .Map(doubledAndSquared);

        foreach(var item in listMonad)
            Console.Write(item + ", ");
    }

    static Func<V, U> Compose<T, U, V>(Func<T, U> func1, Func<V, T> func2) =>
        (V x) => func1(func2(x));
}


texts:
The primary goal of this code is to convert a PDF file to images. I also create a directory under C:/Media based on a combination of the PDF name and current date and insert the uploaded PDF to the same directory as the images for safe keeping.

I am primarily concerned that I am over-complicating the process by initializing too many variables and the process by which I move the PDF to the newly created directory. I am looking for guidance or advice on how to improve this code.

public class PdfService {

public static void main(String[] args) {

    System.out.println("Test of Convert to PNG");
    convertPDFtoImage(args[0]);
 }

public static void convertPDFtoImage(String PDFFileName) {

    try {

         // load PDF document
         PDFDocument document = new PDFDocument();
         File baseFile = new File(PDFFileName);
         document.load(baseFile);

         //Get todays date as a String so that you can append it to the directory
         String df = new SimpleDateFormat("MM-dd-yy").format(new Date());

         //Get the filename without extension so that you can create a directory based on the name
         Path path = Paths.get(PDFFileName);
         String filenameWithExtension = path.getFileName().toString();
         String filename = FilenameUtils.removeExtension(filenameWithExtension);

         //add the current date to the filename to get the directory name
         String dirname = filename + "-" + df;

         //Create the directory
         Path dir =  Paths.get("C:\\Media\\" + dirname);
         Files.createDirectory(dir);

         //Move the pdf to the newly created directory
         movePDFToDirectory(baseFile, dirname, filenameWithExtension);

         // create renderer
         SimpleRenderer renderer = new SimpleRenderer();

         // set resolution (in DPI)
         renderer.setResolution(150);

         // render
         List<Image> images = renderer.render(document);

         // write images to files to disk as JPEG
            try {

                System.out.println("Begin converting PDF...");

                for (int i = 0; i < images.size(); i++) {
                    ImageIO.write((RenderedImage) images.get(i), "jpeg", new File("C:\\Media\\" + dirname + "\\" + filename + "_" + (i + 1) + ".jpeg"));
                }

                System.out.println("PDF converted to image(s) successfully.");

            } catch (IOException e) {
                System.out.println("ERROR: " + e.getMessage());
            }

       } catch (Exception e) {
         System.out.println("ERROR: " + e.getMessage());
       }
}

public static void movePDFToDirectory(File originalFile, String directory, String filename) {
        InputStream inStream = null;
        OutputStream outStream = null;

        try{

            File newFile = new File("C:\\Media\\" + directory + "\\" + filename);

            inStream = new FileInputStream(originalFile);
            outStream = new FileOutputStream(newFile);

            byte[] buffer = new byte[1024];

            int length;
            //copy the file content in bytes
            while ((length = inStream.read(buffer)) > 0){

                outStream.write(buffer, 0, length);

            }

            inStream.close();
            outStream.close();

            System.out.println("Original PDF has been copied successfully!");

        }catch(IOException e){
            e.printStackTrace();
        }

}
}

Notes:

Eventually I plan on moving this bit of code to a web application that accepts the image as an upload. As it stands I'm just passing the file location as an argument in the main method.
I plan on making the base directory (C:/Media) a dynamic variable in the event we move directories.


texts: Re-worked Workbook_Open, Creating DateStrings

texts:
So, I had a go at re-writing my Workbook_Open event based on The advice from my previous question. Thoughts?

Private Sub Workbook_Open()

    Dim strTableTitle       As String
    Dim StrTodaysDate       As String
    Dim StrThisDay          As String
    Dim StrThisMonth        As String
    Dim StrThisYear         As String

    Dim strSaveFileFolder   As String
    Dim StrSaveFilename     As String
    Dim StrSaveDate         As String

    Dim SheetDashboard As Worksheet
    Set SheetDashboard = Sheets("Market Dashboard")

        SheetDashboard.Activate
        SheetDashboard.Cells(1, 1).Value = strTableTitle

        StrThisDay = day(Date)
        StrThisMonth = MonthName(month(Date))
        StrThisYear = year(Date)

        StrTodaysDate = StrDay & " " & StrMonth & " " & StrYear
        strTableTitle = "Weekly Market Recap - " & StrDateString

        strSaveFileFolder = "S:\Investments\Regular Reports\Market Insight Reports\Weekly Dashboard\"
        StrDateNumber = StrDay & "." & month(Date) & "." & StrYear
        StrSaveFilename = "Client Facing Dashboard - " & StrDateNumber & ".xlsm"

    Dim lngDay As Long, lngMonth As Long, lngYear As Long
    Dim str3MonthsAgo As String, str6MonthsAgo As String, str9MonthsAgo As String, str12MonthsAgo As String
    Dim strStartDate As String

    strStartDate = "01/" & month(Date) & "/" & year(Date)

        str3MonthsAgo = DateAdd("m", -3, strStartDate)

        str6MonthsAgo = DateAdd("m", -6, strStartDate)

        str9MonthsAgo = DateAdd("m", -9, strStartDate)

        str12MonthsAgo = DateAdd("yyyy", -1, strStartDate)

        '/ Key Rates Headers
        Cells(20, 12) = str3MonthsAgo
        Cells(20, 13) = str6MonthsAgo
        Cells(20, 14) = str9MonthsAgo
        Cells(20, 15) = str12MonthsAgo

        '/ Currencies Headers
        Cells(20, 20) = str3MonthsAgo
        Cells(20, 21) = str6MonthsAgo

        ActiveWorkbook.SaveAs filename:=strSaveFileFolder & StrSaveFilename

End Sub


texts: Numerical maximization procedure normal distribution

texts:
Firstly, I programmed this gaussian density as an R function which takes the parameters mean and variance (mean=4,sd=1) and calculates the density on a given realization x. Then, passing the density function that I have coded to a (numerical) maximizer, I want to get a maximum close to the parameters which have been used to generate the sample. (mean=4,sd=1).

The question was:

  Generate 1000 realizations following N(4,1) and then apply a numerical maximization procedure to determine a maximum likelihood estimator for the unknown parameters.

This is for homework and I would like to know whether my solution is correct or not, and how I can improve. In the case it's wrong I am not asking for a complete correction but just some clues. Hence, my problem is to apply this maximization procedure.

library(stats4)
set.seed(123)
n <- 5000
x <- rnorm(n, mean =4, sd = 1)

likelihood <- function(mu, sigma)
{
a = dnorm(x, mu, sigma)
-sum(log(a))
}
mle(minuslogl =likelihood, start = list(mu = 1, sigma = 1), method = "L-BFGSB",lower = c(-Inf, 0), upper = c(Inf, Inf))

Output:

  mu=3.9994305, sd=0.9944726


texts: Merge sort Java implementation for an interview

texts:
I just learned Merge sort, and I really like this Merge sort implementation since it is very logical and very easy to follow. If I was asked in an interview to implement merge sort, will this implementation suffice?

I know creating those new arrays every time the mergeSort() method is called is bad practice. I fully understand merge sort, I can explain it in very good detail as I implement it, but will this implementation lose me some "points" because of the the way I am creating all these new arrays?

Are there any other things that may lose me some points?

public static void mergeSort(int[] a) {
    if(a.length < 2) return;

    int mid = a.length / 2;

    int[] left = new int[mid];
    int[] right = new int[a.length - mid];

    //Filling left and right arrays.
    for(int i = 0; i < left.length; i++)
        left[i] = a[i];
    for(int i = 0; i < right.length; i++)
        right[i] = a[i + mid];

    mergeSort(left);
    mergeSort(right);
    merge(left, right, a);
}

public static void merge(int[] left, int[] right, int[] a) {
    int i = 0; //For left array
    int j = 0; //For right array
    int k = 0; //For a array

    while(i < left.length && j < right.length) {
        if(left[i] <= right[j])
            a[k++] = left[i++];
        else
            a[k++] = right[j++];
    }

    //Filling remaining integers, for the array that has left over numbers.
    while(i < left.length)
        a[k++] = left[i++];
    while(j < right.length)
        a[k++] = right[j++];

}

This is tested and working.


texts: A bash prompt that includes battery level & git branch

texts:
Is there a better way to handle the color codes and display git branch and battery percentage?

#!/bin/bash

## set colors
t="\[\033[0;34m\]"
p="\[\033[0;35m\]"
g="\[\033[0;32m\]"
b="\[\033[0;36m\]"
y="\[\033[0;33m\]"
## the color reset code
re="\[\033[0m\]"

## inserts git brance into prompt at $(PBG)
PBG(){
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

I would rather not make three different calls to insert the battery level.

## inserts battery percentage into prompt @ $(BATT)
BATT(){
    acpi | awk '{print $4}' | sed -e 's/,//'
}

PS1="$b($re$y\$(BATT)$re$p \h$re $gÎ»$re $g\W$re$t \$(PBG)$re$b)$re "


texts:
I'd like to ask if this PHP/HTML code has any flaws which can be exploited by the potential aggressor:

<form method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<input type='text' name='foo' value='<?php echo htmlspecialchars($_POST['foo']); ?>' />
<input type='submit' value='bar' />
</form>

I'm aware that it can be exploited by calling script like this http://foo.bar/baz.php/'><script>alert('xss')</script><foo' and

<?php echo $_SERVER['PHP_SELF']; ?>

should be replaced with

<?php echo htmlentities($_SERVER['PHP_SELF']); ?> or <?php echo htmlspecialshars($_SERVER['PHP_SELF']); ?>

Are there any other possible ways to conduct XSS attack on this piece of code? If so, how can I secure this form?

@Update: Ok, I've just found another possible attack - entering code like ' onmouseover='alert(String.fromCharCode(88,83,83,33)); (with the apostrophe in the beginning) into the text field, which causes simple 'XSS!' alert. It can be avoided by changing <?php echo htmlspecialchars($_POST['foo']); ?> to <?php echo str_replace('\'', '&#39;', htmlspecialchars($_POST['foo'])); ?>


texts: Expression template to compute the Euclidean distance

texts:
I was writing some geometry-related code again and had a closer look at my function supposed to compute the Euclidean distance between two points (N-dimensional points by the way, hence the N template parameter). Here is a simplified version:

template<std::size_t N, typename T>
auto distance(const Point<N, T>& lhs, const Point<N, T>& rhs)
    -> T
{
    T res{};
    for (std::size_t i = 0 ; i < N ; ++i)
    {
        auto tmp = std::abs(lhs[i] - rhs[i]);
        res += tmp * tmp;
    }
    return std::sqrt(res);
}

So far, so good. However, one very common operation is to compare the distances. Generally speaking, when comparing the distances, the sqrt is optimized away and the sum of the squares is compared instead of the distance itself. Therefore, I tried to create some kind of expression template to represent the distance between two points, so that users will benefit from both the ease of use and the "get rid of sqrt optimization" when comparing distances. Basically, the call of sqrt is not done until the exact value of the distance is needed. Here is the class:

template<typename T>
struct DistanceExpression
{
    explicit constexpr DistanceExpression(T data):
        _data(data)
    {}

    operator T() const
    {
        return std::sqrt(_data);
    }

    bool operator==(const DistanceExpression& other) const
    {
        return _data == other._data;
    }

    bool operator!=(const DistanceExpression& other) const
    {
        return !(*this == other);
    }

private:

    T _data;
};

My new distance function is implemented as such:

template<std::size_t N, typename T>
auto distance(const Point<N, T>& lhs, const Point<N, T>& rhs)
    -> DistanceExpression<T>
{
    T res{};
    for (std::size_t i = 0 ; i < N ; ++i)
    {
        auto tmp = std::abs(lhs[i] - rhs[i]);
        res += tmp * tmp;
    }
    return DistanceExpression<T>{res};
}

Here is a minimal working code at Coliru. Is such a design reasonable or is it overkill to elegantly solve this problem?


texts:
Problem: Concat all sub-arrays of a given array.

Example input: [[0, 1], [2, 3], [4, 5]]

Example output: [0, 1, 2, 3, 4, 5]

Solution A: Use a loop

var flattened=[];
for (var i=0; i<input.length; ++i) {
    var current = input[i];
    for (var j=0; j<current.length; ++j)
        flattened.push(current[j]);
}

Solution B: Use reduce

var flattened = input.reduce(function(a, b) {
    return a.concat(b);
}, []);

Solution B looks much shorter and easier to understand, but, it seems to be much more resource-wasteful - for each element of the input, a new array is created - the concatenation of a and b. On the contrary, solution A uses a single array 'flattened', which is updated during the loop.

So, my question is: which solution is better? Is there a solution that combines the best of both worlds?


texts:
This is a Python chat room that I've been working on and it enables to you to chat to other people on the same network through Python.

Server.py:

import socket
import sys

s = socket.socket()
host = socket.gethostname()
print(" server will start on host : ", host)
port = 8080
s.bind((host,port))
name = input(str("Please enter your username: "))
print("")
print("Server is waiting for incoming connections")
print("")
s.listen(1)
conn, addr = s.accept()
print("Recieved connection")
print("")
s_name = conn.recv(1024)
s_name = s_name.decode()
print(s_name, "has joined the chat room")
conn.send(name.encode())

while 1:
    message = input(str("Please enter your message: "))
    conn.send(message.encode())
    print("Sent")
    print("")
    message = conn.recv(1024)
    message = message.decode()
    print(s_name, ":" ,message)
    print("")

Client.py:

import socket
import sys

s = socket.socket()
host = input(str("Please enter the hostname of the server : "))
port = 8080
s.connect((host,port))
name = input(str("Please enter your username : "))
print(" Connected to chat server")

s.send(name.encode())
s_name = s.recv(1024)
s_name = s_name.decode()
print("")
print(s_name, "has joined the chat room ")

while 1:
    message = s.recv(1024)
    message = message.decode()
    print(s_name, ":" ,message)
    print("")
    message = input(str("Please enter your message: "))
    message = message.encode()
    s.send(message)
    print("Sent")
    print("")

I just wanted suggestions on how I can to improve this chatroom to make it better and faster. All suggestions will be greatly appreciated.


texts:
I've implemented a singly linked list in Java as a practice exercise and would appreciate a review.

LinkedList.java

public class LinkedList {

    private Node head;
    private int size;

    public LinkedList() {
    }

    public void addToEnd(char data) {
        addAtIndex(data, size);
    }

    public void addToBeginning(char data) {
        addAtIndex(data, 0);
    }

    public void addAtIndex(char data, int index) {
        Node temp = new Node(data);
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException();
        } else if (index == 0) {
            temp.setNextNode(head);
            head = temp;
            incrementCount();
        } else {
            Node current = head;
            for (int i = 1; i < index; i++) {
                current = current.getNextNode();
            }
            temp.setNextNode(current.getNextNode());
            current.setNextNode(temp);
            incrementCount();
        }
    }

    public void deleteFromBeginning() {
        deleteFromIndex(0);
    }

    public void deleteFromEnd() {
        deleteFromIndex(size - 1);
    }

    public void deleteFromIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        } else if (index == 0) {
            head = head.getNextNode();
            decrementCount();
        } else {
            Node current = head;
            for (int i = 1; i < index; i++) {
                current = current.getNextNode();
            }
            current.setNextNode(current.getNextNode().getNextNode());
            decrementCount();
        }
    }

    public char getFirst() {
        return getAtIndex(0);
    }

    public char getLast() {
        return getAtIndex(size - 1);
    }

    public char getAtIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        } else {
            Node current = head;
            for (int i = 0; i < index && current != null; i++) {
                current = current.getNextNode();
            }
            return current.getData();
        }
    }

    public void decrementCount() {
        size--;
    }

    public void incrementCount() {
        size++;
    }

    public int getSize() {
        return size;
    }

    public Node getHead() {
        return head;
    }
}

Node.java

public class Node {

    private char data;
    private Node next;

    public Node(char data) {
        this.data = data;
    }

    public char getData() {
        return data;
    }

    public Node getNextNode() {
        return next;
    }

    public void setData(char data) {
        this.data = data;
    }

    public void setNextNode(Node next) {
        this.next = next;
    }
}


texts: Optimize Scipy Sparse Matrix Factorization code for SGD

texts:
I'm working on implementing the stochastic gradient descent algorithm for recommender systems (see Funk) using sparse matrices with Scipy.

This is how a first basic implementation looks like:

N = self.model.shape[0] #no of users
M = self.model.shape[1] #no of items
self.p = np.random.rand(N, K)
self.q = np.random.rand(M, K)
rows,cols = self.model.nonzero()
for step in xrange(steps):
    for u, i in zip(rows,cols):
        e=self.model-np.dot(self.p,self.q.T) #calculate error for gradient
        p_temp = learning_rate * ( e[u,i] * self.q[i,:] - regularization * self.p[u,:])
        self.q[i,:]+= learning_rate * ( e[u,i] * self.p[u,:] - regularization * self.q[i,:])
        self.p[u,:] += p_temp

I have two questions and I am hoping some seasoned python coders / recommender systems experts here could provide me with some insight into this:

1) How often should the error e be adjusted? It is not clear from Funk's and Koren's papers if it should be once for every rating or if it should be once per every factor. Meaning, should i take it out of the for loop, leave it there, or put it even deeper (over the k iterations) ?

2) Unfortunately, my code is pretty slow, taking about 20 minutes on ONE iteration over a 100k ratings dataset. This means that computing the factorization over the whole dataset takes about 10 hours. I was thinking that this is probably due to the sparse matrix for loop. I've tried expressing the q and p changes using fancy indexing but since I'm still pretty new at scipy and numpy, I couldn't figure a better way to do it. Do you have any pointers on how i could avoid iterating over the rows and columns of the sparse matrix explicitly?


texts:
I have a device I connect to on TCP socket. I send it a message with what I want and it sends back all sorts of useful information:

Header:

+---------------+----------+----------+
| MagicWord     | 2 bytes  | 0xCAFE   |
| Version       | 1 byte   | 0x02     |
| Type          | 1 byte   | Variable |
| UTC offset    | 1 byte   | Variable |
| Reserved      | 1 byte   | Variable |
| PayloadSize   | 2 bytes  | Variable |
+---------------+----------+----------+

Payload:

+---------------+----------+----------+
| StartTime     | 4 bytes  | Variable |
| Duration      | 4 bytes  | Variable |
| Temp          | 2 bytes  | Variable |
| EstimatedDist | 2 bytes  | Variable |
| NumKnocks     | 1 byte   | Variable |
| Reserved      | 1 byte   |          |
+---------------+----------+----------+

Here is my attempt at how I got the variables from the message:

var location:[(String, [UInt8], Int)] = []

//Name, message, location in data

let dict  = [
    ("startTime", [UInt8](), 8),
    ("duration", [UInt8](), 12),
    ("Temp", [UInt8](), 16),
    ("EstimatedDist", [UInt8](), 18),
    ("NumKnocks", [UInt8](), 20),
    ("Reserverd", [UInt8](), 21)]

for item in dict {
    location.append(item)
}

var i = 0
var itemLen = Int()
for item in location {
    if 0...4 ~= i {

        //find length of byte by length subtraction of item itself from item above.
        itemLen = location[i + 1].2 - location[i].2
    }
    let typeRange = NSRange(location: location[i].2, length: itemLen)
    let typeData = data.subdataWithRange(typeRange)
    var arr = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(typeData.bytes), count: typeData.length))
    location[i].1 = arr
    i = i + 1
}

0000   fe ca 02 30 00 00 0e 00 4e 5b a2 56 12 19 00 00
0010   22 00 12 19 07 00

In my situation data is NSData from a GCDAsyncSocket response with the header removed.

For testing i've been doing and connecting to port.

echo -e "\xfe\xca\x02\x30\x00\x00\x0e\x00\x4e\x5b\xa2\x56\x12\x19\x00\x00\x22\x00\x12\x19\x07\x00" | nc -kl -c 1975

I can connect, send the packet, get the message back thats all fine. I can get the variables from the packet. However, I don't feel it's that elegant. I want to know what I should be looking at to try to improve. Examples (with explanations) would be great.


texts: Code to modify string as per instructions

texts:
I solved this problem statement on dear old codeforces.
The Problem Statement wants users to replace occurrences of '10' in the given string with either '1' or '0' until there is no occurrence of '10' left and the string formed is the lexicographically smallest string from the set of all valid answers.
This is my solution (and it has been accepted). However, I would like to know if we can simplify this solution further:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main() {
    int T = 0;
    std::cin >> T;
    while (T--) {
        int n = 0;
        std::cin >> n;
        std::string str;
        std::cin >> str;
        while (str.find("10", 0) != std::string::npos) {
            auto it = std::find(str.begin(), str.end(), '1');
            auto begin = it;
            std::string window;
            while (it != str.end() && *it == '1') {
                window.push_back(*it);
                it++;
            }
            while (it != str.end() && *it == '0') {
                window.push_back(*it);
                it++;
            }
            if (std::count(window.begin(), window.end(), '0') == 0 || std::count(window.begin(), window.end(), '1') == 0) {
                std::cout << str << "\n";
                break;
            }
            while (window.size() > 1) {
                auto count0 = std::count(window.begin(), window.end(), '0');
                auto count1 = std::count(window.begin(), window.end(), '1');
                if (count0 > count1) {
                    window.erase(--window.end());
                }
                else if (count1 > count0) {
                    window.erase(window.begin());
                }
                else {
                    if (str.find("10", std::distance(str.begin(), it)) == std::string::npos) {
                        window.erase(window.begin());
                    }
                    else {
                        window.erase(--window.end());
                    }
                }
            }
            *(--it) = window.front();
            str.erase(begin, it);
        }
        std::cout << str << "\n";
    }
    return 0;
}

Please review and suggest :)


texts:
I have written the following script that is pointed at a CSV through it's file name and then splits the file into "drops" (for mailings) and does a couple of operations on it. As of now it works, but seems fairly slow when I use it on any significant number of records (>5000). Also there is a section in there where I need to seed each file with semi-static data and the portion of the code where I store it is just ugly. If anyone can suggest improvements from a approach, style, logical, or really any perspective. What follows are the functions for seeding the file, for creating and writing the CSVs, and for transforming the rows for output. (seeding portion is in the following gist)
Part of the challenge in making this is that the headers might not always be the same or in the same order, so I need some way of comparing an "ideal" to what actually is, or so I think.
As of right now it is tragically uncommented, so I'll work on editing those in soon.

def create_output_csvs(source_file, start_WO, start_title, po_number)
  # Prep variables for use
  drop_sizes = read_drop_sizes
  dealer_pin = read_dealer_pin
  purl = read_dealer_purl
  purl = ".#{purl}" if purl[0] != '.'
  drop = 0
  current_title = start_title
  current_drop_number =  start_WO
  stop_at = drop_sizes[drop] - 1
  start_at = 0
  pin_seq = 100_099

  ipd_head = header_to_ipd_header(source_file)
  write_file = "#{current_drop_number} for import.csv"
  CSV.foreach(source_file, headers: true).each_with_index do |row, i|

    write_header_to(ipd_head, write_file) if i == start_at

    pin_seq += 1
    pin = "#{dealer_pin}-#{pin_seq}"

    CSV.open(write_file, 'a') { |out| out << transform_row(row, pin, purl) }

    if i == stop_at
      ipd_seed(write_file, current_drop_number, pin_seq, dealer_pin, purl)
      drop += 1
      create_ipd_pallet_flag(current_drop_number, po_number, current_title)

      if drop < drop_sizes.size
        current_drop_number = next_work_order_number(current_drop_number)
        current_title = next_job_title(current_title)
        write_file = "#{current_drop_number} for import.csv"
        pin_seq = 100_100 * (drop + 1)
        pin = "#{dealer_pin}-#{pin_seq}"
        start_at += drop_sizes[drop]
        stop_at += drop_sizes[drop]
        nav_to_next_drop_folder("#{current_drop_number} #{current_title}")
      end
    end
    drop == drop_sizes.length ? break : true
  end
end

Individual row transformations:

def transform_row(row, pin, purl)
  tmphead = row.headers
  lname_i = tmphead.find_index { |l| /lname.*|last.*/i=~l }
  fname_i = tmphead.find_index { |l| /fname.*|first.*/i=~l }
  first = row[fname_i].capitalize.gsub(/\s+/, '')
  last = row[lname_i].capitalize.gsub(/\s+/, '')
  sfx_i = tmphead.find_index { |l| /sfx.*|suffix.*|sufx.*/i =~ l }
  mi_i = tmphead.find_index { |l| /mi.*|mname/i =~ l }

  row[lname_i] = full_name(first, last, row[mi_i], row[sfx_i])

  row[mi_i] = salutat(first, last, row[sfx_i])
  row[fname_i] = first

  full_purl = "#{first}#{last}#{purl}".downcase

  address2_i = tmphead.find_index { |l| /add.*2/i =~ l }

  if address2_i
    address = "#{row[(address2_i - 1)]} #{row[address2_i]}"
    row[address2_i - 1] = address
    row.delete(address2_i)
  end

  row << pin
  row << full_purl
  row.delete_if { |h| col_blacklist?(h[0]) }
  row
end

Any suggestions for improvement would be appreciated, but primarily I am interested in reworking the code so that it's more readable/maintainable as well as speeding it up in general.


texts: Verify application configuration from JSON file with matching type using TypeScript in an Angular project

texts:
To bootstrap our application we have a configuration stored in a JSON file. This config holds different settings, like definition of endpoints (e. g. an API or SMS gateway etc.) or some default values for login.
endpoint.ts
export const isEndpoint = (candidate: any): candidate is Endpoint => {
  return (
    candidate && typeof candidate === 'object' &&
    candidate.hasOwnProperty('protocol') && (candidate.protocol === null || ['http', 'https'].includes(candidate.protocol)) &&
    candidate.hasOwnProperty('address') && (candidate.address === null || typeof candidate.address === 'string') &&
    candidate.hasOwnProperty('port') && (candidate.port === null || typeof candidate.port === 'number') &&
    candidate.hasOwnProperty('path') && (candidate.path === null || typeof candidate.path === 'string')
  );
}

export interface Endpoint {
  protocol: 'http'|'https'|null,
  address: string|null,
  port: number|null,
  path: string|null,
}

configutation.ts
import { Endpoint, isEndpoint } from './endpoint';

export const isConfiguration = (candidate: any): candidate is Configuration => {
  return (
    candidate && typeof candidate === 'object' &&
    candidate.hasOwnProperty('endpoints') &&
      candidate.endpoints.hasOwnProperty('api') && isEndpoint(candidate.endpoints.api) &&
      candidate.endpoints.hasOwnProperty('smsGateway') && isEndpoint(candidate.endpoints.smsGateway) &&
    candidate.hasOwnProperty('auth') &&
      candidate.auth.hasOwnProperty('company') && (candidate.auth.company === null || typeof candidate.auth.company === 'string')
  );
}

export interface Configuration {
  endpoints: {
    api: Endpoint,
    smsGateway: Endpoint
  },

  auth: {
    company: string|null
  }
}

In the end the code is used in an Angular service like this:
get configuration$(): Observable<Configuration> {
  if (this.configutation$) {
    return this.configutation$;
  }

  const path = environment.configuration;

  this.configutation$ = this.http.get<any>(path).pipe(
    map(configutation => {
      if (isConfigutation(configutation)) {
        return configutation;
      }

      throw new Error('Configutation is broken.');
    }),
    shareReplay(1),
    catchError(error => {
      console.log(error);
      return of(null);
    })
  );

  return this.configutation$;
}

Now the isEndpoint and isConfiguration methos seems very cumbersome, especially when the configuration grows. I was thinking of using JSON schema and validate the input against the schema file. But if somebody replaces that file for example during build, then it still could go wrong.
Can this be improved?
Is this the TypeScrpt way or how could this be improved?


texts:
I have following data structure

>>> a = [{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}]
>>> b = [{'id': 1, 'age': 12}, {'id': 2, 'age': 21}]

I want to merge the dictionaries present in list b with list a by matching id. (a and b have the same number of entries, but the order can be different.)
So I want following:

[{'age': 12, 'id': 1, 'name': 'a'}, {'age': 21, 'id': 2, 'name': 'b'}]

I am doing it by following:

>>> for ta in a:
...   for tb in b:
...     if ta['id'] == tb['id']:
...       ta.update(tb)
...
>>> a
[{'age': 12, 'id': 1, 'name': 'a'}, {'age': 21, 'id': 2, 'name': 'b'}]
>>>

Is there a better Pythonic way of doing it?


texts: PHP Iterate over Child's Child Efficiently

texts:
I have this code:

foreach($list as $id => $item_array) {
    if (($item_array['approved'] == 1) || $is_admin) {
        include('item.php');
    }
    $temp = $item_array;
    while(!empty($temp['child'])) {
        foreach($temp['child'] as $id => $item_array) {
            if (($item_array['approved'] == 1) || $is_admin) {
                include('item.php');
            }
        }
        if(empty($temp['child']['child'])) {
            unset($temp);
        }
    }
}

which functions but I'm going to need to duplicate the while block 5 times because my items can have up to six levels. There must be a more efficient way to do this, right? (The item.php just outputs HTML based on the array values)

In the simplest form $list would be:

Array
(
    [id] => 1
    [name] => Water
    [date] => 2018-05-14 13:24:22
    [content] => It's Good
    [approved] => 1
    [level] => 0
    [child] => Array([0] => Array(
                    [id] => 2
                    [name] => Hydrogen
                    [date] => 2017-05-07 15:12:14
                    [content] => Part air
                    [approved] => 1
                    [level] => 1)
                )
)

If needed I build $list with:

if($parent != -1) {
        $list[$parent]['child'][] = $this->build_list_array($id, $date, $content, $name, $approved, $level);
} else {
    $list[$id] = $this->build_list_array($id, $date, $content, $name, $approved, $level);
}
function build_comment_array($id, $date, $content, $name, $approved, $level) {
    return array('id' => $id,
                'name' => $name,
                'date' => $date,
                'content' => $content,
                'approved' => $approved,
                'level' => $level);
}


texts: Defining of new, temporary, variables or usage of already known ones?

texts:
I want to check if the length of phone number is appropriate for specified country (let's consider that only some countries have restriction, another countries accept phone number with various length). I have a Map, where the correct pairs are defined so this map can be used as a reference in the condition:

public static ErrCode checkStatePhoneLen(final String state, final String phoneNo)
{
    String  stateTmp = state.trim();
    String  phoneTmp = phoneNo.trim();
    Integer phoneLen = new Integer(phoneTmp.length());

    if ( statePhoneNoMap.containsKey(stateTmp) && !phoneLen.equals(statePhoneNoMap.get(stateTmp)))
    {
        return ERROR;
    }
    return SUCCESS;
}

My questions are:

Is it better to use temporary variables or directly usage of already existed object? I can just use "state.trim()" instead of creating the variable state_tmp and so on. I think that advantages of the solution with temporary variables are better readability and debugging but disadvantages are the effort to create new variable by runtime (or is it optimized someway by compiler?) and more rows of code (but I prefer readability factor more than number of rows factor).
is it better to check if map contains the key and then compare, or to get value for given key and then check if it is not null and compare them? As following example:

Integer definedLen = (Integer) statePhoneNoMap.get(stateTmp);

if (definedLen != null && !definedLen.equals(phoneLen)){

In this code sample, there is needed one more variable, but the condition is clearer. And, there is just one operation upon map (get()) instead of two in previous code (containsKey(), get())

What is better solution? How would you modify this function?


texts:
This code basically just does a Caesar cipher on the contents of the variable "s" with a shift of 1.

Sorry if the comments on the code don't explain it well. I'm quite new to Python and I'm not very good at explaining.

Can this be code be improved?

# Imports the lowercase alphabet as a whole string.
from string import ascii_lowercase

# Returns a list of each char in the given string.
def charSplit(str):
    return [char for char in str]

letters = charSplit(ascii_lowercase)
result = []
finalResult = ""
letterIndex = 0
strIndex = 0
s = "abcde test bla bla bla"
found = False

if __name__ == "__main__":
    while found == False:
        # Checks if the string has been converted to the cipher.
        if len(result) == len(s):
            found = True
        # Adds a space to the result variable if the string index is a space.
        elif s[strIndex] == " ":
            result.append(" ")
            strIndex += 1
        # Checks if the string index is equal to the letter index.
        elif charSplit(s)[strIndex].lower() == letters[letterIndex]:
            result.append(letters[letterIndex - 1])
            strIndex += 1
        #
        else:
            if len(letters) - 1 == letterIndex:
                letterIndex = 0
            else:
                letterIndex += 1
    # Iterates through result and adds each string to the empty string, "finalResult".
    for l in result:
        finalResult += l

    print(finalResult)


texts: Is this the correct usage of ConcurrentDictionary?

texts:
I need to make a simple class that tracks how many clients are listening to a specific item, will be referred to as building hence forth.  I will have a timer running that will check which buildings are active and send updates to them.  While this is occurring, the client will be able connect and disconnect.  This means they will also be modifying the building list as time goes on.

To make sure that I don't have any concurrency issues, I decided to make a simple class that uses a ConcurrencyDictionary<TKey, TValue>.  I don't have a need of the class in the past and want to make sure it is being used correctly as the documentation seems to lack a bit for this class, mostly when it comes to updating values and the like.

/// <summary>
/// Tracks the buildings that are actively being listened to and the number of clients subscribed to the building
/// </summary>
public static class BuildingSubscriptionTracker
{
    /// <summary>
    /// A dictionary of building name and listening client count
    /// </summary>
    private static readonly ConcurrentDictionary<string, int> _buildingsSubscribedTo = new ConcurrentDictionary<string, int>();

    /// <summary>
    /// Get all the buildings that are actively being listened to by clients
    /// </summary>
    /// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> of string</returns>
    public static IEnumerable<string> GetBuildings()
    {
        return _buildingsSubscribedTo.Keys;
    }

    /// <summary>
    /// Get how many clients are listening to updates for this building
    /// </summary>
    /// <param name="buildingName">Name of building to get client listening count for</param>
    /// <returns>A count of how many clients are listening to updates for this building.  If the building is no longer being tracked, this will return 0</returns>
    public static int GetActiveClientCountFor(string buildingName)
    {
        int clientCount;

        if (_buildingsSubscribedTo.ContainsKey(buildingName))
            if (_buildingsSubscribedTo.TryGetValue(buildingName, out clientCount))
                return clientCount;

        return 0;
    }

    /// <summary>
    /// Increment the client count of the given building
    /// </summary>
    /// <param name="buildingName">Name of the building the client wants updates for</param>
    public static void IncrementClientCountFor(string buildingName)
    {
        //If the building doesn't exist, add it and +1 the count
        if (!_buildingsSubscribedTo.ContainsKey(buildingName))
            _buildingsSubscribedTo.TryAdd(buildingName, 0);

        int clientCount;

        _buildingsSubscribedTo.TryGetValue(buildingName, out clientCount);

        _buildingsSubscribedTo.TryUpdate(buildingName, clientCount++, clientCount);
    }

    /// <summary>
    /// Decrements the client count of the given building
    /// </summary>
    /// <param name="buildingName">Name of the building the client wants updates for</param>
    public static void DecrementClientCountFor(string buildingName)
    {
        //If the building doesn't exist, there isn't anything to do
        if (_buildingsSubscribedTo.ContainsKey(buildingName))
        {
            int clientCount;

            //Get how many clients are listening to building so we can properly update it
            if (_buildingsSubscribedTo.TryGetValue(buildingName, out clientCount))
            {
                var newClientCount = clientCount--;

                if (newClientCount < 1)
                {
                    int unusedValue;
                    _buildingsSubscribedTo.TryRemove(buildingName, out unusedValue);
                }
                else
                {
                    _buildingsSubscribedTo.TryUpdate(buildingName, newClientCount, clientCount);
                }
            }
        }
    }
}


texts: Creating 3 sublists based on unique conditions

texts:
I have written the following code for one of my requirements. Kindly help me if I can write this logic in a better.

public class PersonService {
    public PersonCategorized getCategorizedPerson(List<Person> allPersonFromDb) {
        List<Person> adultList = allPersonFromDb.stream().filter(PersonUtil::isAdult).collect(Collectors.toList());
        List<Person> underAgedList = allPersonFromDb.stream().filter(PersonUtil::isUnderAged).collect(Collectors.toList());
        List<Person> seniorCitizenList = allPersonFromDb.stream().filter(PersonUtil::isSeniorCitizen).collect(Collectors.toList());

        return new PersonCategorized(underAgedList, adultList, seniorCitizenList);
    }
}

public class PersonCategorized {
    private List<Person> underAgedPersonList;
    private List<Person> adultList;
    private List<Person> seniorCitizenList;

    public PersonCategorized(List<Person> underAgedPersonList, List<Person> adultList, List<Person> seniorCitizenList) {
        this.underAgedPersonList = underAgedPersonList;
        this.adultList = adultList;
        this.seniorCitizenList = seniorCitizenList;
    }

    public List<Person> getAdultList() {
        return adultList;
    }

    public List<Person> getSeniorCitizenList() {
        return seniorCitizenList;
    }

    public List<Person> getUnderAgedPersonList() {
        return underAgedPersonList;
    }
}

public class Person {
    private int age;
    private String name;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }
}

public class PersonUtil {
    public static boolean isAdult(Person person) {
        return person.getAge() >= 18 && person.getAge() < 60;
    }

    public static boolean isUnderAged(Person person) {
        return person.getAge() >= 0 && person.getAge() < 18;
    }

    public static boolean isSeniorCitizen(Person person) {
        return person.getAge() >= 0 && person.getAge() < 18;
    }
}

One observation I had after posting here is I am iterating over the list 3 times to collect 3 different lists.


texts: Best practice instantiating generic delegates and accessing property getters

texts:
I want to create delegates to access properties of different objects without knowing them in advance.

I have the following definitions

public delegate T MyMethod<K, T>(K data);

public static MyMethod<K, T> CreatePropertyGetter<K, T>(PropertyInfo property)
{
   MethodInfo mi = property.DeclaringType.GetMethod("get_" + property.Name);
   return (MyMethod<K, T>)Delegate.CreateDelegate(typeof(MyMethod<K, T>), mi);
}

where T can be decimal, string, datetime or int

I have some initializing code that will create MyMethod delegates, based on the reflected properties of my object as follows:

foreach (PropertyInfo property in entityType.GetProperties())
{
    switch (property.PropertyType.Name)
    {
        case "System.Decimal":
            return CreatePropertyGetter<T, decimal>(property);
        case "System.DateTime":
            return CreatePropertyGetter<T, DateTime>(property);
        case "System.String":
            return CreatePropertyGetter<T, DateTime>(property);
    }
}

Is there a better way to

create property getters?
enumerate through the supported property types hard-coded as strings?

However, performance is an issue, since these delegates will be called frequently (ticking scenario), so any casting will slow it down. While a more elegant solution is desirable, performance is still my main concern