texts: Get AD Users' Latest Last Logon Dates across Multiple DCs

texts:
I was recently asked to help our Spanish BU to audit their AD for inactive accounts.

Grabbing a script from online I gave them this: https://gallery.technet.microsoft.com/scriptcenter/Get-Active-Directory-User-bbcdd771

However that doesn't scale well when there's multiple users; as this takes one account then manually searches for the maximum last logon on any domain controller, rather than pulling back the values from all DCs then performing an aggregate function (which can then work the same way for 1 or many accounts).

As such I wrote this:

[string]$DCNameFilter = "ES*" #only get Spanish DCs (i.e. our company's naming convention prefixes server names with 2 char country iso code)
[string]$SearchBase = 'OU=es,DC=eu,DC=myCompany,DC=com' #only look within the Spanish OU; our OUs are under their collective region's domain (i.e. EU) within the company

#filter down to just the ES domain controllers
$DCs = Get-ADDomainController -Filter {Name -like $DCNameFilter} | Select -expand Name

#for each of the above domain controllers
$DCs | %{
    #get a list of enabled users & their last logon dates
    Get-AdUser -SearchBase $SearchBase -Filter {Enabled -eq $true} -Properties LastLogonDate -Server $_ `
    | Select-Object samAccountName, Name, LastLogonDate #filter to only the columns we're interested in
} | Group-Object -Property samAccountName | %{ #group results by account name
    #return the account name, full name, & their latest logon date
    $_ | select Name, @{Name='Full Name';Expression={$_.Group | select -ExpandProperty Name -first 1}}, @{Name='LastLogonDate';Expression={$_.Group | Measure-Object -Property LastLogonDate -Maximum | select -ExpandProperty Maximum}}
} | sort Name #nb: name is sAmAccountName; column name changed as result of earlier group-object statement.

I've seen lots of examples similar to the technet script above used before, but have never seen someone using the aggregate/group-object approach, so wondered if there was a reason for this (e.g. some inefficiency I'd not considered); hence posting here.

NB: I'm also aware of the Search-ADAccount -AccountInactive option, which would show inactive accounts; but the request was to return the last logon dates rather than simply what's inactive; so I provided both options so the local team could determine which was more suited to their requirements.


texts:
I usually use c++ so it may not be best practice for c.
This is a stack based toy vm and as a result it is very primitive, and it has no bitwise
instructions
64k might be a bit overkill for a toy vm.
coding is hard
#include <stdio.h>
#include "vm.h"

int main() {
    Vm *vm = new_vm();
    i32 buffer[] = {
        0x00000A01, /* push 0x0A(\n) */
        0x00004301, /* push 0x43(C)  */
        0x00004201, /* push 0x42(B)  */
        0x00004101, /* push 0x41(A)  */
        0x00000009, /* output */
        0x00000002, /* pop */
        0x00000009,
        0x00000002,
        0x00000009,
        0x00000002,
        0x00000009,
        0x00000000  /* halt */
    };
    for (int i = 0; i < sizeof(buffer); i++) {
        vm->mem[vm->pc+i] = buffer[i];
    }
    run_vm(vm);
    free_vm(vm);
    return 0;
}

vm.h
#ifndef VM_H_
#define VM_H_

#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>

typedef uint32_t i32; /* other numbers */
typedef int32_t si32; /* stack pointer */
typedef unsigned char byte;

typedef struct {
    i32 mem[0xffff]; /* approx. 64k */
    si32 sp;
    i32 pc;

    i32 raw;
    byte opc;
    i32 param;

    bool running;
} Vm;

Vm *new_vm();
void reset_vm(Vm *vm);
void free_vm(Vm *vm);
void run_vm(Vm *vm);

#endif

vm.c
#include <stdio.h>
#include "vm.h"

Vm *new_vm() {
    Vm *ret = (Vm*)malloc(sizeof(Vm));
    ret->pc = 1024; /* add space for the stack */
    ret->sp = -1;
    ret->running = true;
    return ret;
}

void reset_vm(Vm *vm) {
    vm->running = true;
    for (int i = 0; i < 0xffff; i++) {
        vm->mem[i] = 0;
    }
    vm->sp = -1;
    vm->pc = 1024;
}
void free_vm(Vm *vm) {
    free(vm);
    vm = NULL;
}

static void fetch(Vm *vm) {
    vm->raw = vm->mem[vm->pc++];
}

static void decode(Vm *vm) {
    /* style of opcode
     * 24 bits for parameter
     * a byte for the opcode
    */
    vm->opc = vm->raw & 0xff;
    vm->param = (vm->raw & 0xffffff00) >> 8;
}

static void execute(Vm *vm) {
    switch(vm->opc) {
        case 0x00: /* halt */
            vm->running = false;
            printf("Halt\n");
        break;
        case 0x01: /* push */
            vm->mem[++vm->sp] = vm->param;
        break;
        case 0x02: /* pop */
            vm->mem[vm->sp--] = 0;
        break;
        case 0x03: /* store */
            vm->mem[ vm->mem[vm->sp - 1] ] = vm->mem[vm->sp];
        break;
        case 0x04: /* load */
            vm->mem[vm->sp + 1] = vm->mem[ vm->mem[vm->sp] ];
            ++vm->sp;
        break;
        case 0x05: /* add */
            vm->mem[vm->sp + 1] = vm->mem[vm->sp] + vm->mem[vm->sp - 1];
            ++vm->sp;
        break;
        case 0x06: /* sub */
            vm->mem[vm->sp + 1] = vm->mem[vm->sp - 1] - vm->mem[vm->sp];
            ++vm->sp;
        break;
        case 0x07: /* mul */
            vm->mem[vm->sp + 1] = vm->mem[vm->sp] * vm->mem[vm->sp - 1];
            ++vm->sp;
        break;
        case 0x08: /* div */
            vm->mem[vm->sp + 1] = vm->mem[vm->sp - 1] / vm->mem[vm->sp];
            ++vm->sp;
        break;
        case 0x09: /* outc */
            printf("%c", vm->mem[vm->sp]);
        break;
        case 0x0A: /* inpc */
            vm->mem[++vm->sp] = getchar();
        break;
    }
}

void run_vm(Vm *vm) {
    while(vm->running) {
        fetch(vm);
        decode(vm);
        execute(vm);
    }
}


texts:
This is a maximum sum contiguous problem from interviewbit.com

Problem : Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example: Given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.

This is my solution :
def max_sub_array(array):
    """ Finds msub-array with maximum sum and returns the maximum sum and sub-array"""
    max_start, max_stop = 0, 1 # Start, Stop of maximum sub-array
    curr = 0                   # pointer to current array
    max_sum = array[0]         # Sum of maximum array
    current_sum = 0            # sum of current array

    for i, elem in enumerate(array):
        current_sum +=  elem

        if max_sum < current_sum:
            max_sum = current_sum
            max_start = curr
            max_stop = i  + 1
        if current_sum < 0:
            current_sum = 0
            curr = i + 1

    return  max_sum , array[max_start:max_stop]

checking test cases:
assert max_sub_array([-4,-2,-3,-4,-5]) == (-2,[-2]), "Wrong evaluation"
assert max_sub_array([-1]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -4, 6]) == (11,[7, -1, 2, 1, -4, 6]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -6, 5]) == (9, [7, -1, 2, 1]), "Wrong evaluation"
assert max_sub_array( [6, -3, -2, 7, -5, 2, 1, -7, 6]) == (8,[6, -3, -2, 7]), "Wrong evaluation"
assert max_sub_array([-5, -2, -1, -4, -7]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array( [4, 1, 1, 4, -4, 10, -4, 10, 3, -3, -9, -8, 2, -6, -6, -5, -1, -7, 7, 8]) == (25,[4, 1, 1, 4, -4, 10, -4, 10, 3]), "Wrong evaluation"
assert max_sub_array([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1 ]) ==  (28, [20, -4, -3, -2, 8, -1, 10]), "Wrong evaluation"

How can this code be optimised ?


texts: SQL stored procedure that returns a boolean value?

texts:
CREATE PROCEDURE dbo.foo
AS
BEGIN
DECLARE @true BIT, @false BIT;
SET @true = 1;
SET @false = 0;

IF (some condition)
    Select @true;
ELSE
    Select @false;
END

SQL is not the language that I'm strongest in now, but the above stored procedure seems to be produce the desired functioning: returning the truth value of some condition.

Is there a better way to define this stored procedure?  By the way, it runs on MS SQL 2008.


texts: Strategy design pattern for writing to a file or to the console

texts:
I have this interface for all strategies:

type PrintStrategy interface {
    Print() error
}

of two types:

type ConsoleStrategy struct{}

type FileStrategy struct {
    DestinationFilePath string
}

with two concrete implementations of strategy:

func (c *ConsoleStrategy) Print() error {
    fmt.Println("ConsoleStrategy")
    lister, _ := template.New("foo").Parse(tplTemplate())
    lister.Execute(os.Stdout, tplParams())
    return nil
}

func (c *FileStrategy) Print() error {
    fmt.Println("FileStrategy")
    var t bytes.Buffer
    foo, _ := template.New("bar").Parse(tplTemplate())
    foo.Execute(&t, tplParams())

    f, err := os.Create(c.DestinationFilePath)
    if err != nil {
        panic(err)
    }
    defer f.Close()
    f.Write(t.Bytes())
    return nil
}

and finally a main function that gets the strategy from the console and prints the content built inside tplTemplate() to the console or a file.

func main() {
    strategy := flag.String("strategy", "console", "selected strategy")
    flag.Parse()

    var printStrategy PrintStrategy

    switch *strategy {
    case "console":
        printStrategy = &ConsoleStrategy{}
    case "file":
        printStrategy = &FileStrategy{"bigciao"}
    default:
        printStrategy = &ConsoleStrategy{}
    }

    printStrategy.Print()
}

Is this a good example of using the pattern?


texts: Data set with many variables in Python, many indented dictionaries?

texts:
I am working with a data set that has many variables. Currently I am storing the data in many indented dictionaries in the following way:
import numpy as np

X_POSITIONS = [0,1.5,1]
Y_POSITIONS = [0,1,2]
CHANNELS = ['left pad', 'right pad', 'top pad', 'bottom pad']

data = {}
for x in X_POSITIONS:
    data[x] = {}
    for y in Y_POSITIONS:
        data[x][y] = {}
        for ch in CHANNELS:
            data[x][y][ch] = np.random.rand() # Here I would place my data.

This works fine, but it is cumbersome if by some reason I need to change the order of the keys. Consider the following function:
def do_something_with_single_channel(data_from_one_channel):
    for x in data_from_one_channel:
        for y in data_from_one_channel[x]:
            print(f'x = {x}, y = {y}, data[x][y] = {data_from_one_channel[x][y]}')

Before calling this function the whole data object has to be rearranged:
new_data = {}
for ch in CHANNELS:
    new_data[ch] = {}
    for x in X_POSITIONS:
        new_data[ch][x] = {}
        for y in Y_POSITIONS:
            new_data[ch][x][y] = data[x][y][ch]

do_something_with_single_channel(new_data['left pad'])

Since this seems to be a very common thing to do, I am sure that there must already exist something better than dictionaries for this purpose. Ideally I imagine something that can be accessed in the same way as the arguments of a function by giving names to the variables and forgetting about the order, for example something of the form
do_something_with_single_channel(data[channel='left pad'])

Does something like this exists? What's the name?


texts: How to speed up a treeview population in Access?

texts:
I have the following function that causes a significant visual jittering and lag in my access database - This is a treeview selection based on data in a table (tblDATA) with the fields:
Object | Attribute | Property | Value
I have tried echo and me.painting but figured my actual for loops need to be looked at for optimisation - wondering if there is a better way to cycle through a Recordset and populate a Treeview ?
' [1] Update the treeview
'------------------------------------

Private Sub btnUpdateFilter_Click()

    'Me.Painting = False
    'Echo False
    'DoCmd.Hourglass True

    Dim sArea As String, N As Integer
    Dim oData_distinct As DAO.Recordset
    Dim oData As DAO.Recordset
    Dim oNone As DAO.Recordset
    Dim rs As DAO.Recordset
    Dim element As Variant
    Dim Arr_distinct() As Variant

    If IsNull(cbxAttributeFilter01) Or IsNull(cbxPropertyFilter01) Then Exit Sub

    Set oData_distinct = CurrentDb.OpenRecordset("SELECT DISTINCT [Value] FROM tblData WHERE Attribute = " & cbxAttributeFilter01 _
                                                & " AND Property = " & cbxPropertyFilter01, dbOpenSnapshot)

    Set oNone = CurrentDb.OpenRecordset("SELECT [Tagname] FROM tblData WHERE NOT Attribute = " & cbxAttributeFilter01 _
                                                & " AND NOT Property = " & cbxPropertyFilter01, dbOpenSnapshot)

    Set oData = CurrentDb.OpenRecordset("SELECT [Tagname], [Value] FROM tblData WHERE [Attribute] = " & cbxAttributeFilter01 _
                                                & " AND [Property] = " & cbxPropertyFilter01, dbOpenSnapshot)

    If oData.RecordCount = 0 Then TreeView.Nodes.Clear: Exit Sub

    Arr_distinct = oData_distinct.GetRows(oData_distinct.RecordCount)

    TreeView.Nodes.Clear

    ' Standard
    TreeView.Nodes.Add , , "MISC", "MISC"
    For Each element In Arr_distinct
        If Not element = "" Then
            If IsNumeric(element) Then element = "_" & element
            TreeView.Nodes.Add , , element, element    ' ADD Parent
        End If
    Next element

    Dim sTemp As String

    With oData
        .MoveFirst
        Do While Not .EOF
            sTemp = !Value
            If IsNumeric(sTemp) Then sTemp = "_" & sTemp
            If sTemp = "" Or sTemp = " " Then sTemp = "MISC"
            On Error Resume Next
            TreeView.Nodes.Add sTemp, tvwChild, DLookup("Tagname", "MASTER", "ID = " & !Tagname), DLookup("Tagname", "MASTER", "ID = " & !Tagname)
        .MoveNext
        Loop
    End With

    With oNone
        .MoveFirst
        Do While Not .EOF
            On Error Resume Next
            TreeView.Nodes.Add "MISC", tvwChild, DLookup("Tagname", "MASTER", "ID = " & !Tagname), DLookup("Tagname", "MASTER", "ID = " & !Tagname)
            .MoveNext
        Loop
    End With

   'DoCmd.Hourglass False
   'Echo True
   'Me.Painting = True

End Sub
```


texts:
I have a Edit/Details form which has 4 user related fields. On click of Save, I save the edited fields to local storage (if supported) and display the same values in the Details view.

Below is the code which does that;

  var UserDataObj = {
name:"John",
email:"john@example.com",
phone:"9999999999",
desc:"some description"
}

/**
 * Check HTML5 Local Storage support
 */
function supports_html5_storage()
{
    try {
        window.localStorage.setItem( 'checkLocalStorage', true );
        return true;
    } catch ( error ) {
        return false;
    };
};

/**
 * Save form data to local storage
 */
function saveFormData()
{
    if (supports_html5_storage())
    {
    $(".formFieldUserData").each(function(){
        UserDataObj[$(this).attr("name")] = $(this).val();
    });

    localStorage.setItem('UserDataObj', JSON.stringify(UserDataObj));
    }
}

/**
 * Set field values based on local storage
 */
function setFormFieldValues()
{
    if (supports_html5_storage())
    {
            var retrievedUserDataObj = JSON.parse(localStorage.getItem('UserDataObj'));
            if(retrievedUserDataObj)
            {
                $(".formFieldUserData").each(function(){
                    var currentKey = $(this).attr("name");
                    var retrievedValue = retrievedUserDataObj[$(this).attr("name")]
                    $("#"+currentKey).val(retrievedValue);
                    $("#"+currentKey+"Txt").html(retrievedValue);
                });
            }
            else
            {
                $(".formFieldUserData").each(function(){
                    var currentKey = $(this).attr("name");
                    var userDataObjValue = UserDataObj[$(this).attr("name")]
                    $("#"+currentKey).val(userDataObjValue);
                    $("#"+currentKey+"Txt").html(userDataObjValue);
                });
            }
    }
    else
    {
        $(".formFieldUserData").each(function(){
        var currentKey = $(this).attr("name");
            if ($(this).val() != "")
            {
            var fieldValue = $(this).val();
            $("#"+currentKey).val(fieldValue);
            $("#"+currentKey+"Txt").html(fieldValue);
            }
            else
            {
            var defaultuserDataObjValue = UserDataObj[$(this).attr("name")];
            $("#"+currentKey).val(defaultuserDataObjValue);
            $("#"+currentKey+"Txt").html(defaultuserDataObjValue);
            }
        })
    }
}

My question is;

This is a completely working code. But is there any further that I can do as far as best coding practices go.
Also performance wise, can I do anything to improve the overall code?


texts:
Based on the feedback and suggestions I received in my previous post (Lightweight shorthand JS library), I've updated and optimized Mozart JS.

Again, the goal is to have some jQuery-like functionality in a minimal size. Thoughts on this updated version?

Full library on GitHub.

Mozart JS

Element Retrieval

Shorthand for document.querySelectorAll or document.querySelector. My decision to include both is just personal preference.

function $get(input) {
    return document.querySelectorAll(input);
}
function $grab(input) {
    return document.querySelector(input);
}

Example:

var foo = $grab('#bar'); //returns element with the Id of "bar"
var zed = $get('.cop'); //returns collection with the classname "cop"

Element Creation

Shorthand for document.createElement and Element.setAttribute. Though text is not an attribute, I chose to allow users to set textContent as well, similar to jQuery.

function $make(tag, params) {
    var obj = document.createElement(tag);
    for (var key in params) {
        if (key === 'text') {
            obj.textContent = params[key];
        } else {
            obj.setAttribute(key, params[key]);
        }
    }
    return obj;
}

Example:

var g = $make('button', {
    style:'float: left',
    class:'myClass',
    text:'Some text here',
    value:'myValue'
});

//Equivalent to:

var g = document.createElement('button');
g.setAttribute('style','float: left');
g.setAttribute('class','myClass');
g.textContent = 'Some text here';
g.setAttribute('value','myValue');

Element Processing

This function is not meant to be called outside the library. It ensures that data is in an iterable format that can be processed by the insertion and removal methods.

//turn something into a set
function $set(input) {
    var set;
    if (typeof input === 'string' || input instanceof String) {
        set = $get(input);
    } else if (input.nodeType === 1 || input.nodeType === 3) {
        set = [input];
    } else if (input[Symbol.iterator] !== undefined) {
        set = input;
    } else {
        throw new TypeError('Cannot convert ' + typeof input + ' to iterable');
    }
    return set;
}

Element Sibling Insertion

Designed to mimic most of jQuery's insertBefore() method. I chose to allow only one element inserted at a time, but that element can be inserted multiple times. I also chose to clone the element for all but the first insertion so that event listeners would be preserved for the first one. There may be a better way to do this, though, so I'd appreciate suggestions.

//equivalent function $addAfter() not shown here
function $addBefore(input, target) {
    var newElm = $set(input)[0];
    var oldElms = $set(target);
    if (oldElms[0]) {
        var firstTarget = oldElms[0];
        firstTarget.parentNode.insertBefore(newElm, firstTarget);
        for (var i = 1; i < oldElms.length; i++) {
            var oldElm = oldElms[i];
            var clone = newElm.cloneNode(true);
            oldElm.parentNode.insertBefore(clone, oldElm);
        }
    }
}

Example:

var foo = $make('div', {'text': 'This is a test'});
$addBefore(foo, '.myClass'); //adds an instance of foo before each myClass

Element Removal

Removes an element or collection of elements.

//element removal
function $remove(input) {
    var rem = $set(input);
    for (var i = 0; i < rem.length; i++) {
        var elm = rem[i];
        elm.parentElement.removeChild(elm);
    }
}

Example:

$remove('#myId');
$remove('.myClass');

//Equivalent to:

var rem = document.querySelectorAll('#myId');
rem.parentNode.remove(rem);

var myClassColl = document.querySelectorAll('.myClass');
for (var i = 0; i < myClassColl.length; i++) {
    var elm = myClassColl[i];
    elm.parentNode.remove(elm);
}


texts:
First time around Code Review so please be gentle (and I am happy for comments on which angles of this post are a good fit and which less so). I'm not pretty much used to software engineering in Python, and so I figured this might be a match:

import pickle

class Lexicon:
    'a lexicon holding each term and providing some lexicon services like term frequency, and term ids'

    def __init__(self):
        self.dictt = {}

    def size(self):
        return len(self.dictt)

    def add(self, token):
        if token in self.dictt:
            self.dictt[token] = self.dictt[token] + 1
        else:
            self.dictt[token] = 1
            return token # for traceability by the caller

    def remove_low_frequency(self, min_frequency):
        'removes low frequency tokens'
        self.dictt = dict(filter(lambda kv: kv[1] >= min_frequency, self.dictt.items()))

    def pickle(self, output_file_name):
        with open(output_file_name, 'wb') as handle:
            pickle.dump(self.dictt, handle, protocol=pickle.HIGHEST_PROTOCOL)

    @staticmethod
    def unpickle(input_file_name):
        with open(input_file_name, 'rb') as handle:
            new_lexicon = Lexicon()
            new_lexicon.dictt = pickle.load(handle)
            return new_lexicon

    def equals(self, other):
        return self.dictt == other.dictt

Am I being non-idiomatic above, or, just cumbersome anywhere?
Does my unpickle method actually represent potential for a huge memory leak as I'm reusing the name but putting a different dictionary into it?
What might be the Pythonic idiom for a correct implementation in these cases?
And what is the Pythonic way of making this class safe for concurrent usage? (thread-safe)


texts:
I recently was playing around with the idea of having an image appear when the user scrolls and came up with the following. Is there a better or more efficient way to do it?

var pastScroll;
jQuery(document).scroll(function () {
    var currentScroll = jQuery(document).scrollTop();
    if (pastScroll == currentScroll) {
        //console.log("not moving");
        jQuery('#content').css('background-image', 'url("/onScroll/blank.png")');
        // clear background
    }
    else {
        jQuery('#content').css('background-image', 'url("/onScroll/logo.png")');
        jQuery('#content').css('background-repeat','no-repeat');
        jQuery('#content').css('background-position', 'center');
        //console.log('moving');
        pastScroll = currentScroll;
        setTimeout(function () {
            if (pastScroll == currentScroll) {
                //console.log("not moving");
                jQuery('#content').css('background-image', 'url("/onScroll/blank.png")');
            }
        }, 100)
    }
});

You can ignore the use of jQuery instead of $ because it's being used in wordpress and ignore the css style added. I'm just wanting to focus on the conditionals and triggering. Any constructive criticism is appreciated, thanks.


texts: Sum of maximum primes as another prime below a million

texts:
This is a project Euler Problem #50. Here is my solution with the problem.

/*
 * The prime 41, can be written as the sum of six consecutive primes: 41 = 2
 * + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that
 * adds to a prime below one-hundred. The longest sum of consecutive primes
 * below one-thousand that adds to a prime, contains 21 terms, and is equal
 * to 953. Which prime, below one-million, can be written as the sum of the
 * most consecutive primes?
 */
public static int get50() {
    int max = 21;
    int prime_max = 953;
    ArrayList<Integer> primes = Helper.getPrimes(1000000);
    for (int len = 21; len <= primes.size(); len += 2) {
        long sum = 0;
        if (primes.get(len - 1) > 1E6) {
            break;
        }
        if (sum > 1E6) {
            return prime_max;
        }
        for (int k = 0; len + k - 1 < primes.size(); k++) {

            if (k == 0) {
                for (int i = 0; i < len; i++) {
                    sum += primes.get(i);
                }
            } else {
                sum += primes.get(len + k - 1) - primes.get(k - 1);
            }
            if (primes.get(len + k - 1) > 1E6 || sum > 1E6) {
                break;
            }
            if (Helper.isPrime((int) sum)) {
                if (len > max) {
                    max = len;
                    prime_max = (int) sum;
                }
                break;
            }
        }
    }
    return prime_max;
}

Some things I wish to improve:

Time (currently over 40 seconds, Answer is 997651, Time taken 43.762743956 seconds)
If possible && If reduces time Then using the new Java 8 methods.This would help me learn it too.


texts:
User has number in head, the program must guess the number.

public class GuessingGame extends JFrame{

    JButton newGameButton, highButton, lowButton, correctButton, exitButton;
    JLabel initialTextLabel, enterLabel;
    JTextArea commentTextArea;
    JScrollPane scroll;
    private int guess, high = 101, low = 0, tries = 1;

    public guessingGame()
    {
        title("Guessing Game");
        newGameButton = new JButton("Start Game");
        exitButton = new JButton("Exit Game");
        highButton = new JButton("Too High");
        lowButton = new JButton("Too Low");
        correctButton = new JButton("Correct!");

        commentTextArea = new JTextArea(null,10,30);
        scroll = new JScrollPane(commentTextArea);
        commentTextArea.setEditable(false);
        initialTextLabel = new JLabel("Think of a number between 0 & 100 can the computer guess it");
        enterLabel = new JLabel("Is your number: ");

        //add components

        highButton.setVisible(false);
        lowButton.setVisible(false);
        correctButton.setVisible(false);

        //set default jframe size

        //create and register the button event handlers

    }//end of GuessGame constructor

    //highButtonHandler class
    class highButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
                high = guess;
                guess = low + (guess - low) / 2;
                tries++;
                commentTextArea.append("Is the number " + guess + " too small, too high or correct.\n");
        }
    }//end of high class

    //lowButtonHandler class
    class lowButtonHandler implements ActionListener
        {
            public void actionPerformed(ActionEvent e)
            {
                low = guess;
                guess = guess + (high - guess) / 2;
                tries++;
                commentTextArea.append("Is the number " + guess + " too small, too high or correct.\n");
            }
        }//end of low class

    //correctButtonHandler class
    class correctButtonHandler implements ActionListener
        {
            public void actionPerformed(ActionEvent e)
            {
                commentTextArea.append("The computer took " + tries + " tries to guess your number");
            }
        }//end of correct class

    //newGame ButtonHandler class
    class newGameButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            commentTextArea.setText(null); //clear textArea
            //reset values
            guess = 50;
            tries = 1;
            low = 0;
            high = 101;

            commentTextArea.append("Is the number " + guess +" too small, too high or correct.\n");
            newGameButton.setText("Start New Game"); //set button text
        }
    }//end of newGame class

    //exitButtonHandler class
    class exitButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }

    public static void main(String[] args)
    {
        guessingGame myGuessGame = new guessingGame(); //instantiate a GUI object
        myGuessGame.setVisible(true);
    }//end main
}


texts: Simple Random Password Generator in Python

texts:
I've made a password generator that works fine. It takes alphabetic, numeric, and punctuation characters and randomly generates a 8-16 character password.

import sys
import string
import random

def PasswordGenerator():
    Name = input("What is your name? ")
    if Name.isalpha():
        GeneratePassword = input(Name + " would you like to generate a random password? ")
        YesOptions = ["Yes", "yes", "Y", "y"]
        NoOptions = ["No", "no", "N", "n"]
        PasswordCharacters = string.ascii_letters + string.digits + string.punctuation
        while GeneratePassword in YesOptions:
            Password =  "".join(random.choice(PasswordCharacters) for i in range(random.randint(8, 16)))
            print(Password)
            GeneratePasswordAgain = input("Would you like to generate another random password? ")
            while GeneratePasswordAgain in YesOptions:
                Password =  "".join(random.choice(PasswordCharacters) for i in range(random.randint(8, 16)))
                print(Password)
                GeneratePasswordAgain = input("Would you like to generate another random password? ")
                break
            while GeneratePasswordAgain in NoOptions:
                print("Good bye!")
                sys.exit()
                break
            while GeneratePasswordAgain not in YesOptions or NoOptions:
                print("Not a valid response! Try again.")
                GeneratePasswordAgain = input("Would you like to generate another random password? ")
                break
        while GeneratePassword in NoOptions:
            print("Good bye!")
            sys.exit()
        while GeneratePassword not in YesOptions or NoOptions:
            print("Not a valid response! Try again.")
            PasswordGenerator()
            while GeneratePassword in YesOptions:
                Password =  "".join(random.choice(PasswordCharacters) for i in range(random.randint(8, 16)))
                print(Password)
                GeneratePasswordAgain = input("Would you like to generate another random password? ")
                while GeneratePasswordAgain in YesOptions:
                    Password =  "".join(random.choice(PasswordCharacters) for i in range(random.randint(8, 16)))
                    print(Password)
                    break
                    GeneratePasswordAgain = input("Would you like to generate another random password? ")
                while GeneratePasswordAgain in NoOptions:
                    print("Good bye!")
                    sys.exit()
                    break
                while GeneratePasswordAgain not in YesOptions or NoOptions:
                    print("Not a valid response! Try again.")
                    GeneratePasswordAgain = input("Would you like to generate another random password? ")
                    break
        while GeneratePassword in NoOptions:
            print("Good bye!")
            sys.exit()
    while Name is not Name.isalpha:
        print("Not a valid response! Try again.")
        PasswordGenerator()

PasswordGenerator()


texts:
I'm making a program to compare Borderlands 3 weapon damage over time in a graphic. There's still some work to be done, like implementing elemental damage, but I'd like to know if I'm doing a good job for now regarding the main firing logic.

My biggest concerns are:

General readability.
WeaponReload and WeaponFire extend WeaponAction, a class containing the properties .startTime, .endTime and .duration (included after the Weapon class code) and both are being treated as if they're the same. I think some other languages can do something similar using structs and protocols to check conformity and I'm not sure if this is the right way to do it in JavaScript.
I don't know whether I'm doing a good use of the try {...} catch {...} statement in Weapon.fullAuto or if this logic could be improved upon using other methods.

class Weapon {
    constructor (damage, fireRate, reloadSpeed, magazineSize, elementalDamage, elementalChance) {
        this.damage = damage
        this.fireRate = fireRate
        this.reloadSpeed = reloadSpeed
        this.magazineSize = magazineSize
        this.elementalDamage = elementalDamage
        this.elementalChance = elementalChance

        this.bulletsLeftInMagazine = magazineSize
    }
    get timePerShot () {
        return 1 / this.fireRate
    }
    fire (startTime = 0) {
        if (this.bulletsLeftInMagazine < 1)
            throw new Error("Not enough bullets in the magazine")

        let whenCanFireAgain = startTime + this.timePerShot

        --this.bulletsLeftInMagazine

        return new WeaponShot(startTime, whenCanFireAgain, this.damage)
    }
    reload (startTime = 0) {
        let whenCanFireAgain = startTime + this.reloadSpeed

        this.bulletsLeftInMagazine = this.magazineSize

        return new WeaponReload(startTime, whenCanFireAgain)
    }
    fullAuto (duration, startTime = 0) {
        let localActionStartTime = 0,
            globalActionStartTime = startTime,
            actions = []

        while (duration > localActionStartTime) {

            let localActionEndTime,
                globalActionEndTime,
                action

            try {
                action = this.fire(globalActionStartTime)
            } catch {
                action = this.reload(globalActionStartTime)
            }

            actions.push(action)

            localActionStartTime += action.duration
            globalActionStartTime += action.duration

        }

        return actions
    }
}

class WeaponAction {
    constructor (startTime, endTime, damageDealt) {
        this.startTime = startTime
        this.endTime = endTime
        this.damageDealt = damageDealt
    }
    get duration () {
        return this.endTime - this.startTime
    }
}


texts: Time delay indication bar for a text game

texts:
For a game I am writing in Python 3.6.5, I made a text-based animation to indicate the passage of time (when chopping a tree or mining a rock, etc). I did a lot of trial and error to get the output how I wanted it, however it seems like I went about it in an overly-complicated way. I was wondering if there is a more efficient way to write this.

import os
import time

def progress_bar(text,secs):
    bar = '['
    c = 0 #used in sum method to determine number of Xs in bar

    for i in range(0,11):
        print(text+'\n')
        bar = bar.replace(' ','') #get rid of previous spaces added to bar
        num_of_X = sum(c == 'X' for c in bar) #get number of Xs (progress)
        for x in range(0,(10 - num_of_X)): #Fill remaining space after Xs
            bar += ' '
        print(bar + ']')
        bar += 'X'
        time.sleep(secs)
        os.system('cls' if os.name == 'nt' else 'clear') #clears terminal

    input('Loading complete!')

progress_bar('Enter Your Text Here!',0.15)


texts: Optimize Performance challenge 'Vinay Queried '

texts:
Input:

  The first line contains N denoting the length of Target String. This
  line is followed by the Target String. The Target String is followed
  by an integer Q denoting the number of queries asked. After this Q
  lines follow each line containing a Query String.

  Output:

  For each query output the total number of distinct Cruel Pairs that
  satisfies the given conditions.

  Constraints:

  \$1 \le N \le 5000\$

  \$1 \le Q \le 10^4\$

  Sum of Lengths of all Query Strings \$\le\$ 106

  All strings are composed only of '0' - '9'

  SAMPLE INPUT

5
75201
5
78945884875
22
00048
77
501

  SAMPLE OUTPUT

0
8
8
6
5

  Explanation

  Query String 1 : No such Pair exist.

  Query String 2 : Pairs are (1,2) , (1,3) , (1,4) , (1,5) , (2,3) ,
  (2,4) , (2,5) , (3,5)

  Query String 5 : Pairs are (1,3) , (1,4) , (1,5) , (2,4) , (2,5)

  Time Limit:1.0 sec(s) for each input file.

  Memory Limit:256 MB

  Source Limit:1024 KB

FUll question:
http://qa.geeksforgeeks.org/9744/vinay-queried-interesting-problem-optimization

Code:

def get_all_substrings(input_string, length):
    return [int(input_string[i:j + 1]) for i in xrange(length) for j in xrange(i, length)]

N = int(raw_input())

target = raw_input()

target_subsets = get_all_substrings(target, N)
target = int(target)

Q_N = int(raw_input())

queries_list=[]
output=[]

for x in xrange(Q_N):
    queries_list.append(int(raw_input()))

for x in queries_list:
    if x > target:
        print 0
        continue
    cruel_pairs = sum(i>x for i in target_subsets)
    print cruel_pairs


texts: Copying orders and prices into another Excel sheet

texts:
I would like to know if the below VBA can be streamlined to process faster, since it takes on average 9hrs to complete a sheet (800 000 lines), and I have quite a few to get through. Running on 3 computers already to get ahead of the work.

Sub Calculate_Sheet()

Dim orderSh As Worksheet
Dim wiroSh As Worksheet
Dim lastRow As Long, r As Long
Dim pctComp As Double
Dim Arr1 As Variant
Dim StartTime As Double
Dim MinutesElapsed As String

StartTime = Timer

With ThisWorkbook
'calculator
  Set orderSh = .Sheets("ORDER")
'price list
  Set wiroSh = .Sheets("WiroA3C100gsmI100gsm116-118pp ")
End With

Arr1 = wiroSh.Range("C1:M800001")
lastRow = wiroSh.Cells(Rows.Count, 3).End(xlUp).Row

For r = 2 To 2

'copy from price list to calculator
  orderSh.Range("F4") = Arr1(r, 1)
  orderSh.Range("F5") = Arr1(r, 2)
  orderSh.Range("F6") = Arr1(r, 3)
  orderSh.Range("F7") = Arr1(r, 4)
  orderSh.Range("F8") = Arr1(r, 5)
  orderSh.Range("F9") = Arr1(r, 6)
  orderSh.Range("F10") = Arr1(r, 7)
  orderSh.Range("F11") = Arr1(r, 8)
  orderSh.Range("F12") = Arr1(r, 9)
  orderSh.Range("F13") = Arr1(r, 10)

'copy result
  wiroSh.Range("m" & r).Value = orderSh.Range("F14")

 Next r

    For r = 3 To 400001

    'copy from price list to calculator
        orderSh.Range("F4") = Arr1(r, 1)

    'copy result
        wiroSh.Range("m" & r).Value = orderSh.Range("F14")

         'display the row and percentage each 1000 rows
        If r Mod 1 = 0 Then
        Application.StatusBar = "Row = " & r & Format(r / lastRow, " #0.00%")
        End If

     Next r

          For r = 400002 To 400002
          'copy from price list to calculator
              orderSh.Range("F4") = Arr1(r, 1)
              orderSh.Range("F5") = Arr1(r, 2)
              orderSh.Range("F6") = Arr1(r, 3)
              orderSh.Range("F7") = Arr1(r, 4)
              orderSh.Range("F8") = Arr1(r, 5)
              orderSh.Range("F9") = Arr1(r, 6)
              orderSh.Range("F10") = Arr1(r, 7)
              orderSh.Range("F11") = Arr1(r, 8)
              orderSh.Range("F12") = Arr1(r, 9)
              orderSh.Range("F13") = Arr1(r, 10)

        'copy result
              wiroSh.Range("m" & r).Value = orderSh.Range("F14")

     Next r

                For r = 400003 To 800001
                  'copy from price list to calculator
                      orderSh.Range("F4") = Arr1(r, 1)

                  'copy result
                         wiroSh.Range("m" & r).Value = orderSh.Range("F14")

           'display the row and percentage each 1000 rows
  If r Mod 1 = 0 Then
     Application.StatusBar = "Row = " & r & Format(r / lastRow, " #0.00%")

  End If
Next r

MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
MsgBox "This code ran successfully in " & MinutesElapsed & " minutes", vbInformation

End Sub


texts:
In order to learn haskell, I wrote a solver for the Infinite House of Pancakes problem.

-- Solve the 'Infinite House of Pancakes' problem.
-- https://code.google.com/codejam/contest/6224486/dashboard#s=p1

import Text.Printf
import Control.Monad

-- Generic solver code

readInt :: IO Int
readInt = readLn

readIntList :: IO [Int]
readIntList = getLine >>= return . map read . words

main :: IO [()]
main = do
  n <- readInt
  forM [1..n] (\i ->
    parse >>= putStr . printf "Case #%d: %d\n" i . solve)

-- Problem-specific code

parse :: IO [Int]
parse = getLine >> readIntList

cost :: Int -> Int -> Int
cost l n = if r == 0 then q - 1 else q where (q, r) = n `quotRem` l

test :: Int -> [Int] -> Int
test l = (+l) . sum . map (cost l)

solve :: [Int] -> Int
solve s = minimum . map (\l -> test l s) $ [1 .. maximum s]

I used this python solution as a reference, which is based on the  following problem analysis. I tested  my program using those input and output files, and it seems to work fine:

$ stack ghc pancake.hs -- -O2
$ \time -f "%e s" ./pancake < B-large-practice.in | diff - B-large-practice.out
0.28 s

I'm looking for comments about the following points:

coding style
performance (currently runs in 0.28 seconds using -O2, against 5.5 seconds for python 3)
bind operators vs do syntax (I used both  here, but it was mostly for educational purposes)
tools and ecosystem (code analysis, better compilation flags, etc.)

EDIT - Thanks to @Gurkenglas answer, I've been able to improve this program quite a lot. Here's a link to the corresponding gist.


texts: Async telnet connection over StreamSocket

texts:
My team and I have a very poor understanding of best practices in relation to telnet. We have Task.Delay and Task.Wait in the code, including async voids and from what I understand those are potential areas that can cause deadlocks and other issues.

I'm trying to understand async in relation to running a telnet client. Is this a safe implementation of cancellation tokens and telnet connections?

public enum TelnetClientStatus : int
{
    Unset = 0,
    Connected= 1,
    Disconnected  = 2,
    Failed = 3
}

public TelnetClientStatus Status { get; set; } = TelnetClientStatus.Unset;

public async Task OpenConnection()
{
    //Don't allow the session to keep trying to open after the 5 seconds
    var cancellationTokenSource = new CancellationTokenSource();
    cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(5));
    Status = await Task.Run(MakeConnection, cancellationTokenSource.Token);
}

private async Task<TelnetClientStatus> MakeConnection()
{
    _streamSocket = new StreamSocket();

    _dataWriter = new DataWriter(_streamSocket.OutputStream);
    _dataReader = new DataReader(_streamSocket.InputStream)
    {
        InputStreamOptions = InputStreamOptions.Partial
    };

    try
    {
        await _streamSocket.ConnectAsync(new HostName(HostName), Port.ToString());
        return TelnetClientStatus.Connected;
    }
    catch (TaskCanceledException) //All other exceptions need to be investigated not ignored
    {
        //I understand a connection failed due to timeout, give the app some flag to work with
        //Maybe retry the connection?
        return TelnetClientStatus.Failed;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}


texts: Perform instruction in loop every time except the last time?

texts:
The specific issue is this: I am writing to a file and want to output a new line after each line written.  If I use a normal loop without any further checks, this will create a blank line at the very end of the file for no reason.  So I need to do this every time except the last one.

Despite the fact that this is a specific problem, I'm actually looking for a better general coding practice to deal with scenarios like this, since it isn't the first and won't be the last time I have to deal with it.

Here's my unsatisfying solution:

//Write contents to the file
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
for(int i = 0; i < lines.size(); i++) {
    writer.write(lines.get(i));
    if(i < lines.size() - 1) writer.newLine();
}

It seems wasteful to check the conditions twice through each iteration of the loop, and I feel like there ought to be a better way to accomplish what I want without the vague code smell.  Anyone have any cool tips or tricks to make this more elegant?

It also prevents me from using an enhanced for loop, which makes me sad.

lines is a List<String>.

Also, for those saying I should just join all the Strings with \n, that's not an adequate solution.  Firstly, it doesn't actually address the general coding practice.  Secondly, when writing to a file with a BufferedWriter, it's important to use newLine() rather than writing a \n.


texts:
I'm learning Rust by completing a variety of coding challenges, such as the Google Codejam problem stated in the title.  I completed a Python 3 implementation that I liked, which I then tried to port over to Rust.

To my surprise, the Python implementation appeared to be considerably faster: when I ran time python3 ../a.py ../A-large-practice.in > /dev/null, I got times of roughly .075s for each Python run as compared to when I ran time cargo run --release ../A-large-practice.in > /dev/null for which I got roughly .210s for each Rust run.  These times come from averaging the sums of the usr and sys outputs generated by running the time command around 10 times per language.

How can I improve my Rust implementation so that it better conforms to best practices and also ends up being faster (at least to a level comparable with the Python implementation)?

use std::env::args;
use std::fs::File;
use std::io::Read;

fn main() {
    let args: Vec<String> = args().collect();
    let mut input = String::new();
    let mut f = File::open(&args[1]).unwrap();
    f.read_to_string(&mut input).unwrap();

    let mut input = input.lines();
    let num_inputs: u32 = match input.next() {
        None => panic!("No contents."),
        Some(num) => {
            match num.trim().parse() {
                Ok(num) => num,
                Err(_) => panic!("First line in input not a number."),
            }
        }
    };

    for i in 0..num_inputs {
        let mut score = 0;
        let moods: Vec<char> = match input.next() {
            None => panic!("Missing content."),
            Some(mood) => mood.chars().collect(),
        };
        let mut problems: Vec<&char> = Vec::new();
        for (j, mood) in moods.iter().enumerate() {
            /*
             * the assumption is that you'll only request problems that're the same mood that the grader is in
             * reason being that you can receive a maximum of 10 points and a minimum of 5,
             * whereas for the other mood it'll be a max of 5 and a min of 0
             */
            if problems.is_empty() {
                problems.push(mood);
            } else if problems.len() >= moods.len() - j {
                if problems.last() == Some(&mood) {
                    score += 10;
                } else {
                    score += 5;
                }
                problems.pop();
            } else if problems.last() == Some(&mood) {
                score += 10;
                problems.pop();
            } else {
                problems.push(mood);
            }
        }
        println!("Case #{}: {}", i+1, score);
    }
}


texts:
I just wrote a singleton base class for a hobby project I'm currently working on. Python is not my first language, which is why I am not sure if everything is done the pythonic way.

I also used multiple resources/tutorials/articles for Python2 and 3. My singleton is supposed to be Python3 compatible. The implementation should be thread safe, which is why I enter a lock while creating the instance.

To allow custom initializations I decided to let the user provide a create_class function where the object could be created and initialized. The base class is more like a "singleton-factory" than a "classical" singleton where the object itself provides both (logic and singleton).

Please tell me what can I do better, more efficient, and more pythonic.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
  this module implements provides a baseclass for
  a singleton.

  it allows you to simply create singleton objects
  by overriding the PyRlSingleton class.

  it gives you access to the singleton instance in
  a explicit way via a "get_instance()" function.

  if you mistakingly try to create your singleton
  class it raises an exception telling you that this
  is not allowed.

  you have to provide a "create_instance()" function
  which creates your singleton implementation; this
  is automatically called when the singleton is used
  the first time.

  the creating process is thread safe, so you can use
  it in a multithreading environment.

  see the "main()" function for a simple example.

  have fun!
"""

import _thread # allocate_lock()

class PyRlSingletonMeta(type):
  def __call__(cls, *args, **kwargs):
    """
      this method disallows creation of a
      singleton via a ClassName() call
    """
    raise Exception("not allowed, use get_instance()")

class PyRlSingleton(object, metaclass = PyRlSingletonMeta):
  __lock = _thread.allocate_lock()
  __inst = None

  @classmethod
  def create_instance(cls):
    """
      this is the default create_instance method
      you should provide your own via overriding.
    """
    raise Exception("create_instance() missing in {0}".format(cls.__name__))

  @classmethod
  def get_instance(cls):
    """
      this classmethod returns always the same instance
      of cls. it creates an object via calling the
      create_instance class method when it is first
      called.
    """
    if cls.__inst == None:
      with cls.__lock:
        if cls.__inst == None:
          cls.__inst = cls.create_instance()
    return cls.__inst

def main():
  """ test the singleton in a simple example, a logger """

  class LoggerImpl(object):
    """ my class supposed to be a singleton """
    def log(self, text):
      print(text)

  class Logger(PyRlSingleton):
    """
      the singleton itself. i have to override the
      create_instance() class method and let it return
      my LoggerImpl.
    """
    @classmethod
    def create_instance(cls):
      """ create and initialize your implementation here. """
      return LoggerImpl()

  Logger.get_instance().log("hello world")
  l1 = Logger.get_instance()
  l2 = Logger.get_instance()
  if l1 != l2:
    raise Exception("what?")
  if l1 != Logger.get_instance():
    raise Exception("ugh!?")

if __name__ == '__main__':
  main()


texts: Apply a custom property on every descendent of an element

texts:
I chose this approach to keep the code short, as I can't think of purely iterative approach without conditionally testing or storing the index of a node for moving horizontally. If I wanted re-usability, I could pass in the property and the value and use node[passedProp]=passedValue.

The code:

function applyProp(node){
    node.prop='prop';
    for(var i=0, len=node.children.length;i<len;i++)
    {
        applyProp(node.children[i]);
    }

}
applyProp(node);


texts: Print all permutations with some constraints

texts:
I've the following problem:

  Print all valid phone numbers of length n subject to following
  constraints:
       1.If a number contains a 4, it should start with 4
       2.No two consecutive digits can be same
       3.Three digits (e.g. 7,2,9) will be entirely disallowed, take as input

Here's my solution:

public static void ans(int length, int d1, int d2, int d3) {
    StringBuffer numbers = new StringBuffer();

    for(int i = 0; i < 10 ;i++) {
        if(i != d1 && i != d2 && i != d3) {
            numbers.append(i);
        }
    }
    printNumbers("", numbers.toString(), length);
}

public static void printNumbers(String soFar, String remaining, int length) {
    if(soFar.length() == length) {
        boolean four = false;
        boolean sameAdjDigits = false;

        for(int i = 1; i < soFar.length(); i++) {
            if(soFar.charAt(i-1) == soFar.charAt(i)) sameAdjDigits = true;
            if(soFar.charAt(i) == '4') four = true;
        }

        if(!sameAdjDigits) {
            if(!four || (four && soFar.charAt(0) == '4'))
                System.out.print(soFar + " ");
        }

        return;
    }

    if(soFar.length() < length) {
        for(int i = 0; i < remaining.length(); i++) {
            String newSoFar = soFar + remaining.charAt(i);
            String newRemaining = remaining.substring(0, i) + remaining.substring(i+1);
            printNumbers(newSoFar, newRemaining, length);
        }
    }
}

I ran some tests on this code and checked all the printed values. It worked for length 1 and 2. However, I couldn't verify for length > 2 because there were too many numbers.

Can anyone verify if my code runs a correct result? Is there any part of the code that can be improved?


texts:
This appears to work. Are there any edge cases I am missing? What are your thoughts on the algorithm and implementation?

template <typename el>
void Linkedlist<el>::reverse() {
    Node<el> * oldHead = head;
    Node<el> * tailAfterReversal = recReverseList( head->getNextNode() );
    oldHead->setNextNode(NULL);
    tailAfterReversal->setNextNode(oldHead);
}

// Reverses part of a linked list starting from toRevesrPortionHead, returns the tail node
// after the reversal operation has been performed
template <typename el>
Node<el> * Linkedlist<el>::recReverseList( Node<el> * toReversePortionHead ) {
    if ( toReversePortionHead->getNextNode() == NULL ) {
        head = toReversePortionHead;
        return toReversePortionHead;
    }

    Node<el> * tailAfterReversal = recReverseList( toReversePortionHead->getNextNode() );
    tailAfterReversal->setNextNode(toReversePortionHead);
    toReversePortionHead->setNextNode(NULL);

    return toReversePortionHead;

}


texts: Comparing JSON documents for changes to values

texts:
Please go through below code and improve the quality by reducing the IF conditions:

I have 2 jsons, first one is the source and second one is the updated json. I have to compare both values and set true/false flags. Based on the flags i need to proceed further.

I am checking below conditions:

NULL changed to DECLINED
NULL changed to a VALUE
VALUE changed to DECLINED
VALUE1 changed to VALUE2

O/P -
canProceed = (nullDec) ? (nullDec && (nullVal || valDec || valVal)) :(nullVal || valDec || valVal);

Plnkr - https://plnkr.co/edit/gKJXibTFQhInBOhz?open=lib%2Fscript.js

import angular from 'angular';

angular.module('plunker', []).controller('MainCtrl', function($scope) {
  $scope.name = 'Plunker';

    var json1={id:"01", name:"Jon", city:null, state:"NY", phone:null, zip:"06033"};
    var json2={id:"02", name:"Kris", city:"DECLINED", state:"DECLINED", phone:"860-000-0000", zip:"06033"};
    var json3={id:"02", name:"Sam", city:"EDISON", state:"DECLINED", phone:"860-000-0000", zip:"06033"};

    compareJsons(json1, json2);

    function compareJsons(model1, model2){
        console.log(model1);
        console.log(model2);

        var decline = "DECLINED";
        var canProceed = false;
        var nullVal = false;
        var nullDec = false;
        var valDec = false;
        var valVal = false;

        angular.forEach(model1, function(m1Val, m1Key){
           if(!m1Val){
               console.log("Found NULL - "+ m1Key +" - " + m1Val);

              angular.forEach(model2, function(m2Val, m2Key){
                  if((m2Key === m1Key) && (m2Val !== m1Val)){
                      console.log(m1Key +" - " + m1Val + "  CHANGED TO  " + m2Key +" - " + m2Val);
                      if((m2Val === decline) && !(m1Val)){
                          nullDec = true;
                      }
                      if(((m2Val) && (m2Val !== decline)) && !(m1Val)){
                          nullVal = true;
                      }
                  }
              })
           } else {
              angular.forEach(model2, function(m2Val, m2Key){
                  if(m2Key === m1Key && m2Val !== m1Val){
                      if(m2Val === decline){
                            console.log(m1Key +" - " + m1Val + "  CHANGED TO " + m2Key +" - " + m2Val);
                            if(((m1Val) && (m1Val !== decline)) && (m2Val)){
                                valDec = true;
                            }
                      }else{
                            console.log(m1Key +" - " + m1Val + "  CHANGED TO " + m2Key +" - " + m2Val);
                            if((m1Val) && (m2Val)){
                                valVal = true;
                            }
                      }
                  }
              });
           }
        });

        console.log("NULL to DECLINE    - " + nullDec);
        console.log("NULL to VALUE      - " + nullVal);
        console.log("VALUE to DECLINE   - " + valDec);
        console.log("VALUE1 to VALUE2   - " + valVal);

        canProceed = (nullDec) ? (nullDec && (nullVal || valDec || valVal)):(nullVal || valDec || valVal);

        console.log("Can Proceed        - " + canProceed);

    }

});


texts: First program with scraping, lists, string manipulation

texts:
I wanted to find out which states and cities the USA hockey team was from, but I didn't want to manually count from the roster site here.

I'm really interested to see if someone has a more elegant way to do what I've done (which feels like glue and duct tape) for future purposes. I read about 12 different Stack Overflow questions to get here.

from bs4 import BeautifulSoup
from collections import Counter
import urllib2

url='http://olympics.usahockey.com/page/show/1067902-roster'
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())

locations = []
city = []
state = []

counter = 0
tables = soup.findAll("table", { "class" : "dataTable" })
for table in tables:
    rows = table.findAll("tr")
    for row in rows:
        entries = row.findAll("td")
        for entry in entries:
            counter = counter + 1
            if counter == 7:
                locations.append(entry.get_text().encode('ascii'))
        counter = 0

for i in locations:
    splitter = i.split(", ")
    city.append(splitter[0])
    state.append(splitter[1])

print Counter(state)
print Counter(city)

I essentially did a three tier loop for table->tr->td, and then used a counter to grab the 7th column and added it to a list. Then I iterated through the list splitting the first word to one list, and the second word to a second list. Then ran it through Counter to print the cities and states. I get a hunch this could be done a lot simpler, curious for opinions.


texts: Designing a listener method and making it Testable

texts:
I have a java based server application that needs to support multiple clients. In the main class I have a method that runs in an infinite loop and waits for client connection. Following is this method:

public void listen() {
    try {
        serverSocket = new ServerSocket(portNo);
        while (true) {
            clientSocket = serverSocket .accept();
            ClientMgr client = new ClientMgr(clientSocket);
            client.start(); //start a separate thread to manage client
        }
    } catch (Exception e) {
        //handle any exceptions
    } finally {
        close(); //close any open sockets
    }
}

I would like to know how I can design (change) this method such that it can be tested by a unit test. If it is already testable then suggest how this can be tested?


texts: Basic playing card generation and shuffle

texts:
This is my first attempt at Java so I appreciate any criticism or pointers.  The program should generate a full set of given decks and then shuffle them.

import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;

public class shuffle {
    //Make it easier to find array items
    static int value = 0;
    static int suit = 1;
    static int remaining = 2;

    public static void main(String Args[]) {
            int[][] deck;

            String clabel;
            //number of decks to generate
            int deckcount = 1;
            int decksize = deckcount * 52;

            deck = new int[decksize][2];
            //loop through deck building until deck reaches card count
            for (int c = 0; c < decksize;) {
                for (int s = 0; s < 4; s++) {
                    for (int v = 1; v <= 13; v++) {
                        deck[c][value] = v;
                        deck[c][suit] = s;
                        System.out.println(getCard(deck[c]));
                        c++;
                    }
                }
                //test parameters for debugging
                //System.out.println(""+c);
                //pressAnyKeyToContinue();
            }

            System.out.println("\nSHUFFLING\n");

            int order[];
            order = new int[decksize];
            order = shuffle(decksize);

            for(int i = 0;i < decksize;i++) {
                System.out.println(getCard(deck[order[i]]));
            }
        }
    //method to get cards correct label
    public static String getCard(int[] card) {
            String c_label, s_name = "", v_name = "";
            //get suit name
            switch (card[suit]) {
                case 0:
                    s_name = "Clubs";
                    break;
                case 1:
                    s_name = "Diamonds";
                    break;
                case 2:
                    s_name = "Hearts";
                    break;
                case 3:
                    s_name = "Spades";
                    break;
            }
            //get card label
            if (card[value] > 10 || card[value] == 1) {
                switch (card[value]) {
                    case 1:
                        v_name = "ACE";
                        break;
                    case 11:
                        v_name = "Jack";
                        break;
                    case 12:
                        v_name = "Queen";
                        break;
                    case 13:
                        v_name = "King";
                        break;
                }
            } else {
                v_name = "" + card[value];
            }
            c_label = v_name + " of " + s_name;

            return c_label;

        }
        //shuffle deck
    public static int[] shuffle(int size) {
        Random rgen = new Random(); // Random number generator
        int[] order;
        order = new int[size];

        for(int i = 0; i < order.length; i++) {
            order[i] = i;
        }

        for (int i = 0; i < order.length; i++) {
            int randomPosition = rgen.nextInt(order.length);
            int temp = order[i];
            order[i] = order[randomPosition];
            order[randomPosition] = temp;
        }

        return order;
    }
    private static void pressAnyKeyToContinue() {
        System.out.println("Press any key to continue...");
        try {
            System.in.read();
        } catch (Exception e) {}
    }
}


texts:
How to make this code better?

if (Program.Data.DataBase.TryOpenDataBase())
{
 bool result;
 DataBase= new Program.Data.DataBase(out result);
 if (!result)
 {
    if (Program.DataBase!= null)
       Program.DataBase.Dispose();
     Program.DataBase= null;
     Log.WriteERROR("Can not open database");
     Application.Exit();
     return;
 }
 else
 {
    Log.WriteERROR("Can not open database");
    Application.Exit();
    return;
 }


texts: Program follows sequence of instructions to arrive at destination

texts:
I'm warming up with Clojure to try my hand at the advent of code challenge that starts in December. This is my attempt at the first challenge from last year.

This is my first attempt at a non trivial program in clojure, so comments on any part of the program would be appreciated.

(defrecord Vector [x y])

(defrecord State [orientation position])

(def orientations {
    :north (Vector. 0 -1),
    :east (Vector. 1 0),
    :south (Vector. 0 1),
    :west (Vector. -1 0) })

;; Given a compass orientation
;; Return the new orientation after a left turn
(defn turnLeft [current_orientation]
    (case current_orientation
        :north :west
        :east :north
        :south :east
        :west :south))

;; Given a compass orientation
;; Return the new orientation after a right turn
(defn turnRight [current_orientation]
    (case current_orientation
        :north :east
        :east :south
        :south :west
        :west :north))

;; Given a position, orientation and distance
;; Return a new position after moving in that direction for that distance
(defn moveForward [current_position orientation distance]
    (let [direction_vector (orientation orientations)]
        (Vector.
            (+ (:x current_position) (* distance (:x direction_vector)))
            (+ (:y current_position) (* distance (:y direction_vector))))))

;; Given a state and an instruction
;; Return a new state
(defn act [state, instr]
    (case instr
        \L (State. (turnLeft (:orientation state)) (:position state))
        \R (State. (turnRight (:orientation state)) (:position state))
        (State.
            (:orientation state)
            (moveForward (:position state) (:orientation state) instr))))

;; Given a starting state and list of instructions
;; Return the final state
(defn doActions [state instrs]
    (if (empty? instrs)
        state
        (doActions (act state (first instrs)) (rest instrs))))

;; Instructions are a sequence of combined instructions as follows:
;; L13, R10, R1, L3, ...
;; Convert this into an alternating list
;; of TurnLeft / TurnRight and Move instructions
(def instrs
    (->> "input.txt"
        slurp
        (re-seq #"[LR]|\d+")
        (map
            (fn [instr]
                (case instr
                    "L" \L
                    "R" \R
                    (read-string instr))))))

(require '(java.lang.Math))
(let [finalstate (doActions (State. :north (Vector. 0 0)) instrs)]
    (+
        (Math/abs (get-in finalstate [:position :y]))
        (Math/abs (get-in finalstate [:position :x]))))


texts:
Is there is a better way of selecting the span tag that I'm dynamically adding?

Here's what I'm trying to do:

If you click the .toggle div, it shows a detailed div with the id that matches the href of the anchor tag in the particular .toggle div.

$('.toggle').click(function (e) {
  e.preventDefault();
  var elemHref = $(this).find("a").attr("href");
  var id = elemHref.replace('#', '');
  $("#"+id).toggle();
});

Before you click, when you hover over the .toggle div, it shows expand in a span tag if the details div is hidden.  When you are not hovering over the appropriate .toggle div, it shows nothing if the details div is hidden and close if the details div is visible.

$('.toggle').hover(function(e)
    {
        $(this).find("a:not(:has(span))").append('expand');
        $('.expand').eq(0).css({"position":"absolute", "bottom":"0", "right":"-5px"});
    },
    function()
    {
        var elem = $(this).find("a");
        var elemHref = elem.attr("href");
        var visibleDetail = $(elemHref).is(":visible");
        if(visibleDetail)
        {
            $('.expand').text('close');
        }
        else
        {
            elem.empty();
        }
    }
);

I've thought that using .children might help, but is there a better way altogether than with .find()/.children()?


texts:
I have the following given code after some refactoring:

public static void storePreferences() {
    try {
        Preferences.userRoot().exportSubtree(new FileOutputStream(ReleaseInfo.getAppFolder() + File.separator + SETTINGSFILENAME));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (BackingStoreException e) {
        e.printStackTrace();
    }
}

Now I wonder - should I explicitly close the FileOutputStream or the JVM takes care for doing so? I have looked at this question on the same topic, where it is said that it is not a good practice to rely on the garbage collector, but still I need a bit more confirmation (therefore this question). I have changed the above code to:

public static void storePreferences() {
    FileOutputStream fos = null;

    try {
        fos = new FileOutputStream(ReleaseInfo.getAppFolder() + File.separator + SETTINGSFILENAME);
        Preferences.userRoot().exportSubtree(fos);
    } catch (IOException | BackingStoreException e) {
        e.printStackTrace();
    } finally {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Here I close the stream manually, so which would be the better alternative and do the performed changes really bring something to the table?

Any other remarks?


texts: Simple string-split by root and sufix algorithm

texts:
A classic problem to split a string into its "root and suffix":

(Stemming) The word "walk" is the base form for word "walking" (suffix is "ing");
The file path /var/www is the base path of /var/www/myApp;
The string doi:10.1038/ncomms is the URN-prefix for doi:10.1038/ncomms7368 and doi:10.1038/ncomms7666;
The word "hello" is not a root for "walking" (suffix is "walking");

There are many ways to implement the same algorithm, so, what is the best? Examples in PHP, but valid for any language.

/**
 * Splits a string by its root and sufix.
 * @param $str string input
 * @param $root string empty when no root, or start string
 * @return array (rootFlag,sufix)
 */
function  str_splitByRoot($str, $root){
    ...
}

Algorithms str_splitByRoot1(), str_splitByRoot2(), ..., str_splitByRoot5()  or other (show more if you know). All do the same thing, are valid solutions.

function  str_splitByRoot1($str, $root){
    if (strpos($str,$root)===0)
        return array($root, substr($str, strlen($root)) );
    else
        return array( '', $str );
}

function  str_splitByRoot2($str, $root){
    $rootLen = strspn($str ^ $root, "\0");
    return array( substr($root,0,$rootLen), substr($str,$rootLen) );
}

function  str_splitByRoot3($str, $root){
    $s = explode($root,$str);
    return ( count($s)>1  && !array_shift($s) )?
      array($root,join($root,$s)):
      array('',$str);
}

function  str_splitByRoot4($str, $root){
    // to generalize need a secure regex, something like
    // $regex = str_replace(array('/','.','-'),array('\\/','\\.','\\-'),$root);
    $suffix = preg_replace("/^$root/",$str,1,$n);
    return $n?
      array($root,$suffix):
      array('',$str);
}

function  str_splitByRoot5($str, $root){
    // need also $root translating as algorithm 4.
    if (preg_match("/^$root(.+)$/",$str,$m))
          return array($root,$m[1]);
    else
          return array('',$str);
}

The first is the traditional way. The last (algorithms 4 and 5) use regular expression, the second trim excess garbage from strings that are null terminated; and the  third  remember that the algorithm  is a kind of split (explode function).

All can be used with

function str_sepByRoot($str,$root){
   return join(' * ',str_splitByRoot($str,$root));
}
print "\n".str_sepByRoot("walking","walk");
print "\n".str_sepByRoot("hello","walk");
print "\n".str_sepByRoot("walking-walk-walk","walk");
print "\n".str_sepByRoot("/var/www/myApp","/var/www/");
print "\n".str_sepByRoot("10.1038/ncomms7368","10.1038/ncomms");

returning

   walk * ing
    * hello
   walk * ing-walk-walk
   /var/www/ * myApp
   10.1038/ncomms * 7368


texts: Moving List View items from one list to another

texts:
I'm writing a form that contains 2 ListViews with a set of 4 buttons. 2 move all the items from one to the other in each direction, the other move only selected items in each direction.

Nothing fancy or complicated.

However I'm feeling like I could write the MoveItem method in a more elegant way and was wondering if any would mind taking a look and advising me.

private void MoveItem(ListView source, ListView dest, bool all)
{
    if (all)
    {
        foreach (ListViewItem item in source.Items)
        {
            source.Items.Remove(item);
            dest.Items.Add(item);
        }
    }
    else
    {
        foreach (ListViewItem item in source.SelectedItems)
        {
            source.Items.Remove(item);
            dest.Items.Add(item);
        }
    }
}

Any suggestions would be thankfully recived


texts:
I am upgrading my C++11 knowledge and repeating some essential algorithm. Here is binary search only in terms of iterators.

#include <iostream>

#include <vector>
#include <iterator>

using namespace std;

template<typename t_iter>
t_iter binarySearch(t_iter begin, t_iter end, typename iterator_traits<t_iter>::value_type q)
{
    typedef iterator_traits<t_iter>::value_type t_elem;
    size_t len = end - begin;

    if (len < 2)
    {
        if (*begin == q)
        {
            return begin;
        }

        return end;
    }

    t_iter middleElem = begin + len / 2;

    if (*middleElem < q)
    {
        return binarySearch(middleElem, end, q);
    }

    return binarySearch(begin, middleElem, q);
}

int main()
{
    int tmp[] = {1, 2, 4, 5, 8, 10, 20, 35, 41, 42, 100};
    size_t len = sizeof(tmp)/sizeof(tmp[0]);
    vector<int> a(tmp, tmp + len);

    int q = 35;

    auto it = binarySearch(a.begin(), a.end(), q);

    cout << distance(a.begin(), it) << endl;
}


texts:
The common FizzBuzz implementation I saw is using a check for % 15 for printing "FizzBuzz"

Would you let me know if there is anything wrong / better with this approach?

public class FizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            boolean fizzOrBuzz = false;
            if (i % 3 == 0) {
                System.out.print("Fizz");
                fizzOrBuzz = true;
            }
            if (i % 5 == 0) {
                System.out.print("Buzz");
                fizzOrBuzz = true;
            }

            if (fizzOrBuzz) {
                System.out.println();
            } else {
                System.out.println(String.valueOf(i));
            }
        }
    }
}


texts: Infinite monkey theorem demonstration in Python

texts:
This was the assignment:

  Here’s a self check that really covers everything so far. You may have
  heard of the infinite monkey theorem? The theorem states that a monkey
  hitting keys at random on a typewriter keyboard for an infinite amount
  of time will almost surely type a given text, such as the complete
  works of William Shakespeare. Well, suppose we replace a monkey with a
  Python function. How long do you think it would take for a Python
  function to generate just one sentence of Shakespeare? The sentence
  we’ll shoot for is: “methinks it is like a weasel”

  You’re not going to want to run this one in the browser, so fire up
  your favorite Python IDE. The way we’ll simulate this is to write a
  function that generates a string that is 27 characters long by
  choosing random letters from the 26 letters in the alphabet plus the
  space. We’ll write another function that will score each generated
  string by comparing the randomly generated string to the goal.

  A third function will repeatedly call generate and score, then if
  100% of the letters are correct we are done. If the letters are not
  correct then we will generate a whole new string.To make it easier to
  follow your program’s progress this third function should print out
  the best string generated so far and its score every 1000 tries

Soo i have created a python program which generates the string provided, i am in learning phase, can someone please suggest any improvement or any tips or corrections.

Note: I know i have not did the exact method said in that question, but i have created the expected result.
makeRandSent: This will give me random character.
compare: This will give me final result by comparing each user character with randomly generated character and  it will only change those chracter which are not match.

def makeRandSent(userSent):
    counter = 0
    randSent = [""] * (len(userSent) - 1)
    randSent.clear()
    while counter < len(userSent):
        counter = counter + 1
        randSent.append(myalphlist[random.randrange(0,len(myalphlist) - 1)])
    return randSent

def compare(userSent):
    myBoolList = [False] * len(userSent)
    myRandSent = makeRandSent(userSent)
    print("random sent: ",myRandSent)
    myFinalList = [""] * len(userSent)
    while myBoolList.count(False) > 0:
        counter = 0
        myRandSent = makeRandSent(userSent)
        for char in myRandSent:
            if char == userSent[counter]:
                myBoolList[counter] = True
                myFinalList[counter] = char
            counter = counter + 1
        print(myBoolList," Final: ",myFinalList)
    return myBoolList

E.G:
Input: compare("pratik")
Output after several automatic attempts by program: [True, True, True, True, True, True]  Final:  ['p', 'r', 'a', 't', 'i', 'k']


texts:
I wish to generate an online feedback system. Requirements are

Admin can enter feedback questions
Admin will select these questions and create a feedback session
One Question can be used in many feedback session
User can select any feedback session and answer/rate
one user can answer same feedback session more than once

My table structure is

dummy data (not all columns)

Questions
---------
QuestionId  Question
1           Question 1
2           Question 2
3           Question 3
4           Question 4
5           Question 5

Feedback
--------
FeedbackId  Questions
2           1,2,3,4,5                   -- Questions column has questionid from Question table

 FeedbackResults
    ---------------
    FeedbackResId   FeedbackId  QuetionID Answers    UserId
    1               2           4          4         1
    2               2           1          3         1
    3               2           5          3         1
    4               2           1          2         2

Please rate this design and provide valuable suggestions. Comma separated values are affordable ?


texts: Import data from XML files into data.frame

texts:
I have a number of XML files containing data I would like to analyse. Each XML contains data in a format similar to this:

<?xml version='1.0' encoding='UTF-8'?>
<build>
  <actions>
    ...
  </actions>
  <queueId>1276</queueId>
  <timestamp>1447062398490</timestamp>
  <startTime>1447062398538</startTime>
  <result>ABORTED</result>
  <duration>539722</duration>
  <charset>UTF-8</charset>
  <keepLog>false</keepLog>
  <builtOn></builtOn>
  <workspace>/var/lib/jenkins/workspace/clean-caches</workspace>
  <hudsonVersion>1.624</hudsonVersion>
  <scm class="hudson.scm.NullChangeLogParser"/>
  <culprits class="com.google.common.collect.EmptyImmutableSortedSet"/>
</build>

These are build.xml files generated by the continuous integration server, Jenkins. The files themselves don't have some important data that I would like, like the Jenkins job name, or the build number that created the xml. The job and build ids are encoded into the path of each file like .\jenkins\jobs\${JOB_NAME}\builds\${BUILD_NUMBER}\build.xml

I would like to create a data frame contain job name, build number, duration, and result.

My code to achieve this is the following:

library(XML)

filenames <- list.files("C:/Users/jenkins/", recursive=TRUE, full.names=TRUE, pattern="build.xml")

job <- unlist(lapply(filenames, function(f) {
    s <- unlist(strsplit(f, split=.Platform$file.sep))
    s[length(s) - 3]
}))

build <- unlist(lapply(filenames, function(f) {
    s <- unlist(strsplit(f, split=.Platform$file.sep))
    s[length(s) - 1]
}))

duration <- unlist(lapply(filenames, function(f) {
    xml <- xmlParse(f)
    xpathSApply(xml, "//duration", xmlValue)
}))

result <- unlist(lapply(filenames, function(f) {
    xml <- xmlParse(f)
    x <- xpathSApply(xml, "//result", xmlValue)
    return(x)
}))

build.data <- data.frame(job, build, result, duration)

Which gives me a data frame that looks like this:

  job             build result     duration
1 clean-caches    37    SUCCESS    248701
2 clean-caches    38    FAILURE    1200049
3 clean-caches    39    FAILURE    1200060
4 clean-caches    40    FAILURE    1200123
5 clean-caches    41    SUCCESS    358024
6 clean-caches    42    SUCCESS    130462

This works, but I have serious concerns about it from both a style and a performance point of view. I'm completely new to R, so I don't know what would be a nicer way to do this.

My concerns:

Repeated code:

The code blocks to generate the job and build vectors are identical. Same for duration and result. If I decide to import more nodes from XML, I'll end up repeating even more code.

Several iterations must be made of my list of files. There are thousands of XML files, and this number will likely grow. As above, if I wish to extract more data from the XML, I must add more iterations.


texts: Code redundancy issue while feeding dropdownlists

texts:
I have a dashboard to manage a learning center system. There are scenarios like admin create learning center and define a classroom in it and then assign some courses in it and assign students to those courses and assign a teacher for each courses.

In order to achieve this, I have to create lot of dropdownlists such as for creating a course you have to select first a learning center then an appropriate classroom.

Below is the code for the dropdownlists in assigning a student into a course:

    //Retrieve all learning centers
    studentAssignmentViewModel.LearningCenters = _learningCenterService.LearningCenters.ToList();
    studentAssignmentViewModel.StudentSelectListItem = studentAssignmentViewModel.LearningCenters
        .Where(y => y.Status != Status.Removed).OrderBy(x => x.Name)
        .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });

    //Retrieve All Students
    studentAssignmentViewModel.Students = _studentAssignmentService.Students.ToList();
    studentAssignmentViewModel.StudentSelectListItem = studentAssignmentViewModel.Students
        .Where(y => y.Status != Status.Removed).OrderBy(x => x.Name)
        .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });

    //If the user is not admin, it retrieves the courses belong to the teacher otherwise all courses
    var userId = _dashboardUserAuthenticationService.AuthenticatedDashboardUser.Id;
    var userRole = _dashboardUserService.Get(userId).UserRole;
    if (userRole != "1")
    {
        studentAssignmentViewModel.Courses = _studentAssignmentService.Courses.ToList();
        studentAssignmentViewModel.CourseSelectListItem = studentAssignmentViewModel.Courses
            .Where(t => (t.Status != Status.Removed) && t.TeacherId == userId).OrderBy(x => x.Name)
            .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
    }
    else
    {
        studentAssignmentViewModel.Courses = _studentAssignmentService.Courses.ToList();
        studentAssignmentViewModel.CourseSelectListItem = studentAssignmentViewModel.Courses
            .Where(t => (t.Status != Status.Removed)).OrderBy(x => x.Name)
            .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
    }

And I am repeating those similar code pieces in edit and create actions in mvc for all scenarios. So I don't know if there is enough information to make a statement but what would be your suggestions for such cases, what would be the best practice to get rid of those ugly code pieces? Since situations vary, turning them into classes would lead me into so many specific classes which cannot be used for any other situation.


texts:
I'm learning Smalltalk programming as I think its way ahead as an OOP programming tool. I would appreciate feedback regarding my coding of the following problem. I have a sequence of letters representing bases in a DNA and want to change the T to a U in the string. I have done this in two ways. The first uses the copyReplaceAll:with: message to the string object which changes every occurrence of 'T' to a 'U':

string := 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'.
string copyReplaceAll: 'T' with: 'U'.

My second method uses iteration and boolean conditions to test whether a 'T' is identified. I learned that I have to copy the string to an Array object, then iterate over that object and copy the elements to an empty array. Ideally I would like the original string object to be mutable. Am I going at this the wrong way? Here's my code:

string := 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'.
strCopy := string asArray.
empty := Array new: strCopy size.
cntr := 1.

strCopy do: [:char |
     (char = $T) ifTrue: [empty at:cntr put: $U ]
    ifFalse: [empty at:cntr put: char].
    cntr := cntr + 1
    ].


texts: Compute a value (and update a CSV record), based on prior value

texts:
The F# code below embodies the two specific questions I have.  It is part of a working transformation utility, the entirety of which, including sample data, is in this gist:
http://bit.ly/2i3kUwF.

Generically, the task is: given a file of discrete records, compute a value for a subsequent record that depends on a value of the previous record. Since I want a transformed stream and not just a computed summary value, this seems a perfect use of Seq.scan.  Here is the relevant portion of main:

File.ReadLines(inFile)
    |> Seq.map appendEmptyColumnForBarValue  // add the col to hold the new barValue
    |> Seq.scan updateBarValue ("", target)  // compute the barValue, based on prev state and target
    |> Seq.skip 1                            // exclude initial blank state above from output
    |> Seq.iter outFile.WriteLine

But I have some questions concerning proper usage of Seq.scan.

Since, by definition, there is no initial state prior to reading the first record, and because I want to return an entire record to the stream, I initialize state to an empty string (ignore the "target" for a bit - that is question 2).  This creates the need to distinguish between this special case of the of the state being the empty string that first time through, vs all other invocations:

let updateBarValue (state:string, target:int32) (line:string) =
    // This is the "folder" function to maintain state for the scan function in main.
    // Since the first time through there will be no accumulated state, the inital state is set to "".
    // The match below handles the decision for first time through, or all other cases.
    //
    // From doc, usage for Seq.scan:
    // Seq.scan folder state source
    //
    // Because scan accepts a single parameter for state AND we need the target passed from the command line
    // invocation, we bundle state and target into a tuple.
    // However, target remains unchanged, while the true state is continually updated
    match state with
    | "" -> buildLineWithBarValue  (line, target) line  // first time through we pass line instead of accumulated state
    | _  -> buildLineWithBarValue (state, target) line

And this use of the empty string, forces the

    |> Seq.skip 1                            // exclude initial blank state above from output

in the main routine above to prevent a blank line from being output.

So, question #1: Am I using Seq.scan correctly? Is there a different/better way to accomplish the goal, that would not force the inclusion of the "Seq.skip 1", which seems less-than-tidy? This would be an easy-to-forget item in this pattern.

Secondly, let's deal with that "target" value.  As you can see from the comment above, I'm cheating a bit by adding it to the state for Seq.scan because it is necessary for the computation and I saw no other way to pass it to my Seq.scan's folder function, updateBarValue.

So, question #2: it seems to me that passing target in as part of the state, when it is clearly not, is a code smell of some sort.  How might this be achieved without my cheat?

The code works, but I'm not happy with it as is; looking for ideas for improvements (in the gist there are a couple of clear TODOs- not talking about those). And, of course, if there is something stupid/crazy that I have not asked about or flagged with a TODO, don't be shy.


texts: Timeline request function for Twitter bot

texts:
I'm writing a Twitter™ bot for the Retrocomputing Stack Exchange site using JavaScript. To ensure that it doesn't tweet about the same question twice in a row, I request the account's timeline. My code should work, but I have a feeling that there's something "wrong" with the way I've written it.

The get_request function is a wrapper for XMLHttpRequest that returns a Promise object. It takes one url parameter, and an optional responsetype parameter that is currently unused by get_twitter_timeline_fragments. The get_twitter_timeline_fragments function is initially called with only the userid and count parameters, as maxid and fragments are used internally. The function doesn't call itself recursively because of the behaviour of Promise.

Here is the get_twitter_timeline_fragments function:

function get_twitter_timeline_fragments(userid, count, maxid, fragments) {
    if (fragments === undefined) {
        fragments = [];
    }
    return get_request(
        "https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=" + userid +
        "&count=" + ((count > 200) ? 200 : count) +
        ((maxid === undefined) ? "" : ("&max_id=" + maxid))
    ).then(function(response) {
        qobj = JSON.parse(response.responseText);
        fragments.concat(qobj);
        if (qobj.length >= count) {
            return fragments;
        } else {
            return get_twitter_timeline_fragments(userid, count - qobj.length, qobj[qobj.length - 1].id_str, fragments);
        }
    });
}

To use the result of the function would require get_twitter_timeline_fragments(userid, count).then(f) where f=x=>isPromise(x)?x.then(f):x; that doesn't seem like a big problem because I'm going to wrap this function in one that processes the data.

The full code is located here. To run the code on the test page you must "Allow All" on your ad-blocker, use a "Same Origin" spoofer (e.g. CORS everywhere) and pre-authenticate to the Twitter API with an API key (so the Twitter side works).


texts:
I've been reading up on OOP concepts such as: polymorphism, inheritance and encapsulation and would like to know if I am even close to using these concepts correctly.

interface Canine
{
    public function bark();
    public function howl();
}

interface Feline
{
    public function chase();
}

interface Mammal
{
    const GENDER_MALE = 'male';
    const GENDER_FEMALE = 'female';

    public function isMale();
    public function isFemale();
}

abstract class Animal
{
    public function breath()
    {
        return 'I breath oxygen found in the air using my nose.';
    }
}

class Dog extends Animal implements Canine, Mammal
{
    private $name;
    private $gender;

    public function __construct($name, $gender)
    {
        $this->setName($name);
        $this->setGender($gender);
    }

    private function setName($name)
    {
        $this->name = (string) $name;
    }

    private function setGender($gender)
    {
        if ($gender === self::GENDER_MALE || $gender === self::GENDER_FEMALE) {
            $this->gender = $gender;
        } else {
            throw new InvalidArgumentException('Mammals can only be male or female');
        }
    }

    public function getGender()
    {
        return $this->gender();
    }

    public function eat()
    {
        return 'I eat meat.';
    }

    public function bark()
    {
        return 'Woof, woof!';
    }

    public function howl()
    {
        return 'AHROOOOOOO WOO WOOO!';
    }

    public function isMale()
    {
        return $this->gender === self::GENDER_MALE;
    }

    public function isFemale()
    {
        return $this->gender === self::GENDER_FEMALE;
    }
}

class Lion extends Animal implements Mammal, Feline
{
    private $gender = self::GENDER_MALE;

    public function chase()
    {
        return 'I am chasing a Gazelle!';
    }

    public function isMale()
    {
        return $this->gender === self::GENDER_MALE;
    }

    public function isFemale()
    {
        return $this->gender === self::GENDER_FEMALE;
    }

    public function eat()
    {
        return 'I am now eating the gazelle I just caught.';
    }
}

class Fish extends Animal
{
    final public function breath()
    {
        return 'I breath oxygen found in the water using my gills.';
    }
}

class Client
{
    public function __construct()
    {
        $dog = new Dog('Sparky', Mammal::GENDER_MALE);
        $cat = new Lion;
        $fish = new Fish;

        $this->setupFeline($cat);
        $this->setupCanine($dog);

        $this->setupAnimal($cat);
        $this->setupAnimal($dog);
        $this->setupAnimal($fish);
    }

    public function setupFeline(Feline $cat)
    {
        echo 'Feline: ' . $this->iAmA($cat), ' and ',$cat->chase(), '&nbsp;', $cat->eat() . '
';
    }

    public function setupCanine(Canine $dog)
    {
        echo 'Canine: ' . $this->iAmA($dog), '&nbsp;', $dog->howl() . '
';
    }

    public function setupAnimal(Animal $animal)
    {
        echo $this->iAmA($animal) . ' and ' . $animal->breath() . '
';
    }

    private function iAmA(Animal $animal)
    {
        return 'I am a ' . get_class($animal);
    }
}

$client = new Client;


texts: Building a chain of responsibility in Ruby to apply transformators on an object

texts:
I try to make a middleware stack system in the rack way (but not for HTTP request).

Here is the main class:

class MiddlewareStack

  def self.stack middleware
    @middlewares ||= []
    @middlewares << middleware
  end

  def self.middlewares
    @middlewares
  end

  def self.next payload
    next_middleware = @middlewares.shift
    next_middleware.apply(payload, self)
  end

  def self.apply payload
    self.next payload
  end

end

Usage

We can setup a middleware stack this way:

class PlusOneMiddleware
  def self.apply payload, stack
    stack.next(payload) + 1
  end
end

class DummyMiddleware
  def self.apply payload, stack
    return payload
  end
end

class PlusOneStack < MiddlewareStack
  stack ::PlusOneMiddleware
  stack ::DummyMiddleware
end

Now we can call the stack like this:

PlusOneStack.apply(1) #return 2

This use case is pretty useless, but I plan to use it for filtering and caching purposes.

Questions

What do you think about the naming/the code?
Do have a better implementation in mind?
What do you think about the test suite? (above)

Test suite

describe MiddlewareStack do

  context "when we stack middlewares" do
    it "contains all the middlewares in the right order" do
      expect(DummyMiddlewareStack.middlewares).to eq [PlusOneMiddleware, DummyMiddleware]
    end
  end

  context "when we apply the middleware stack" do
    it "call all the middlewares" do
      expect(PlusOneMiddleware).to receive(:apply).ordered.and_call_original
      expect(DummyMiddleware).to receive(:apply).ordered.and_call_original
      PlusOneStack.apply(1)
    end
  end

end


texts:
This is "my" version of a basic C++ calculator, that requires a single line input (like 1+1) to calculate the result. I have been (self)learning the language for 2 months now. I don't pretend to have invented this code, but I haven't taken the time to search for this variation.

The functions included are:

Addition: 1 + 1 = 2

Input in program: 1+1
Subtraction: 1 - 1 = 0

Input in program: 1-1
Multiplication: 1 * 1 = 1

Input in program: 1*1
Division: 1 / 1 = 1

Input in program: 1/1
Exponentiation: 2 ^ 2 = 4

Input in program: 2^2

#include <iostream>
#include <string>

using namespace std;

class Math_Functions
{
private:
    double result;

public:
    double addition(double, double);
    double subtraction(double, double);
    double multiplication(double, double);
    double division(double, double);
    double exponentiation(double, double);
} math;

double Math_Functions::addition(double a, double b)
{
    result = a + b;
    return result;
}

double Math_Functions::subtraction(double a, double b)
{
    result = a - b;
    return result;
}

double Math_Functions::multiplication(double a, double b)
{
    result = a * b;
    return result;
}

double Math_Functions::division(double a, double b)
{
    result = a / b;
    return result;
}

double Math_Functions::exponentiation(double a, double b)
{
    result = 1;
    for (int i = 0; i < b; i++)
    {
        result *= a;
    }
    return result;
}

int main()
{
    double a, b;
    string function;
    bool loop = 1;

    while(loop)
    {
        system("CLS");
        cin >> a;
        function = getchar();
        cin >> b;

        switch(function[0])
        {
            case '+' : cout << math.addition(a, b); break;
            case '-': cout << math.subtraction(a, b); break;
            case '*': cout << math.multiplication(a, b); break;
            case '/': cout << math.division(a, b); break;
            case '^': cout << math.exponentiation(a, b); break;
        }
        cout << endl << "Press Any Key to Continue . . . ";
        cin.sync();
        cin.ignore();
    }
    return 0;
}


texts: Selecting minimal sum of two distinct entries of two dicts with common keys

texts:
Can this function simplified?
The goal is return one key from each dictionary (both contain the identical keys), so that the sum of the values that belong to the selected keys are minimal (and also the two keys cannot be identical).

a = {1:50, 2:60, 3:30}
b = {1:50, 2:70, 3:40}
def get_double_min(a, b):
        a_sorted = sorted(a, key=a.get)
        a1, a2 = a_sorted[0], a_sorted[1]
        b_sorted = sorted(b, key=b.get)
        b1, b2 = b_sorted[0], b_sorted[1]
        if a1 != b1:
            return a1, b1
        if a1 == b1:
            sum1 = a[a1] + b[b2]
            sum2 = a[a2] + b[b1]
            if sum1 < sum2:
                return a1, b2
            else:
                return a2, b1
        else:
            raise ValueError("error incorrect value")
print get_double_min(a, b)