texts:
This function updates the user last login date on the user collection.  I guess there are too many brackets and much spaghetti. How can I shorten this code?

(function () {
    'use strict';

    var database = require('mongodb');
    var util = require('util');

    var constants = require('../constants');

    var dbhelper = {
        updateLastSeenDate: function (me) {
            database.connect(constants.variables.connection, function (err, db) {
                if (err) {
                    db.close();
                    throw err;
                }
                var bsonID = database.BSONPure.ObjectID(me);
                var collection = db.collection('users');
                collection.findOne({
                    _id: bsonID
                }, function (err, result) {
                    if (result) {
                        result.lastLoginDate = Date.now();
                        collection.update({
                            _id: bsonID
                        }, result, function (err, u) {
                            if (err) {
                                db.close();
                                throw err;
                            }
                            util.log('Update complete: updateLastSeenDate');
                            db.close();
                        }); //end of update
                    }
                });
            });
        }
    };

    module.exports = dbhelper;
}());


texts:
I want to ask for code review for my JavaScript implementation of Flatten_dictionary about this coding challenge for "Flatten a Dictionary" can be found at pramp:

  Given a dictionary dict, write a function flattenDictionary that
  returns a flattened version of it .

  If you’re using a compiled language such Java, C++, C#, Swift and Go,
  you may want to use a Map/Dictionary/Hash Table that maps strings
  (keys) to a generic type (e.g. Object in Java, AnyObject in Swift
  etc.) to allow nested dictionaries.

  Example:

  Input:

dict = {
    "Key1" : "1",
    "Key2" : {
        "a" : "2",
        "b" : "3",
        "c" : {
            "d" : "3",
            "e" : "1"
        }
    }
}

  Output:

{
    "Key1" : "1",
    "Key2.a" : "2",
    "Key2.b" : "3",
    "Key2.c.d" : "3",
    "Key2.c.e" : "1"
}

  Important: when you concatenate keys, make sure to add the dot character between them. For instance concatenating Key2, c and d the result key would be Key2.c.d.

#implementation#1

function flattenDictionary(dict) {
 //flattened dictionary = {}
  //iterate through dictionary
  //check for type of value for each key
     //if value is another dictionary, i will recurivec callthis appending it to the dictionary
  let flattened = {}
  let keys = Object.keys(dict) //give me an array of keys
  for (let i=0; i< keys.length; i++){
    if (typeof dict[keys[i]] === "object") {
      let flatObj = flattenDictionary(dict[keys[i]])
      let newKeys = Object.keys(flatObj) //[a,b]
      for (let j=0; j<newKeys.length; j++) {
        if (newKeys[j] === "") {
          flattened[keys[i]] = flatObj[newKeys[j]]
        } else {
           flattened[keys[i]+"."+newKeys[j]] = flatObj[newKeys[j]]
        }

      }
      //get back to this
    } else {
      flattened[keys[i]] = dict[keys[i]]
    }
  }
  return flattened
}

#implementation#2

function flattenDictionary(dict) {
  // your code goes here
  let results = {};
  let currKey = "";

  function flattenUtil(dict) {
    // 1. 'Iterate' over the dictionary
    // Keys will either be 'Key_' for outermost level
    // or a letter/empty string for inner levels
    // 2. If the value is an int/string, append onto output dictionary
    // else if the value is a dictionary, recurse
    // 3. Base case: dict empty, return

    Object.keys(dict).forEach(key => {
      if (typeof dict[key] === 'object') {
        if (!currKey) {
          currKey += key;
        } else {
          currKey += `.${key}`;
        }
        flattenUtil(dict[key]);
      } else {
        if (!currKey) {
          results[`${key}`] = dict[key];
        } else {
          if (!key) {
            results[`${currKey}`] = dict[key];
          } else {
            results[`${currKey}.${key}`] = dict[key];
          }
        }
      }
    });
  }

  flattenUtil(dict);
  return results;
}


texts:
I am a beginner and have created this bash script that helps me with creating bash scripts.

The script shows no issues on shellcheck.net

The code can be found here. https://github.com/plutesci/Iwanttobash/blob/master/Icode.bash

I would like some feedback from more experienced users. Any suggestions or thoughts about this.

#!/bin/bash
# This Program is to Show user the commands and or to create a bash script
# to execute this program type at terminal ./ICode.bash
# I am attempting to have the program open the named file with the header
# shebang at the top #!/bin/bash as it is not there you will need to add  it.
# created by plutesci for self or public use.

clear
# Banner shows a banner to install should it not show on Ubuntu is.
# sudo apt-get install sysvbanner
# banner "Icode"
# figlet is a banner aswell to install that just type in your terminal
# sudo apt-get install figlet
figlet "Icode"
echo Showing a way to use the command line steps to start a Hello World   program
echo Where you see test.bash, Please rename test.bash
echo Follow Steps Below...
echo ####################
echo "echo '#!/bin/bash' > test.bash " #change test
echo "'echo Hello World' >> test.bash " # change test.bash
echo "chmod 755 test.bash"  # change test.bash
echo "nano test.bash"   # change test.bash
echo "Exit Ctrl c"
echo ###################
#echo '#!/bin/bash' >> "$text.bash"

# I want to add an option to ask user if they want to start a new bash \
# program yes \ no?
# if yes\Yes query user for new name, What to call this bash ? ......
# I am happy with the the selection part but would like it going into a      menu
# afterwards with press 9 return to previous menu

######## Things to improve on.

# when playing i found a program called openvt, It would be great to have the
# bash program open virtual termin and run the output
echo -n "Please Enter a Filename For Your New Bash Script > "
read -r text
echo "Your New Bash Script is named: $text"

# chmod +x $text.bash

# I need to figure out how to add .bash to the $text varable

selection=
until [ "$selection" = "0" ]; do
echo "
ICODE MENU
1 - Start a new Bash Script
2 - Make it Executable
3 - Run Bash Program
4 - Continue working on script
5 - Start python idle
6 - Open a new shell
7 - Create Automatic Shell scripts
8 - Delete the script
9 - Help
0 - Exit Program
"
    echo -n "Enter selection: "
    read -r selection
    echo ""
    case $selection in
    1 ) echo "#!/bin/bash" > "$text.bash" ; nano "$text.bash"  ;;
    2 ) chmod 755 "$text.bash" ;;
    3 ) gnome-terminal ; echo "./$text.bash" ;;
    4 ) nano "$text.bash" ;;
    5 ) idle ;;
    6 ) gnome-terminal ;;
    7 ) nano ;; # would be something like grep a special crafted document
    8 ) echo "#!/bin/bash" > "$text.bash" ;;
    9 ) cat icodehelp ;;
    0 ) exit ;;
    * ) echo "Please enter 1, 2, 3, 4, 5, 6, 7, 8, 9, or 0"
    esac
done

# Things I would like to add to the program would be a auto statment maker
# and auto create bash programs like open the randomly grep for certain
# keywords, and random cut from a libary of scripts 10 - 100 scripts
# run it in a virtual terminal, looking for errors and print out example
# 3 out of 100  run with no errors, would you like to view these?
# 17 out of 100 return a slight error, would you like to inspec these.
# 83% percent should be removed. something like that just visualising it   out

# My first bash application would like any help, still trying to learn how
# github works


texts: Immediately send redirect response, preserving session data

texts:
This question is for Laravel 4 only, as the relevant parts are completely refactored in the upcoming Laravel 5.

I have written an helper function for validation, so I only have to put this in controllers:

public function postAdd()
{
    validate([
        'foo' => 'required',
        'bar' => 'required',
    ]);

    // process data...
}

I love it!

And here is the helper:

function validate($rules)
{
    $validator = Validator::make(Input::all(), $rules);

    if ($validator->fails())
    {
        $request = Request::instance();

        $response = Redirect::to(URL::previous())
            ->withInput()
            ->withErrors($validator);

        Session::save();
        $response->send();
        App::terminate($request, $response);
        exit;
    }
}

My concerns are mainly about the four last lines. The point is to immediately send the response, otherwise I have to return it from the helper, then handle the helper result (Response|null) in the controller (quite easy, but I want really thin controllers).

I did my best to return this response the more gracefully possible. Session data obviously has to be saved, and possible "finish" callbacks are triggered. But, looking at Application's run() and getStackedClient() method, I'm afraid of missing something.

So, am I missing something? Could this code be further improved?


texts:
I have written a piece of MATLAB code that (hopefully) calculates CECT. I have two matrices of psychophysiological measures - one for brain data, one for heart rate; both are of the format epochs * times (i.e., multiple epochs of 10-second long intervals). The supposed outcome is to calculate the correlation between EEG in a short window using narrow bins, and heart rate in a longer window using wider bins. The basic idea is that an early brain effect predicts a heart rate speedup a few seconds later. In the words of the author (from the paywalled paper in the link):

  To allow CECT computation across the 350–420 trials available for analysis per individual after artifact screening, EEG segments were divided into 50 bins of 15.625 ms each, ranging from 0 ms (stimulus onset) to 781.25 ms. HP segments were divided into 10 bins of 500 ms, ranging from 0–5 s. Next, CECTs were computed by correlating (Pearson’s r) each EEG bin with each HP bin across trials within subjects, resulting in a 10 × 50 cross-correlation CECT matrix.

My code differs from that a bit in that I calculate for overlapping sliding windows instead of non-overlapping consecutive bins. Also, my windows are slightly different. However, what I'm mostly concerned with is that I have the hunch my code is extremely suboptimal.

Currently, the procedure is that I For-loop over brain data bins, collect a vector of heart rate data using a For loop, do a correlation between the heart bin vector and the single brain bin, store the resulting vector of correlations, and proceed to the next vector.

Importantly, the search windows and the bin windows for heart and brain data are of different length (heart rate variations are slower than brain effects).
Also, this will in the end be calculated for multiple subjects; I have omitted this dimension of the data.

% data is a matrix of format (channels * times * epochs)
% times is a matrix of time points corresponding to sampling points

% CECT is supposed to be a matrix of correlation coefficients,
% dimensions (braintime * hearttime)

scalefac = 1000/samplingrate;

brainchannel = 12;  % channel # for brain data
heartchannel = 62;  % channel # for heart data

brainbin = 10;      % bin length for brain data (symmetric, in msec)
heartbin = 250;     % bin length for heart data (= 500 msec window)

heart = 5500;       % max point (from zero, in msec) for heart data
brain = 2500;       % max point (from zero, in msec) for brain data
first = -500;       % first point (from zero, in msec)

yy = 1;             % counter for looping over brain data
for x = find(times>first,1):find(times>brain,1)
    t0 = (x-brainbin/scalefac);
    t1 = (x+brainbin/scalefac);
    eeg = mean(squeeze(data(brainchannel,t0:t1,:)),1);
    p=1;
    clear hps
    for y = find(times>first,1):find(times>heart,1)
        t0 = (y-heartbin/scalefac);
        t1 = (y+heartbin/scalefac);

        hps(p,:) = mean(squeeze(data(heartchannel,t0:t1,:)),1);
        p = p+1;    % counter for looping over heart data
    end
    CECT(yy,:) = corr(squeeze(eeg).',hps.');
    yy = yy+1;
end

How can I make this code less awful (faster, more structured)?


texts:
This is my current method for populating the sub-items of ListView controls. I like this method for two reasons...

1) I don't have to keep up with the display order of the columns.

2) If I enable column re-ordering, I don't have to change anything with the code.

So, the question is... Is this a good approach? Can it be improved?

Note: I'm not too happy about declaring Result As Object. It seems like there should be a better way to handle that, but it's the only way I could get it to working.

Private Function RetrieveItem(Of T)(ByVal displayIndex As Integer) As T
    Dim Result As Object = If(GetType(T) Is GetType(ListViewItem), New ListViewItem, New ListViewItem.ListViewSubItem)
    Select Case displayIndex
        Case ColumnHeader1.DisplayIndex
            Result.Text = "First Item"
            Result.Tag = "First"
        Case (ColumnHeader2.DisplayIndex)
            Result.Text = "Second Column"
            Result.Tag = "Second"
        Case ColumnHeader3.DisplayIndex
            Result.Text = "Third Column"
            Result.Tag = "Third"
        Case ColumnHeader4.DisplayIndex
            Result.Text = "Fourth Column"
            Result.Tag = "Fourth"
    End Select
    Return Result
End Function

Example Usage...

Dim item As ListViewItem = RetrieveItem(Of ListViewItem)(0)
For i As Integer = 1 To ListView1.Columns.Count - 1
    item.SubItems.Add(RetrieveItem(Of ListViewItem.ListViewSubItem)(i))
Next
ListView1.Items.Add(item)

Here is the example I came up with using @MarkHurd's suggestion of using a Widening CType Operator...

Private Class LVI
    Public Name As String
    Public Text As String
    Public Tag As Object
    Public Sub New(ByVal name As String, ByVal text As String, ByVal tag As Object)
        Me.Name = name
        Me.Text = text
        Me.Tag = tag
    End Sub
    Public Shared Widening Operator CType(ByVal item As LVI) As ListViewItem
        Dim Result As New ListViewItem(item.Text)
        Result.Name = item.Name
        Result.Tag = item.Tag
        Return Result
    End Operator
    Public Shared Widening Operator CType(ByVal item As LVI) As ListViewItem.ListViewSubItem
        Dim Result As New ListViewItem.ListViewSubItem
        Result.Text = item.Text
        Result.Name = item.Name
        Result.Tag = item.Tag
        Return Result
    End Operator
End Class

Private Function RetrieveItem(ByVal index As Integer) As LVI
    Select Case index
        Case ColumnHeader1.DisplayIndex : Return New LVI("1", "First Column", "one")
        Case ColumnHeader2.DisplayIndex : Return New LVI("2", "Second Column", "two")
        Case ColumnHeader3.DisplayIndex : Return New LVI("3", "Third Column", "three")
        Case ColumnHeader4.DisplayIndex : Return New LVI("4", "Fourth Column", "four")
        Case Else : Return Nothing
    End Select
End Function

Example usage...

Dim item As ListViewItem = RetrieveItem(0)
For i As Integer = 1 To ListView1.Columns.Count - 1
    item.SubItems.Add(RetrieveItem(i))
Next
ListView1.Items.Add(item)

I like both of these approaches, but I feel like the first is shorter and easier to implement, so I lean towards the first option.


texts: adding properties together from list of objects using LINQ

texts:
Looking to see if there is a simpler way to achieve this. I would love if I could keep the return as a one-line LINQ expression. I want to grab the total number of hints used, which can be more than one.

public int hintsUsed
{
    get
    {
        int i = 0;
        questions.ForEach(q => i += q.hintsUsed);
        return i;
    }
}


texts: Count the number of digits in an integer using F# and log10

texts:
This code counts the number of digits in an integer.

let digitCount number = (int) (log10 ((float)number)) + 1;

For instance, it tells us 123456789 has 9 digits.

let input = 123456789;
printfn "%i has %i digits" input (digitCount input);

https://dotnetfiddle.net/nxuoah

A weakness of the code is that it uses two casts. Can we use math to count the number of digits in an integer without having to cast twice? The reason to cast to a float is to make the type compatible with a the log10 function. The reason to cast back in to an integer is to represent a "count" of digits instead of a "measure" of digits.

A second, related weakness of the code is the number of parentheses, which makes the code more difficult to read.


texts:
I have this function that gets an item passed from another function, together with the subtotal and the fee of the item. The function has to act as fast as possible, as other people also want the item. However, the function seems to take a very long time, and almost never ends up buying the actual item because it was too late.

def buy(self, listingid, subtotal, fee):
    print('ATTEMPT')
    buy_url = BUY_URL + listingid
    values = {'sessionid' : self.sessionid,
              'currency' : '3',
              'subtotal' : str(subtotal),
              'quantity' : '1',
              'total' : str(subtotal + fee),
              'fee' : str(fee)
              }
    headers = {'Referer' : BASE + urllib.parse.quote(self.item)}
    print(buy_url, values, headers)
    post = urllib.parse.urlencode(values)
    binary_data = post.encode('utf-8')
    request = urllib.request.Request(buy_url, binary_data, headers)
    response = urllib.request.urlopen(request).read()
    data = json.loads(response.decode('utf-8'))

Is there any way I can (codewise) speed this function up? There are no exceptions, so that's not to worry about.

Note: I have removed the print()s in the real function


texts:
Given an array nums of n integers where n > 1,  return an array output
  such that output[i] is equal to the product of all the elements of
  nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).

  Follow up: Could you solve it with constant space complexity? (The
  output array does not count as extra space for the purpose of space
  complexity analysis.)

My solution

public class ProductExceptSelf {
    /**
     * Approach 1:- Find the left[i] at i containing all the left multiplication. Do same with right[i]
     */
    public int[] productExceptSelf(int[] nums) {

        int size = nums.length;

        int[] output = new int[size];
        int[] left = new int[size];
        int[] right = new int[size];

        int temp = 1;
        // Start filling up left array
        for (int i = 0; i < size; i++) {
            left[i] = temp;
            temp = temp * nums[i];
        }

        // Again set the temp to 1
        temp = 1;

        // Start filling up right array
        for (int i = size - 1; i >= 0; i--) {
            right[i] = temp;
            temp = temp * nums[i];
        }

        // Final traversal and return sum array.
        for (int i = 0; i < size; i++) {
            output[i] = left[i] * right[i];
        }

        return output;
    }
}

Please help me to improve Auxilary space, code readibility and any best practice if I am missing.


texts: Python/Pandas code creating 12 month product balance forecast

texts:
I have an input DataFrame with one row per product with balances, rates, etc. I want to be able to take that starting balance, and other inputs from the row (characteristics of the product), and forecast out 12 months of balances.  What is the best approach to turn this one row per product information (there are a lot of individual products) and turn it into a summary forecast 12 months forward looking?  The below is an example of one type of product that would have to be modelled.

The below code works, but I would like to know whether there is a better way overall to create forecasts with scenarios using python, pandas or numpy.

Code that gets me from one to the other:

Creates generator function that creates Ordered Dict, when called in pandas DataFrame outputs the example output.

EDIT: Added imports and sample dataframe

# Add relevant packages
import pandas as pd
pd.options.display.float_format = '{:.2f}'.format
import numpy as np
import datetime as dt
from collections import OrderedDict
from dateutil.relativedelta import relativedelta
%matplotlib inline

# SAMPLE DATA

df = pd.DataFrame({
 'balance': {1: 1500, 2: 700},
 'freq': {1: 999, 2: 999},
 'maturity': {1: '2018-01-31', 2: '2018-01-31'},
 'period': {1: 'months', 2: 'months'},
 })

def dmd_flow(balance, start_date, num_periods, run_off_rate, new_funds_rate, int_rate, period='monthly'):

    """
    Implements the cash flow modeling for demand products

    Arguments:
    balance -- initial balance of product at t0
    start_date -- calendar date of t0
    num_periods -- number of period to model
    run_off_rate -- annualized rate at which deposit runs off- straight line
    new_funds_rate -- annualized rate at which funds increase (net)
    int_rate -- rate paying on deposit which would be used if modeling interest payable
    period -- the period used for modeling i.e. monthly, annual

    Returns:
    liq_sched -- a schedule of liquidity based on the inputs ordered by time (ordered dictionary)
    """

    p=1
    b_bal = balance
    e_bal = balance
    current_date = start_date

    while p <= num_periods:
        if period == 'monthly':
            e_bal = round(b_bal - (balance*1/12*run_off_rate), 4)
            e_bal += round((balance*1/12*new_funds_rate), 4)
        if period == 'annual':
            e_bal = round(b_bal - (balance*run_off_rate), 4)
            e_bal += round((balance*new_funds_rate), 4)

        yield(OrderedDict([('Month', current_date),
                           ('Period', p),
                           ('Beg Bal', b_bal),
                           ('End Bal', e_bal),
                          ]))
        p += 1
        current_date += relativedelta(months=+1, day=31)
        b_bal = e_bal

def create_timeseries_df(input=None, func=None, args=(dt.date(2018,1,31), 0, 0, 0, 0, 'monthly')):
    '''takes a series as an input and applies the fuctions to create the timeseries in the right shape'''
    new_df = input['balance'].apply(
     func, args=args)
    return pd.DataFrame([o_dict for gen in new_df for o_dict in gen])

out_df = create_timeseries_df(df, func=dmd_flow, args=(dt.date(2018,1,31), 12, 0, .10, .03, 'monthly'))
out_df.groupby(['Month', 'Period'])[['Beg Bal', 'End Bal']].sum()

Example input DF (can use sample DF included above, and run in order to get the resulting output:

Example Output Created using code:


texts: Order list of movies and save sorting in cookies

texts:
I did this project and I'm going back over it and trying to optimize some stuff. This is the movies_controller.rb file, which is basically a table that I need to sort based on user parameters. What I really want to know here, is there a better way to save and assign the @sort and @ratings_filter? I just need to save them between sessions.

This is my first "revised" attempt:

def index
  @movies = Movie.all
  @all_ratings = Movie.all_ratings
  @ratings_filter = @all_ratings

  (params[:sort]) ? (@sort = params[:sort]) : (@sort = session[:sort])

  (params[:ratings] and params[:commit] == 'Refresh') ?
  (@ratings_filter = params[:ratings].keys) : (@ratings_filter= session[:ratings] || @all_ratings)

  #save cookies
  if params[:sort] != session[:sort] or params[:ratings] != session[:ratings]
    session[:ratings] = @ratings_filter
    session[:sort] = @sort
    redirect_to movies_path :sort => @sort, :ratings => @ratings_filter# and return
  end

  @movies = Movie.sort_by_and_rating(@sort, @ratings_filter)

end

Here's the original for comparison:

    #params[:commit] has the value of the last button pressed
if (params[:ratings] and params[:commit] == 'Refresh')
    @ratings_filter = params[:ratings].keys
elsif params[:ratings]
    @ratings_filter = params[:ratings]
else
    @ratings_filter = session[:ratings] || @all_ratings
end

#@ratings_filter = params[:ratings].keys || session[:ratings] || @all_ratings

@sort = params[:sort] || session[:sort]

#save cookies
if params[:sort] != session[:sort] or params[:ratings] != session[:ratings]
    session[:ratings] = @ratings_filter
    session[:sort] = @sort
    redirect_to movies_path :sort => @sort, :ratings => @ratings_filter# and return
end

@movies = Movie.sort_by_and_rating(@sort, @ratings_filter)

Here's my GitHub if you need other files for context.


texts:
I decided to build a GUI that would seemlessly create user interfaces for validation functions, functions that check if a string satisfies given rules.

An example 'hello, world!' usage is:

from gui_validation import gui_validation

def is_valid_salutation(salutation):
    """
    Salutations to be valid must start with one of:
         ['hello', 'hi', 'howdy'] + ',' [COMMA]
    and must end with '!' [EXCLAMATION MARK]

    >>> is_valid_salutation('howdy, moon!')
    True
    >>> is_valid_salutation('random phrase')
    False
    """
    return any(salutation.startswith(i+',') for i in ['hello', 'hi', 'howdy']) \
           and salutation.endswith('!')

if __name__ == "__main__":
    gui_validation(is_valid_salutation)

As you can see the only argument required is the function itself.

gui_validation.py

"""
General purpose user input validation GUI.
"""
import tkinter
from tkinter.constants import X
from tkinter import messagebox

def gui_validation(validator, title=None, text=None, button_text="Validate"):
    """
    Provides a general purpose gui to validate user input.
    The user will be prompted to enter a string and will be
    given feedback by the `validator` function.

    This interface avoids verbosity and assumes the title to be
    the `validator` name and the text to be the `validator` doc if not +
    told explicitly.
    """
    if title is None:
        title = validator.__name__.replace('_',' ').capitalize()
    if text is None:
        text = validator.__doc__

    def validate():
        if validator(user_input.get()):
            messagebox.showinfo("Input valid.",
                                "Congratulations, you entered valid input.")
        else:
            messagebox.showerror("Input NOT valid.",
                                 "Please try again and enter a valid input.")

    root = tkinter.Tk()
    root.wm_title(title)

    title_label = tkinter.Label(root, text=title, font='25px')
    title_label.pack(fill=X, expand=1)

    text_label = tkinter.Label(root, text=text, font='20px')
    text_label.pack(fill=X, expand=1)

    user_input = tkinter.Entry(root)
    user_input.pack()

    button = tkinter.Button(root, text=button_text, command=validate)
    button.pack()

    root.mainloop()

I was wondering:

Would a class make the code clearer or just more verbose?
Am I asking too little, should I force the user to give more details?
Is it OK to use big fonts? The small fonts are much less legible to me.
Any other improvement?


texts:
I want to read a file containing comma-separated values, so have written a finite state machine:

private IList<string> Split(string line)
{
    List<string> values = new List<string>();
    string value = string.Empty;
    ParseState state = ParseState.Initial;
    foreach (char c in line)
    {
        switch (state)
        {
            case ParseState.Initial:
                switch (c)
                {
                    case COMMA:
                        values.Add(string.Empty);
                        break;
                    case QUOTE:
                        state = ParseState.Quote;
                        break;
                    default:
                        value += c;
                        state = ParseState.Data;
                        break;
                }
                break;
            case ParseState.Data:
                switch (c)
                {
                    case COMMA:
                        values.Add(value);
                        value = string.Empty;
                        state = ParseState.Initial;
                        break;
                    case QUOTE:
                        throw new InvalidDataException("Improper quotes");
                    default:
                        value += c;
                        break;
                }
                break;
            case ParseState.Quote:
                switch (c)
                {
                    case QUOTE:
                        state = ParseState.QuoteInQuote;
                        break;
                    default:
                        value += c;
                        break;
                }
                break;
            case ParseState.QuoteInQuote:
                switch (c)
                {
                    case COMMA:
                        values.Add(value);
                        value = string.Empty;
                        state = ParseState.Initial;
                        break;
                    case QUOTE:
                        value += c;
                        state = ParseState.Quote;
                        break;
                    default:
                        throw new InvalidDataException("Unpaired quotes");
                }
                break;
        }
    }

    switch (state)
    {
        case ParseState.Initial:
        case ParseState.Data:
        case ParseState.QuoteInQuote:
            values.Add(value);
            break;
        case ParseState.Quote:
            throw new InvalidDataException("Unclosed quotes");
    }

    return values;
}

Yes, I know the advice about CSV parsers is "don't write your own", but

I needed it quickly and
our download policy at work would take several days to allow me to
get open source off the 'net.

Hey, at least I didn't start with string.Split() or, worse, try using a Regex!

And yes, I know it could be improved by using a StringBuilder, and it's restrictive on quotes in the data, but

performance is not an issue and
this is only to generate well-defined test data in-house,

so I don't care about those.

What I do care about is the apparent trailing block at the end for mopping up all the data after the final comma, and the way that it's starting to look like some sort of an anti-pattern down there, which was exactly the sort of thing that "good" patterns such as a FSM were supposed to avoid.

So my question is this: is this block at the end some sort of anti-pattern, and is it something that's going to come back to bite me in the future?


texts: Phrase matching between two Strings in Ruby

texts:
I've written a phrase-matching method to return the longest matching phrase from two Strings in Ruby. My method looks like this and works as expected:

class String
  def phrase_in_common(other)
    n = [size, other.size].min
    while n > 0 do
      other_words = other.downcase.split.each_cons(n)
      string_words = split.each_cons(n)
      matching_words = string_words.find { |cons_words| other_words.include?(cons_words.map(&:downcase)) }
      return matching_words&.join(' ') if matching_words
      n -= 1
    end
  end
end

>> string = "Hello world, please come to my house next week"
>> other = "Hello friends, please come to my party next week"
>> string.phrase_in_common(other)
=> "please come to my"

My question is, can (and should) this be accomplished in a more Ruby way, perhaps by replacing the while with an Enumerable method of some kind?

To clarify, the phrase-matching should be based on words, so for example:

>> "this phrase".phrase_in_common("his phrase")
=> "phrase"

Also, note that the method is case-insensitive in matching and uses the case of the subject String for the return value:

>> "Greatest Show On The Earth".phrase_in_common("Silliest Show on the Earth")
=> "Show On The Earth"


texts:
I wrote this basic calculator class using php.It will only execute the basic arithmetics operations so any suggestion for new functions add and improvements will be accepted. Thank you.

<?php

class Calculator{

public $x , $y , $z;

    public function __construct($x,$y,$z){
        $this->x = $x;
        $this->y = $y;
        $this->z = $z;
    }

    public function calc(){
        try{
            if($this->x != 0 && $this->z != 0){

                switch($this->y){
                case '+':
                return ($this->x + $this->z);
                break;

                case '-':
                return ($this->x - $this->z);
                break;

                case '/':
                return ($this->x / $this->z);
                break;

                case '*':
                return ($this->x * $this->z);
                break;

                }
            } else {

                throw new Exception('Operations with 0 not alloewd!');

            }
        }
        catch(Exception $e){
            return $e->getMessage();
        }
    }
}
?>


texts: Creating users with different roles using .Net Identity 2.0 within Entity Framework

texts:
I am using .Net Identity 2.0 with Entity Framework 6.0. I have a Person class inheriting IdentityUser. I have a Teacher (has additional Title property) and Student (has additional StudentNumber property) class inheriting from the Person class. I also have their corresponding roles in the database: Student and Instructor (or teacher).

I wonder if the code below is the most efficient way of creating users with specific roles, it seems to be a redundant but I could not figure a shorter way:

 gEchoLuDBContext _db = new gEchoLuDBContext();

        var userStore = new UserStore<IdentityUser>(_db);
        var userManager = new UserManager<IdentityUser>(userStore);

        foreach (ListItem role in rb_Roles.Items)
        {
            if (role.Selected)
            {
                var user = new Person()
                {
                    UserName = txt_Username.Text,
                    FirstName = txt_Firstname.Text,
                    LastName = txt_Lastname.Text,
                    Email = txt_Email.Text
                };

                if (role.Text == "Student")
                {
                    user = new Student()
                    {
                        StudentNumber = " ",
                        UserName = txt_Username.Text,
                        FirstName = txt_Firstname.Text,
                        LastName = txt_Lastname.Text,
                        Email = txt_Email.Text
                    };
                }
                else if (role.Text == "Instructor")
                {
                    user = new Teacher()
                    {
                        Title = "",
                        UserName = txt_Username.Text,
                        FirstName = txt_Firstname.Text,
                        LastName = txt_Lastname.Text,
                        Email = txt_Email.Text
                    };
                }

                IdentityResult result = userManager.Create(user, txt_Password.Text);
                if (result.Succeeded)
                {
                    IdentityResult result2 = userManager.AddToRole(user.Id, role.Text);
                    if (!result2.Succeeded)
                    {
                        lbl_Result.Text = "The user created successfully. But, the selected roles are not assigned!";
                    }
                }
            }
        }


texts: Fill a vector with uniformly distributed random complex numbers

texts:
I want to fill an array of complex numbers using a uniform generator. I thought up the next code. (Complex is a simple fixed-point complex data type.)

std::generate(inputData.begin(), inputData.end(), []()-> Complex {
    static std::default_random_engine generator;
    static std::normal_distribution<double> distribution(0.0, 0.5); // mean = 0.0, stddev = 0.5
    return Complex(distribution(generator), distribution(generator));
});

So I though up using static variables within the lambda expression. Is that inefficient? Alternatively I would create them outside of the lambda, and put them on the capture list. But I don't need them outside of the lambda, so this seems cleaner to me.


texts: Quicksort implementation in TASM assembly

texts:
Is this assembly (TASM) implementation of quicksort efficient, and does this code follow common best practices?

IDEAL
MODEL small
STACK 100h
DATASEG
; --------------------------
; Your variables here
; --------------------------
arr db 3,1,2
var db ?
CODESEG
proc Swap
;swap two values
;1,2 values to be swaped
push bp
mov bp,sp
push di
push bx
push ax
push cx
xor ax,ax
xor cx,cx
mov bx,[bp+6];value to be swapped
mov di,[bp+4];
mov ah,[bx]
mov ch,[di]
mov [bx],ch
mov [di], ah
pop cx
pop ax
pop bx
pop di
pop bp
ret
endp Swap
proc Split
;sorting the array by valus greater then the pivot and values lower then the pivot
;1. start of the array
;2.end of the array
;3. pivot
push bp
mov bp,sp
push ax
push bx
push cx
push dx
push di
mov bx,[bp+8];start of the array(offset)
mov di,[bp+6]; end of the array(offset)
mov ax,[bp+4];pivot
push di ;offset to be swapped
add ax,bx
push ax ;offset to be swapped
call Swap
mov ax,bx
mov cx,di
sub cx,bx
inc cx
lpivot:
    mov dh,[byte ptr bx]
    cmp dh,[byte ptr di]
    jae greater
    push ax;offset to be swapped
    push bx;offset to be swapped
    call Swap
    inc ax
    greater:
    inc bx
loop lpivot
push ax;offset to be swapped
push di;offset to be swapped
call Swap
mov [bp+6],ax
pop di
pop dx
pop cx
pop bx
pop ax
pop bp
ret 2
endp Split
proc QuickSort
;sort an array(quicksort implention) usually around O(n log n) complexiy worst case O(n^2)
;1.strat of the array(offset)
;2.end of the array (offset)
push bp
mov bp,sp
push ax
push bx
push cx
push di
mov bx,[bp+6];start of the array(offset)
mov di,[bp+4];end of the array(offset)
cmp bx,di
jae return ;if the array size is 1 or 0 return
push bx;start of the array(offset)
push di;end of the array(offset)
call PickPivot
pop ax;pivot
push bx;start of the array(offset)
push di;end of the array(offset)
push ax;push pivot
call Split
pop ax;new pivot
push bx;start of the array(offset)
dec ax
push ax
call QuickSort
inc ax
inc ax
push ax
push di
call QuickSort
return:
pop di
pop cx
pop bx
pop ax
pop bp
ret
endp QuickSort
proc PickPivot
;1.strat of the array(offset)
;2.end of the array (offset)
push bp
mov bp,sp
push bx
push di
mov bx,[bp+6];start of the array(offset)
mov di,[bp+4];end of the array(offset)
add bx,di
shr bx,1
mov [bp+6],bx
pop di
pop bx
pop bp
ret 2
endp PickPivot
start:
mov ax, @data
mov ds, ax
xor ax,ax
mov bx,offset arr
mov di,offset var
dec di
push bx
push di
call QuickSort
exit:
mov ax, 4c00h
int 21h
END start


texts:
For practice, I decided to write a run-length decoder. For example:

basic_run_length_decode("1A2B3C")
=> 'ABBCCC'

basic_run_length_decode("5A10Z10J")
=> 'AAAAAZZZZZZZZZZJJJJJJJJJJ'

It ended up getting long, but that's mostly because I wanted try incorporating the partition-by function from Clojure. It seemed like it would work nicely here, and it did. It required me to write that function though since Python doesn't seem to have anything equivalent. I also "stole" grouper from the "recipe" section of the itertools docs. Clojure has both of these functions as part of its standard library, so that's what I thought of while writing this.

Basically, it works by cutting the string into groups of digits and non-digits, pairing them into [digits, word] pairs, then parsing the digits and doing some string multiplication.

What I'd like commented on mainly:

partition_by. I tried to see if there was a sane way of using something like takewhile + drop_while, but both of those functions consume an extra element after the predicate flips, which caused problems. I opted to just do manual iteration, but it's quite verbose.
Anything else that I may be doing the hard way.

Note, it actually allows for multiple characters per number.

basic_run_length_decode("10AB10CD")
=> 'ABABABABABABABABABABCDCDCDCDCDCDCDCDCDCD'

I thought about raising an error, but decided to just allow it. This is apparently a type of possible encoding, and it cost me nothing to allow it.

from itertools import zip_longest
from typing import Callable, Any, Iterable, TypeVar, Generator, List

T = TypeVar("T")
# Emulating https://clojuredocs.org/clojure.core/partition-by
def _partition_by(f: Callable[[T], Any], iterable: Iterable[T]) -> Generator[List[T], None, None]:
    """Splits off a new chunk everytime f returns a new value.
    list(partition_by(lambda n: n < 5, [1, 2, 3, 6, 3, 2, 1])) => [[1, 2, 3], [6], [3, 2, 1]]
    """
    last_value = object()  # Dummy object that will never be equal to anything else
    chunk = []

    for x in iterable:
        returned = f(x)

        if returned == last_value:
            chunk.append(x)

        else:
            if chunk:
                yield chunk

            chunk = [x]

        last_value = returned

    if chunk:
        yield chunk

# Recipe from https://docs.python.org/3.8/library/itertools.html#itertools.takewhile
def _grouper(iterable, n, fillvalue=None):
    """Collect data into fixed-length chunks or blocks"""
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

def _invalid_encoded_error(message: str) -> ValueError:
    return ValueError(f"Invalid encoded string. {message}")

def basic_run_length_decode(encoded_string: str) -> str:
    """Decodes a string in the form of <number><chars><number><chars>. . .
    basic_run_length_decode("1A2B3C") => 'ABBCCC'"""
    if encoded_string and not encoded_string[0].isdigit():
        raise _invalid_encoded_error("First character must be a number.")

    chunks = _partition_by(lambda c: c.isdigit(), encoded_string)

    acc = []
    for raw_n, raw_word in _grouper(chunks, 2):
        if not raw_word:
            raise _invalid_encoded_error("Trailing numbers without character at end of encoded string.")

        n = int("".join(raw_n))  # Should never throw as long as the very first char is a digit?
        word = "".join(raw_word)

        acc.append(n * word)

    return "".join(acc)


texts:
I have written some Flex and Bison code for parsing a file.

The following is a simplified example of the input file as well as the code used for parsing.

There are a few things I am not satisfied with:

The way keywords are recognized (Marked with [1] in tokenizer.lex), because the rules also recognize the following whitespaces, which are not part of the keyword itself.
The part after the colon (:) is quite unflexible. If there is a whitespace at the beginning, it is always recognized as STRING.

There has been a nicer solution before, but that one couldn't handle spaces in the right hand side string.

I am mostly interested in the issues I mentioned above but I'm open to any suggestions, as this is a completely new topic to me.

example.txt

File                  :TheFileName.txt
Value                 :19
Date                  :17.08.16
Description           :This is a description

grammar.y

%{
#include <stdio.h>

int yylex();
int yyparse();
FILE *yyin;
extern int line_num;

void yyerror(const char *s);
%}

%union {
        int ival;
        float fval;
        char *sval;
        char cval;
}

%token NEWLINE

%token PARAM_FILE
%token PARAM_DESCRIPTION
%token PARAM_DATE
%token PARAM_VALUE

%token <ival> INTEGER
%token <fval> FLOAT
%token <sval> STRING
%token <sval> DATE

%%

File: AssignList;

AssignList: Assign
          | Assign NEWLINES
          | Assign NEWLINES AssignList
          ;

Assign: PARAM_FILE        ':' STRING  {printf("Found 'File': [%s]\n", $3);}
      | PARAM_DESCRIPTION ':' STRING  {printf("Found 'Description': [%s]\n", $3);}
      | PARAM_DATE        ':' DATE    {printf("Found 'Date': [%s]\n", $3);}
      | PARAM_VALUE       ':' INTEGER {printf("Found 'Value': [%d]\n", $3);}
      ;

NEWLINES: NEWLINES NEWLINE
        | NEWLINE
        ;

%%

int main(int argc, char *argv[]) {
    yydebug = 0;
    do {
            yyparse();
    } while (!feof(yyin));

    return 0;
}

void yyerror(const char *s) {
        printf("Error parsing file! Error on line %d,  Message: %s\n", line_num, s);
}

tokenizer.lex

%option noyywrap
%{
#include "grammar.tab.h"

int line_num = 1;
%}

char    [^:\n]
digit   [0-9]
digit1  [1-9]
integer {digit1}{digit}*
float   (integer|0)("."|,){digit}+

date    {digit}{2}"."{digit}{2}"."{digit}{2}
string  {char}+

%%
    /* [1] I don't like this solution */
File[ \t]*          { return PARAM_FILE; }
Description[ \t]*   { return PARAM_DESCRIPTION; }
Date[ \t]*          { return PARAM_DATE; }
Value[ \t]*         { return PARAM_VALUE; }

:                   { return ':'; }

{integer} { yylval.ival = atoi(yytext);   return INTEGER; }
{float}   { yylval.fval = atof(yytext);   return FLOAT; }
{date}    { yylval.sval = strdup(yytext); return DATE; }

[ \t] ;
\n { line_num++; return NEWLINE; }     /* count the line numbers */

{string}  { yylval.sval = strdup(yytext); return STRING; }

%%
/* Empty 3rd section */

Makefile

grammar.tab.c: grammar.y
    bison -d grammar.y

grammar.tab.h: grammar.y
    bison -d grammar.y

lex.yy.c: tokenizer.lex
    flex.exe tokenizer.lex

parser.exe: lex.yy.c grammar.tab.c grammar.tab.h
    gcc -DYYDEBUG=1 lex.yy.c grammar.tab.c -o parser.exe

run: parser.exe
    type example.txt | parser.exe

output of type example.txt | parser.exe

Found 'File': [TheFileName.txt]
Found 'Value': [19]
Found 'Date': [17.08.16]
Found 'Description': [This is a description]


texts:
I'm not familiar with Python but want to provide a code snippet for an SO question about Dynamic Programming.

The snippet should show the bottom-up approach of DP.

The function isPowerOfTwo returns True if the given number n is a power of two otherwise False. The implementation uses a button-up table results.

def isPowerOfTwo(n):
    results = {}
    for i in range(1, n + 1):
        if i == 2:
            results[i] = True
        elif i % 2 != 0:
            results[i] = False
        else:
            results[i] = results[i/2]
    return results[n]

Do you have any recommendations?


texts:
I'm working on a project to find anagrams of words. My goal is to figure out the longest anagrams out there. I took a look at my code and it works but is woefully inefficient.

I have two arrays, each containing a length of long words:

words_one = ["sarcocarcinomata", "dactylopteridae", "autoradiographic", "pterylographical",
"nonconversational", "pathophysiological"]

words_two = ["carcinosarcomata", "pterodactylidae", "radioautographic", "pterylographical", "nonconservational", "physiopathological"]

Most of these words have to do with science, so they're relatively long.

For what I'm working on, I would like to find if all of the word pairs are anagrams of each other. In my example above, they are.

def anagrams(words_one, words_two)
  x = 0
  while x < words_one.count
    if words_one[x].chars.to_a.permutation.include?(words_two[x].chars.to_a)
      puts 1
      x += 1
    else
      puts 0
      x += 1
    end
  end
end

There are several potential problems I see here:

Permutation Method: This sorts through all permutations of a given string. Each letter can be one of 26 different characters. This adds up real quickly.
While Loop: I'm not sure this is the most effective method.
Duplicate Code: I put x+=1 in both sections of my if-else block.

I'd like to learn some new techniques to optimize Ruby code.

Which type of algorithm is my code and which type of algorithm do I need?


texts:
This piece of script will take one argument (file which contain list of ip, one per line) and convert it to its hostname. For now this will only work with IPv4.

This definitely doesn't look good and I want experts to review it and suggest some good ways of coding it in Python.

#!/usr/bin/python

import socket
import sys

BLUE='\033[34m'
RED='\033[31m'
NORMAL='\033[0m'

def check_ip():
        try:
                socket.inet_aton(ip)
        except Exception, e:
                print RED+"Invalid ip addresss = "+NORMAL + str(ip)

file = sys.argv[1]
with open(file) as ipfile:
        for iplist in ipfile:
                for IP in iplist.split():
                        ip = IP.strip(' \t\n\r')
                        if ip == '':
                                pass
                        else:
                                check_ip()
                                host = socket.getfqdn(ip)
                                print BLUE+ip+NORMAL + " hostname is " + BLUE+host+NORMAL


texts: python search replace and join with delimiter

texts:
I'm brand new and been going through some beginner code problems on checkIO. I finished this one today and am posting because I'm sure there is a much more elegant way to accomplish this, and I think this particular problem has a lot of useful applications. I would like to know what are the 'clean and efficient' ways to do it, or maybe what built-ins I haven't learned yet that I should explore. My version seems pretty ugly. Thanks!

Problem: take a tuple of phrases, anytime the word 'right' appears, replace it with 'left'. Create a new string combining all the phrases separated with a comma.

def left_join(phrases):
    """
        Join strings and replace "right" to "left"
    """
    phrases = list(phrases)
    newstr = ''
    for j, phrase in enumerate(phrases):
        if 'right' in phrase:
            mod = dict(enumerate(phrase))
            for key in mod:
                if mod[key] == 'r' and mod[key+4] == 't':
                    i = key
                    mod[i] = 'l'
                    mod[i+1] = 'e'
                    mod[i+2] = 'f'
                    mod[i+3] = 't'
                    mod[i+4] = ''
            switch = (list(mod.values()))
            phrase = ''.join(switch)
            if j == (len(phrases) - 1) or len(phrases) == 1:
                newstr += phrase
            else:
                newstr += phrase + ','
        else:
            if j == (len(phrases) - 1) or len(phrases) == 1:
                newstr += phrase
            else:
                newstr += phrase + ','
    return newstr

test1 = ("bright aright", "ok", "brightness wright",)
test2 = ("lorem","ipsum","dolor", "fright", "nec","pellentesque","eu",
         "pretium","quis","sem","nulla","consequat","massa","quis",)


texts:
I am trying to create a class for serial port using Node.js, but I want to know if there is a better way to write my data class code.

In my sample code below, in the getPortName prototype in the forEach loop, I declare a port object to store the serial port information before pushing into an array.

Is this a good way of declaring this port object? I think it is not good because it is difficult for users to see what the objects' members contain. Is there any way to make it clearly expose the port object member? Or is there a better way to improve this code structure?

'use strict';

var serialPort = require("serialport");

function Serial() {
    this.ComName = "";
}

Serial.prototype.getPortName = function() {
    serialPort.list(function (err, ports) {
        var availablePorts = [];

        ports.forEach(function(port) {
            var port = {
                 comName: "",
                 manufacturer: "",
                 pnpId:
            }

            port.comName = port.comName;
            port.manufacturer = port.manufacturer;
            port.pnpId = port.pnpId;
            availablePorts.push(port);
        });
    });

    return availablePorts;
};

Serial.prototype.setCOMName = function(name) {
    this.ComName = name;
}

module.exports = Serial;


texts:
This is a game in which a sequence of 4 characters is displayed to the player, one at a time with a delay between them. Then the player must input that sequence as it was displayed.
Sequences are displayed until input is incorrect.
The characters composing the sequences are chosen at random and they are all lines.
__all__ = []

import random
import time

from colorama import deinit, init

MSG_ASK = 'What was the sequence? '
MSG_CORRECT = '\033[32mCorrect!\033[0m'
MSG_INCORRECT = '\033[31mIncorrect\033[0m'

def main():
    k = 4

    lines = r'|\-/'

    seconds = 1

    init()

    while True:
        s = ''

        sequence = random.choices(lines, k=k)
        sequence = ''.join(sequence)

        for i in range(k):
            if not i:
                s = ''
            elif i == 1:
                s = ' '
            else:
                s = i * ' '

            print(s, sequence[i], end='\r')
            time.sleep(seconds)

        print(f'{s}  ')

        if input(MSG_ASK) == sequence:
            print(MSG_CORRECT)
        else:
            print(MSG_INCORRECT)
            break

    deinit()

if __name__ == '__main__':
    main()


texts: return array element if it exists, otherwise null

texts:
Given is an array $array and a key $key.  If the array has the key, then I want to return the value, otherwise null. Is there a better way in PHP7 now, then doing it like that:

return (empty($array[$key])) ? null : $array[$key];


texts:
I am looking for tips on improving my short program.  I am using system("PAUSE") because this was for an assignment.

Code:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

void Display(string* , int* , double*, int);
void Percentage(int*, double*, int);
void Intro(string*, int*, int&);
void Highest(int&, string&, double*, string*, int);

int main()
{
    int students;
    string names[10];
    int hours[10];
    double percents[10];
    int highest;
    string most;

    Intro(names, hours, students);

    Percentage(hours, percents, students);
    Display(names, hours, percents, students);

    Highest(highest, most, percents, names, students);

    system("PAUSE");
}

void Intro(string* names, int* hours, int& students)
{
    int team;
    cout << "A team is made up of atleast 2 students. How many students are on the team?: ";
    cin >> team;

    cout << "Enter student's first name and the hours worked on the final project: " << endl;

    for (int i = 0; i < team; i++)
    {
        cout << i + 1 << ": ";
        cin >> names[i] >> hours[i];
    }

    students = team;
}

void Display(string* names, int* hours, double* percent, int students)
{
    cout << setw(20) << "Students";
    cout << setw(20) << "Hours Worked";
    cout << setw(20) << "% of Total Hours";
    cout << endl;
    cout << "------------------------------------------------------------" << endl;
    for (int i = 0; i < students; i++)
    {
        cout << setw(20) << names[i];
        cout << setw(9) << hours[i];
        cout << setw(16) << percent[i];
        cout << endl;
    }
}

void Percentage(int* hours, double* percent, int students)
{
    int total(0);

    for (int i = 0; i < students; i++)
    {
        total += hours[i];
    }

    for (int i = 0; i < students; i++)
    {
        percent[i] = double(hours[i]) / total * 100;
    }
}

void Highest(int& highest, string& most, double* percent, string* names, int students)
{
    highest = percent[0];

    for (int i = 0; i < students; i++)
    {
        if (highest < percent[i])
        {
            highest = percent[i];
            most = names[i];
        }
    }

    cout << most << " worked the most hours." << endl;
}


texts: ADT Stack with a doubly circular linked list

texts:
I have managed to implement an ADTStack with a circular doubly linked list. I would like to know whether there are things I could have done better or, I should improve.

public class QueueCircularDLL<T> implements ADTQueue<T> {
    private ListElement<T> head;
    private ListElement<T> tail;

    public QueueCircularDLL(){
        head=null;
        tail=null;
    }

    public void enq (T element){
        ListElement<T>newElement=new ListElement<T>(element);
        if (empty()){
            head= newElement;
            tail= head;
        }

        tail.setNextElement(newElement);
        newElement.setPrevElement(tail);
        tail=tail.getNextElement();
        tail.setNextElement(head);
        head.setPrevElement(tail);

    }

    public void deq(){
        if (empty()){
            throw new RuntimeException("queue is empty");
        }

        if (head==tail){
            //head=null;
            head=null;
            tail=null;

        }
        else{
        head=head.getNextElement();
        head.setPrevElement(tail);
        tail.setNextElement(head);
        }

    }

    public T front(){
        if(empty()){
            return null;
        }
        return head.getElement();
    }

    public boolean empty(){
        return (head==null);
    }

    private static class ListElement<T>{
        private T element = null;
        private ListElement<T> nextElement = null;
        private ListElement<T> prevElement = null;

        public ListElement(T element) {
            this.element = element;
        }

        public T getElement() {
            return element;
        }

        public ListElement<T> getNextElement() {
            return nextElement;
        }

        public void setNextElement(ListElement<T> element) {
            this.nextElement = element;
        }
        //für zirkuläre doppelt verkettete liste
        public ListElement<T>getPrevElement(){
            return prevElement;
        }
        // für zirkuläre doppelt verkette liste
        public void setPrevElement(ListElement<T> element){
            this.prevElement=element;
        }

    }

    public static void main(String[] args) {
        QueueCircularDLL<Integer> queue = new QueueCircularDLL<Integer>();

        for (int i = 0; i < 10; ++i) {
            queue.enq(i);
        }

        while (!queue.empty()) {
            System.out.println(queue.front());
            queue.deq();
        }
    }
}


texts:
This code is for a program that needs to add thousands of strings to memory while it's running and these strings will be used until the end of execution. So the memory for these strings will be freed only in the end.

First I tested calling malloc for every new string and have used Valgrind to benchmark total execution cost for 200 hundred thousand strings. Then I wrote these memory handling functions that call malloc once and hand out small chunks of memory for every string. The overall execution cost for the entire program went down over 20%.

This is my first attempt at doing this, so I know this code is probably bad. I would like to know exactly what is wrong with it, so I won't make the same mistakes again.

//The actual numbers will be smaller after DEBUG
#define BIG_BLOCK       1073741824  //  1GiB ..........
#define MEDIUM_BLOCK     524288000  //500MiB .....
#define SMALL_BLOCK      104857600  //100MiB .

//Linked-list containing the required data for each malloc'ed block
typedef struct {
   void   *mem_pool;   //starting address for this block
   void   *next;       //next node
   size_t *position;   //current position
   size_t *available;  //how much memory was allocated?
} memory_t;

//First link
static memory_t *root = 0;

//handles malloc and returns a new memory_t node, it allocates
//more memory on the first call than on subsequent calls
static void *increase_memory(void)
{
    void        *result    = 0;
    memory_t    *new_block = 0;
    static int  firstCall  = 0;
    static const size_t default_sizes[] = {BIG_BLOCK, MEDIUM_BLOCK, SMALL_BLOCK, 0};

    for(size_t i = firstCall; default_sizes[i] != 0; ++i)
    {
        if((result = malloc(default_sizes[i])))
        {
            new_block = result;
            new_block->mem_pool = new_block;                                    //starting address for this block
            new_block->next = 0;                                                //link to next node
            new_block->position = result + sizeof(memory_t);                    //space for size_t *position
            *new_block->position = sizeof(memory_t) + sizeof(size_t) * 2;       //remove used addresses from pool (position, available)
            new_block->available = result + sizeof(memory_t) + sizeof(size_t);  //allocate space for size_t *available
            *new_block->available = default_sizes[i];                           //how much was allocated
            break;
        }
    }
    firstCall = 1; //first call happened, let's malloc smaller blocks
    return result;
}

//mallocs the first block, called by main()
int init_mem_pool(void)
{
    static int initialized = 0;
    if(!initialized++) root = increase_memory(); //protection against multiple calls

    return (root) ? 1 : 0;
    //Should I change the line above?
    //I believe it doesn't need to be this way but GCC compiler warns when the following are used:
    //return root;
    //return (int)root;
    //What should be done here?
}

//hands out memory chunks
void *get_memory(const size_t size)
{
    memory_t *current = root;
    void *temp = 0;

    while(current)
    {
        //there's enough memory in the current node
        if((*current->position + size) < *current->available) //Brackets added for clarity, not sure if it's bad style...
        {
            temp = current->mem_pool + *current->position;
            *current->position += size;
            break;
        }

        //not enough memory, go to next node
        else if(current->next) current = current->next;

        //all nodes are full, create another one
        else current = current->next = increase_memory();
    }
    return temp;
}

//free all nodes
static void recursive_free(const memory_t * const node)
{
    if(node->next) recursive_free(node->next);
    free(node->mem_pool);
}

//called by main(), free all nodes
void clean_mem(void)
{
    //is there anything to free?
    if(root)recursive_free(root);
}


texts:
For starters, I'm a student taking AP Computer Science this year, loving it so far. Lots of fun, especially problems like this. I think I'm going to make it a regular practice to post some of my exercises and projects here for people to review, so I can get some feedback from programmers other than my teacher on different ways to do things, ways to clean up my code, and good practice.

I'm not looking for answers here. I've completely written the code and am just looking for some feedback on a few questions listed below.

The prompt is as follows:

  Write an interactive program that reads lines of input from the user
  and converts each line into Pig Latin. Terminate the program when the
  user types a blank line.

  Words beginning with consonants have the consonant moved to the end of the word and "ay" appended
  Words beginning with vowels simply have "ay" appended

Specific questions:

Did I do this in an acceptably efficient way? What other, possibly better, ways could I have accomplished this?
How could this be done without an ArrayList? Learning how to use ArrayLists is something I've done on my own time, not that we've learned in class, and I want to become more independent from them on problems like this in case my teacher doesn't want me to keep using them.
What variables do I need to keep as class variables? When I was declaring them I wasn't sure exactly how I would structure the program, or if I was going to organize it into separate methods or not.

import java.util.*;
public class PigLatin {
    static ArrayList<String> al = new ArrayList<String>();
    static Scanner sc = new Scanner(System.in);
    static String userString;
    static String latinString;
    static String temp;

    public static void main(String[] args) {
        while (true) {
            latinString = "";
            System.out.print("Enter a string to be converted into Pig Latin. To stop, enter a blank input: ");
            String userString = sc.nextLine();
            if (userString.isEmpty()) {
                break;
            }

            ArrayList<String> al = new ArrayList<String>(Arrays.asList(userString.split("\\s")));

            for(int i = 0; i <= al.size() - 1; i++) {
                temp = al.get(i);
                String tester = temp.toUpperCase();
                if (tester.charAt(0) == 'A' || tester.charAt(0) == 'E' || tester.charAt(0) == 'I' || tester.charAt(0) == 'O' ||
                        tester.charAt(0) == 'U' ) {
                    latinString = latinString + temp + "ay ";
                } else {
                    latinString = latinString + temp.substring(1) + temp.charAt(0) + "ay ";
                }

            }
            System.out.println(latinString);
        }
        sc.close();
    }
}


texts:
I am practicing object oriented design and have taken Tic Tac Toe as an example. I have written first all the requirements and then started writing code. I would like to get it reviewed so that I can improve my skill further. Please provide suggestions.

I have placed code at this GitHub repo.

Square.js

//Square class
function Square(){
    this.symbol = "";
    this.isOccupied = false;
}

//Based on player turn set symbols
Square.prototype.setSymbol = function(value){
    if(value !== 'X' && value !== 'O'){
        return 'Please enter X or O';
    }else if(this.isOccupied){
        return 'This square is already filler'
    }else{
        this.symbol = value;
        this.isOccupied = true;
    }
};

Square.prototype.getSymbol = function(){
    return this.symbol;
};

Board.js

//Board Class
function Board(sqaures){
    this.squares = sqaures;
    this.grid = [];
    this.filledSquare = 0;
}

//Builds board based on number of squares
Board.prototype.buildBoard = function(){
    var i,j;
    for(i = 0; i < this.squares; i++){
        this.grid[i] = [];
        for(j = 0; j < this.squares; j++){
            this.grid[i][j] = new Square();
        }
    }
};

//Updates board on each players turn
Board.prototype.update = function(row, column, symbol){
    this.grid[row][column].setSymbol(symbol);
    this.filledSquare++;
};

//Show the current state of board
Board.prototype.displayBoard = function(){
    var i, j,brd = "";
    for(i = 0; i < this.squares; i++){
        for(j = 0; j < this.squares; j++){
            brd += this.grid[i][j].getSymbol() +' - ';
        }
        brd += '\n';
    }
    console.log(brd);
};

Player.js

//Player Class
function Player(name,symbol){
    this.name = name;
    this.symbol = symbol;
}

tttgame.js

//The game class which governs the play
function TTTGame(squares){
    this.board = new Board(squares);
    this.board.buildBoard();
    this.players = [];
    this.players[0] = new Player('John','X');
    this.players[1] = new Player('Doe', 'O');

    this.getCurrentPlayer = function(){
        return (this.board.filledSquare %2 === 0 ? 'X' : 'O');
    };

    //I have written this as dummy method which should be replaced with actual logic
    this.play = function(){
        this.board.displayBoard();
        var currentPlayer = this.getCurrentPlayer();
        var row, col, symbol;
        this.board.update(0,1,currentPlayer);
        currentPlayer = this.getCurrentPlayer();
        this.board.update(0,0,currentPlayer);
        currentPlayer = this.getCurrentPlayer();
        this.board.update(1,1,currentPlayer);
        currentPlayer = this.getCurrentPlayer();
        this.board.update(2,1,currentPlayer);
        currentPlayer = this.getCurrentPlayer();
        this.board.update(1,0,currentPlayer);
        this.board.displayBoard();
    }

    //It will contain method to decide winner or tie
}

GameStarter.js

//Starts the game
(function GameStarter(){
    var tttGame = new TTTGame(3);
    tttGame.play();
})();


texts:
I'm working with parameters right now in Java, and my colleague told me that this code of mine is redundant, and I see his point. The for loops do look redundant, but I have no idea how to go about changing this. My code is functional, but I wish to improve it.

public static void printLine(int length)
{
    for (int i = 1; i <= length; i++)
    {
        System.out.print("*");
    }
    System.out.println();
}

public static void printBox(int length, int height)
{
    printLine(length);

    for (int i = 1; i <= height - 2; i++)
    {
    System.out.print("*");
        for (int j = 1; j <= length - 2; j++)
        {
            System.out.print(" ");
        }
        System.out.println("*");
    }
    printLine(length);
}


texts: Length of the integer part of a double in C without math.h

texts:
I came up with this simple function to return the length of a double, working fine in all my test but want to make sure that this code will work in all doubles, can't think of a case in which it would not work but I'm sure if there is, then you can find it, here it is:

int length(double number){
     int result = 0;
     if ( number < 0 ) number *= -1;

     while ( number > 1){
         result++;
         number /= 10;
     }
     return result + ( number == 1 );
}

I think that the (number == 1) is pretty clever, but there might be some better way to accomplish the correct result. It's meant to work whenever the number is an exact power of ten but I think it might be a bit cryptic.


texts:
Purpose

Implementation for in-place Insertion Sort.

Discussion

The idea is to start with the second element in the input array (in the single element case, it's already sorted).

Moving backwards, compare the value against each prior element in the array until

You reach the beginning of the array
You find an element that is <= your value

As you continue backwards, move the last value you considered to the next index in the array.

Then repeat the same steps for the third, fourth, etc. elements, if they exist.

Implementation

public class InsertionSorter {
    public static void sort(int[] values) {
        for (int index = 1; index < values.length; index++) {
            int value = values[index];
            int nextIndex = index - 1;
            while (nextIndex >= 0 && values[nextIndex] > value) {
                values[nextIndex + 1] = values[nextIndex];
                nextIndex--;
            }
            values[nextIndex + 1] = value;
        }
    }
}


texts: How can I refactor this oversized Ruby method into smaller bits and have unit tests for them?

texts:
This is the existing code.  Clearly way too much is going on in this index method and furthermore it's untested (and hard to test in its current form).

  def index
#    @s = ""
#    @now=DateTime.now
    @from = params[:from]? ('01/01/'+params[:from]).to_date : '01/01/1991'.to_date
    @to = params[:to]? params[:to]+'/12/31' : '2099/12/31' # + DateTime.now.year + 100.years#  .year)+100.to_s).to_date
    if params[:search_text_1]
      @srch = params[:search_text_1]
      if params[:search_text_2] # An advanced search
        #
        # groups...
        @groups_comparison = ' and group_id in (-1'
        if params[:groups]
          params[:groups].each do |group_id|
            @groups_comparison+= ','+group_id
          end
          @groups_comparison+= ')'
        end
        #
        @srch_2 = params[:search_text_2] # May be null
        @version = (params[:version].to_f) #.is_a?(Integer))? params[:version].to_i : 0 # May be 0
        @version_comparison = '(version_number ' + params[:version_comparison] + ' ' + @version.to_s
        if params[:include_blank_version]  # If not checked doesn't pass.'
          @version_comparison+= " or version_number is NULL or version_number = '' )"
        else
          @version_comparison+= " and version_number is not NULL and version_number <> '' )"
        end
        @date_comparison = ' and ((content_date is NULL) or (content_date > ' + @from.to_s + '))'   #+ ' and content_date <= ' + @to.to_s + '))'

        case params[:join_operator].downcase
          when /and/
            @conditions =
              [@version_comparison + @groups_comparison + @date_comparison +
              ' and ((url_address LIKE ? or alt_text LIKE ?) and (url_address LIKE ? or alt_text LIKE ?))',
              "%"+@srch+"%", "%"+@srch+"%", "%"+@srch_2+"%", "%"+@srch_2+"%"]
          when /or/
            @conditions =
              [@version_comparison + @groups_comparison + @date_comparison +
              ' and ((url_address LIKE ? or alt_text LIKE ?) or (url_address LIKE ? or alt_text LIKE ?))',
              "%"+@srch+"%", "%"+@srch+"%", "%"+@srch_2+"%", "%"+@srch_2+"%"]
        end
      else # Just a simple search
        @conditions = ['(url_address LIKE ? or alt_text LIKE ? or version_number LIKE ?)', "%"+@srch+"%", "%"+@srch+"%", "%"+@srch+"%"]
      end
    else
      @conditions = ''
    end
    @links = Link.all(:joins => :group, :order => 'groups.group_name, links.position', :conditions => @conditions)

    session[:row_shading] = (params[:row_shading] == 'true') ? 'true' : 'false' rescue 'false'
    session[:full_details] = (params[:full_details] == 'true') ? 'true' : 'false' rescue 'false'
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @links }
    end
  end


texts:
Inspired by CodeWars

  We have a string s

  Let's say you start with this: "String"
    The first thing you do is reverse it: "gnirtS"
    Then you will take the string from the 1st position and reverse it
    again: "gStrin"
    Then you will take the string from the 2nd position and reverse it
    again: "gSnirt"
    Then you will take the string from the 3rd position and reverse it
    again: "gSntri"

  Continue this pattern until you have done every single position, and
    then you will return the string you have created. For this particular
    string, you would return: "gSntir"

  The Task:
    In this kata, we also have a number x
    take the above reversal function, and apply it to the string x times.
    Return the result of the string after applying the reversal function to it x times.

  Note:
  String lengths may exceed 2 million and x may exceed a billion.
  Be ready to optimize.

My solution works but times out and I am having trouble optimizing much further. The code contains a lot of useful comments but here is a summary of what I have attempted to do.

Cycle Length Calculation
Because the above algorithm generates cycles, we can calculate a strings cycle length and perform x % cycleLength to determine exactly how many iterations we must perform to get our end result, instead of having to calculate all the duplicate cycles. More on cycle lengths can be found here and here.

This method is better than nothing but can still get quite demanding on high cycle lengths. Potentially there is a better way of calculating the cycle length without so many iterations?

public final class XIterations {
    public static String xReverse(String s, long x) {
        // Using the cycle length and modular arithmetic,
        // We can find the exact number of reverse operations we will need to perform.
        // This way we will only perform operations we need to complete.
        long iterationsRequired = x % calculateCycleLength(s.length());

        // TODO: There may exist an algorithm that allows a linear transformation given x
        while (iterationsRequired > 0) {
            s = reverse(s);
            iterationsRequired--;
        }

        return s;
    }

    // The xReverse algorithm produces cycles and therefore duplicates.
    // This helper method determines the length of the cycle using the number of characters a string contains.
    // More detail on the algorithm can be found at:
    // https://oeis.org/A003558
    // https://oeis.org/A216066
    // TODO: There may exist an algorithm that requires less iterations to find the cycle length
    private static int calculateCycleLength(int n) {
        // Cache these so we only calculate them once.
        final int a = 2 * n + 1;
        final int b = 2 * n;

        int cycleLength = 1;
        while (true) {
            double c = Math.pow(2, cycleLength);
            if (c % a == 1 || c % a == b) {
                return cycleLength;
            }
            cycleLength++;
        }
    }

    public static String reverse(String s) {
        StringBuilder sb = new StringBuilder();
        int front = 0;
        int back = s.length() - 1;
        // Does not account for odd length strings. Will not add the middle character.
        while (front < back) {
            sb.append(s.charAt(back--));
            sb.append(s.charAt(front++));
        }

        // Account for odd length strings. Add the middle character that was never added by loop.
        if (front == back) {
            sb.append(s.charAt(front));
        }
        return sb.toString();
    }
}

I am mostly interested in optimization tips but of course any feedback is welcome.


texts:
The Question :

  Utkarsh being a very talkative child, was scolded by his teacher
  multiple times. One day, the teacher became very angry and decided to
  give him a very rigorous punishment. He made him stand on the school
  field which is X axis.

  Utkarsh initially stood at X = 0. The teacher asked him to run to X =
  N. But, to make the process quick, Utkarsh decided that he will make
  jumps of 2 or 3 steps only, i.e., from X = S he can jump to X = S+2 or
  X = S+3.

  Utkarsh decided that he will jump 2 steps with probability P/100 and
  jump 3 steps with probability 1-P/100.

  You need to find the probability that he will reach exactly on X = N.

  Constraints: 0 < N <= 106  0 <= P <= 100

  Input Constraints: The first line contains two integer N and P.

  Output Constraints: Your answer must contain exactly 6 digits after
  the decimal point.

The Solution

I applied DP using memoization using HashMap ,on large input it gives stackoverflow error at hashmap.containsKey line , please tell why it shows that error and a better way to do memoization here . i have faced this problem many times.

import java.util.HashMap;
import java.util.Scanner;

public class Utkarsh_and_Jumps {
    private static double p;
    private static HashMap<Integer, Double> dp;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        p = scanner.nextInt();
        dp = new HashMap<Integer, Double>();
        System.out.println(String.format("%.6g%n", solve(0, n)));
    }

    private static double solve(int i, int n) {
        if (dp.containsKey(i)) {
            return dp.get(i);
        }
        if (i == n) {
            return 1;
        } else if (i > n) {
            return 0;
        }
        double a = solve(i + 2, n) * (p / 100);
        double b = solve(i + 3, n) * (1 - (p / 100));
        dp.put(i, a + b);
        return a + b;
    }
}

The Input :

29194 14

The Error

Exception in thread "main" java.lang.StackOverflowError
    at java.util.HashMap.hash(HashMap.java:338)
    at java.util.HashMap.containsKey(HashMap.java:595)
    at Utkarsh_and_Jumps.solve(Utkarsh_and_Jumps.java:24)
    at Utkarsh_and_Jumps.solve(Utkarsh_and_Jumps.java:33)


texts: Transparent wrapper class for data structure in Python

texts:
I needed a deque who's maxlen can be set again after it has been initialized. So, since new-style classes in Python are treated as types, I decided to create a new class borrowing from deque to accomplish this. My approach is to have an internal deque as an attribute and when maxlen is set, it replaces the internal deque with a new one, initialized to the old contents and the new maxlen.

I tried subclassing deque but it's too crude, creating a deque that's useless on top with the useful one internally. So I chose to simply have all of the wrapper class's attributes (except special ones) point to the internal deque's. However, due to how new-style classes work, the special  attributes have to be handled manually. Since all I want is to override maxlen's setter, all of this seems inelegant and I'm wondering if there's a cleaner way of accomplishing this.

From what I've read here, it seems I could subclass this class in __new__ to skip overriding the special attributes, but that seems even more hairy than what I already wrote.

This is the result, stripped of extraneous comments (complete code here if you want something runnable, with tests):

# -*- coding: utf-8 -*-

from __future__ import print_function

from collections import deque

class ResizableDeque(object):
    def __init__(self, *args, **kwargs):
        self.internal = deque(*args, **kwargs)

        skip_list = [
            'maxlen'
        ] + [attr for attr in dir(deque) if attr.startswith('__') and
             attr.endswith('__')]

        for attr in dir(deque):
            if attr not in skip_list:
                setattr(self, attr, getattr(self.internal, attr))

    @property
    def maxlen(self):
        return self.internal.maxlen

    @maxlen.setter
    def maxlen(self, value):
        templist = list(self.internal)
        self.internal = deque(templist, value)

    def __str__(self):
        return self.internal.__str__()

    def __repr__(self):
        return self.internal.__repr__()

    def __getitem__(self, value):
        return self.internal.__getitem__(value)

    def __setitem__(self, index, value):
        return self.internal.__setitem__(index, value)

    # these have not been tested
    def __copy__(self):
        return self.internal.__copy__()

    def __delitem__(self, index):
        return self.internal.__delitem__(index)

    def __iadd__(self, other):
        return self.internal.__iadd__(other)

    def __len__(self):
        return self.internal.__len__()

    # not sure if overriding __sizeof__ is wise this way
    def __sizeof__(self):
        return self.__sizeof__() + self.internal.__sizeof__()

    # pretty sure this is ok
    def __format__(self, spec):
        return self.internal.__format__(spec)


texts: Find optimum teams given calendar availabilities

texts:
I'm designing an algorithm that creates optimum teams based on everyone's availabilities (maximizes the amount of shared availability). To this end, I've made a function that takes in a dictionary of availabilities mapping person to an array of their availabilities throughout the week at every 15 minute point (e.g. [True, True, False,...,False]) and desired team size and outputs final teams. Here's my working code:
import numpy as np
from itertools import combinations, chain
import operator
from functools import reduce
from tqdm import tqdm
import operator
def ncr(n, r):
    """N Choose R combination"""
    r = min(r, n-r)
    numer = reduce(operator.mul, range(n, n-r, -1), 1)
    denom = reduce(operator.mul, range(1, r+1), 1)
    return numer // denom  # or / in Python 2

NUM_PEOPLE = 100
TEAM_SIZE = 5
time_slots = 24*4*7

# random availabilities
availabilities = np.random.randint(2, size=(NUM_PEOPLE, time_slots), dtype="bool")
availabilities_dict = {}
for i, availability in enumerate(availabilities):
    availabilities_dict[i] = availability

def make_teams(availabilities_dict, team_size):
    """
    availabilities_dict form: {player: [0,0,0,...,1], player2: [0,0,0,0,1...,0]}
    """

    sums = []
    comb = combinations(availabilities_dict, TEAM_SIZE)
    for i in tqdm(list(comb)):
        sum_of_array = np.logical_and.reduce((np.array(availabilities[i,:]))).sum()
        sums.append((i, sum_of_array))
    sums.sort(key=operator.itemgetter(1))
    sums.reverse()

    assigned = []
    teams = []
    i = 0
    while (len(assigned) < NUM_PEOPLE):
        considering = list(sums[i][0])
        none_assigned = True
        for person in considering:
            if person in assigned:
                none_assigned = False
        if none_assigned:
            teams.append((considering, sums[i][1]))
            for person in considering:
                assigned.append(person)
        i += 1
    return teams
teams = make_teams(availabilities_dict, TEAM_SIZE)

Example output consists of a list of tuples (team, total blocks intersecting):
[([15, 18, 42, 70, 94], 36),
 ([14, 30, 63, 80, 97], 36),
 ([1, 12, 40, 64, 88], 36),
 ([22, 48, 62, 72, 87], 34),
 ([25, 29, 35, 53, 85], 32),
 ([26, 31, 49, 60, 78], 31),
 ([13, 44, 79, 93, 96], 29),
 ([32, 59, 67, 71, 82], 28),
 ([24, 39, 41, 50, 91], 28),
 ([9, 28, 55, 92, 95], 28),
 ([5, 8, 11, 19, 86], 28),
 ([4, 33, 56, 76, 83], 27),
 ([2, 10, 16, 17, 69], 27),
 ([21, 43, 73, 75, 81], 24),
 ([7, 20, 57, 89, 99], 24),
 ([23, 36, 37, 58, 66], 22),
 ([52, 61, 65, 68, 84], 20),
 ([3, 27, 34, 47, 74], 18),
 ([6, 38, 51, 54, 77], 16),
 ([0, 45, 46, 90, 98], 9)]

But this took over 10 mins to run on my state of the art computer! Is there a way to still find an optimum team match without running through all of the possible combinations? How can I make it faster? Thank you!


texts:
Got the following piece of code:

          If boolFlag Then
              With offer.Person1
                entity.Birthdate = .BirthDate

                entity.FirstName = .FirstGivenName
                entity.LastName = .FamilyName

                entity.Street = .StreetName
                entity.HousNr = .HouseNumberIdentifier
                entity.BoxNr = .BoxNumberIdentifier
                entity.PostalCode = .PostalCode
                entity.Municipality = .CityName
            End With
        Else
            With offer.Person2
                entity.Birthdate = .BirthDate

                entity.FirstName = .FirstGivenName
                entity.LastName = .FamilyName

                entity.Street = .StreetName
                entity.HousNr = .HouseNumberIdentifier
                entity.BoxNr = .BoxNumberIdentifier
                entity.PostalCode = .PostalCode
                entity.Municipality = .CityName
            End With
        End If

Objects Person1 and Person2 are of different types, and those types do not share a common Interface / class. (And that can't be changed)

How do I avoid the duplicate code inside the With-blocks?


texts:
I made a compiling IRC bot in Java that compiles JavaScript code using Nashorn engine, bans users if they say bad words and replies for simple user requests. I'd like ask about review my code.

Main.java:

package pl.hubot.irc.javac;

import org.jibble.pircbot.IrcException;

import java.io.IOException;

public class Main
{
    public static void main(String[] args)
    {
        try
        {
            // Now start our bot up.
            MyBot bot = new MyBot();

            // Enable debugging output.
            bot.setVerbose(true);

            // Connect to the IRC server.
            bot.connect("irc.freenode.net");

            // Join the #pircbot channel.
            bot.joinChannel("#jdsofdgojdfg");
        }
        catch (IrcException | IOException ex)
        {
            System.out.println(ex.getMessage());
        }
    }
}

MyBot.java:

package pl.hubot.irc.javac;

import org.jibble.pircbot.*;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.ArrayList;
import java.util.List;

class MyBot extends PircBot
{
    MyBot()
    {
        this.setName("javac");
    }

    public void onMessage(String channel, String sender,
                          String login, String hostname, String message)
    {
        if (message.equalsIgnoreCase("!time"))
        {
            String time = new java.util.Date().toString();
            sendMessage(channel, sender + ": The time is now " + time);
        }
        else if (message.equalsIgnoreCase("!javac -version"))
        {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("nashorn");
            sendMessage(channel, System.getProperty("java.version"));
            sendMessage(channel, engine.toString());
        }
        else if (message.startsWith("!javac ".toLowerCase()))
        {
            try
            {
                String code = message.substring(6, message.length());
                ScriptEngineManager manager = new ScriptEngineManager();
                ScriptEngine engine = manager.getEngineByName("nashorn");
                sendMessage(channel, engine.eval(code).toString());
            }
            catch (ScriptException ex)
            {
                sendMessage(channel, ex.getMessage());
            }
        }
        else if (message.startsWith("!banword "))
        {
            String badWord = message.substring(9, message.length());
            sendMessage(channel, "\"" + badWord + "\" has added to bad words list.");
            badWords.add(badWord);
        }
        else if (message.startsWith("!unbanword "))
        {
            String badWord = message.substring(11, message.length());
            if (badWords.remove(badWord)) sendMessage(channel, "\"" + badWord + "\" has removed from bad words list.");
            else sendMessage(channel, "\"" + badWord + "\" hasn't removed from bad words list.");
        }

        if (!message.startsWith("!banword ") && !message.startsWith("!unbanword ")) badWords.stream().filter(message::contains).forEach(badWord -> kick(channel, sender));
    }

    private List<String> badWords = new ArrayList<>();
}


texts: Class for removing Non Alpha/Numeric Character String and Counting Words

texts:
Yesterday I had help via Stack Overflow on a program I written some code for, and needed to know if it needed to be improved.

After reviewing the responses, I restructured the code into the following...

using System;

namespace Language
{
    public static class Grammar
    {
        /// <summary>
        /// Returns a string value with non alpha/numeric characters removed.
        /// </summary>
        /// <param name="Sentence"></param>
        public static string RemoveNonAlphaNumeric(string Sentence)
        {
            string[] Removed = { " ", ".", "!", "?", "@", "%", "&", "^", "$", "#", "*", "~" };
            string[] words = Sentence.Split(Removed, StringSplitOptions.RemoveEmptyEntries);

            return string.Join(" ", words);
        }

        /// <summary>
        /// Returns the integer value of the number of words in a sentence.
        /// </summary>
        /// <param name="Sentence"></param>
        /// <returns></returns>
        public static int GetWordCount(string Sentence)
        {
            string[] Removed = { " " };
            string[] Words = Sentence.Split(Removed, StringSplitOptions.RemoveEmptyEntries);

            return Words.Length;
        }
    }
}

Initally GetWordCount() contained a foreach() loop which was basically counting the number of words in the array. I took the suggestion of someone removed this. Then replaced the return CountWords which was initially a variable declared at 0, with return words.Length. I also took out Stream as a string parameter as someone  suggested that it may cause confusion.

Here's how the functions can be called from the main()...

using System;
using Language;

namespace ULESConMain
{
    class Program
    {
        static void Main(string[] args)
        {

            string OldSentence = "@#The dirty dog, was &&walking proudly!";

            // output using just Console.WriteLine() without assigning to a varaiable //

            Console.WriteLine($"{Grammar.RemoveNonAlphaNumeric(OldSentence)}");
            Console.WriteLine($"The total number of words in the sentence = {Grammar.GetWordCount(OldSentence)}");

            // Output using Console.WriteLine() using returned values //

            string NewSentence1 = Grammar.RemoveNonAlphaNumeric(OldSentence);
            int WordCount = Grammar.GetWordCount(NewSentence1);

            Console.WriteLine();

            Console.WriteLine(NewSentence1);
            Console.WriteLine($"The total number of words in the sentence = {WordCount}");

            // Prompt to return control to the Operating System and exit the program.
            Console.WriteLine("\nPress the ENTRER key to continue...");
            Console.ReadKey();  // Get user input to return to the Operating System.
        }
    }
}

If anyone has any ideas or if you think this is good enough since it's working as expected. Please let me know.


texts: Ad-hoc analytics script to module/package

texts:
I have a text analytics process that I complete for work. This process mines text for different Twitter accounts and finds patterns in the tweets. The actual machine learning pipeline is much more complicated than what's shown below, but this will have to suffice as my minimum reproducible example. In reality, there are a lot more instances when I asked for user input in the script, so I don't think things like user input should be stored in the same script as the functions.

Right now, I run this script on an ad-hoc basis, and a lot of the things are hard-coded. I want to be able to package the code I've written to make it more robust and stable.

How should the functions before __main__ and the procedures in __main__ be split up to best make this code a package? Should the functions be saved in a different script altogether, and then be imported when needed to a different script? Right now, I just run these scripts from the command line and am sort of lost as to where to go in terms of packaging it.

Text data cleaning script:

import pandas as pd

from nltk.corpus import stopwords

import re
import string

import os

def strip_punct(string, regex):
    return regex.sub(' ', string)

def clean_string(string, regex, stopwords):
    words_to_keep = []
    stripped_string = strip_punct(string, regex)
    string_words = stripped_string.split()
    for word in string_words:
        if word not in stopwords:
            words_to_keep.append(word)
    cleaned_string = " ".join(words_to_keep)
    return cleaned_string

def clean_and_map_column(column, df, regex, stopwords):
    text_set = set(df[column])
    text_dict = dict((string, clean_string(row, regex, stopwords)) for row in text_set)
    df[column] = df[column].map(text_dict)
    return df[column]

if __name__ == '__main__':

    os.chdir("/path/to/my/folder")

    # regular expression containing punctuation to be removed from strings
    regexp = re.compile('[%s]' % re.escape(''.join(p for p in string.punctuation)))

    # set of stopwords to remove from text from NLTK
    stops = stopwords.words('english')

    # my data frame, containing only columns of text
    df = pd.read_csv("file.csv")

    # clean each column
    for col in df.columns.values:
        df[col] = clean_and_map_column(col, df, regexp)

    df.to_csv("cleaned_file.csv")

KMeans clustering script:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.cluster import KMeans

import pandas as pd

import os

if __name__ == '__main__':

    os.chdir("/path/to/my/folder")

    df = pd.read_csv("cleaned_file.csv")

    corpus_column = 'twitter_data'

    corpus = df[corpus_column]

    vectorizer = CountVectorizer()

    X = vectorizer.fit_transform(corpus)

    model = KMeans(k = 5)

    model.fit(X)

    df['cluster_id'] = model.labels_

    df.to_csv('kmeans_file.csv")


texts: Multiple functions to establish a fallback value for a property until not null

texts:
I have a property (called "Head") that can be set externally. When "Head" is not set, it uses Unity3D's MonoBehaviour functions to try to find the best value for "Head". I started with a nested if, but the nesting was starting to get out of hand.

if (Head == null)
{
    Head = this.GetComponent<Camera>();

    if (Head == null)
    {
        Head = this.GetComponentInChildren<Camera>();

        if (Head == null)
        {
            Head = Camera.main;
        }
    }
}

So I developed a loop:

System.Func<Camera>[] fallbacks = new System.Func<Camera>[]
{
    () => this.GetComponent<Camera>(),
    () => this.GetComponentInChildren<Camera>(),
    () => Camera.main,
};

foreach (var fallback in fallbacks)
{
    if (Head != null)
    {
        break;
    }
    Head = fallback();
}

Would this create too much lambda overhead? Do you think the lambdas even increases readability? Is there a more elegant way to handle multiple fallbacks?

Edit:

RobH helped me discover the Null coalescing doesn't work with Unity3D components.
RobH's extension method workaround worked great with some tweaking. I had to enforce that comparison had to be done through UnityEngine.Object.

public static T IfNullThen<T>(this T obj, Func<T> factory) where T : UnityEngine.Object
{
    return obj != null ? obj : factory();
}

With that extension method my code is now just

Head = Head
    .IfNullThen(() => this.GetComponent<Camera>())
    .IfNullThen(() => this.GetComponentInChildren<Camera>())
    .IfNullThen(() => Camera.main);


texts: Modifying a string by passing a pointer to a void function

texts:
Please explain the relationship between pointers and arrays.  In this tutorial, they change int c by changing *r in the function.  How is that possible?

Also, please review my code for reversing a string.  The string variable belongs to the main() function, and I would like to pass a pointer to let the strreverse() function write to the string.  Does my code work?

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

void strreverse(char *string)
{
 int i, len;
 char c;
 len=strlen(string);
 char string2[len+1];

 for(i=0; i<len; i++)
 {
  c=string[i];
  string2[len-i]=c;

 }
 string2[len+1]='\0';
 string=string2;
 //printf("%s\n", string); <-- this would work,but should be in main

}

int main(int argc, char *argv[])
{
  char str[256];
  printf("Type a String to reverse it.[max. 255 chars]\n");
  fgets(str, 255, stdin);
  strreverse(&str[0]);
  printf("%s", str);
  return EXIT_SUCCESS;
}