texts:
You have to find a path through which the rat move from the starting
  position (0,0) to the final position where cheese is (n,n). List the
  total no of possible paths which the rat can take to reach the cheese.

Sample Input:

7

0 0 1 0 0 1 0

1 0 1 1 0 0 0

0 0 0 0 1 0 1

1 0 1 0 0 0 0

1 0 1 1 0 1 0

1 0 0 0 0 1 0

1 1 1 1 0 0 0

Sample Output:

4

My code:

import java.util.*;

class maze

{

    static int n;
    static int[][] a;
    static int path;

    public static void main(String[] ar)
    {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        a = new int[n][n];
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < n; j++)
            {
                a[i][j] = sc.nextInt();
            }
        }
        search(0,0);
        System.out.println(path);
    }

    public static void search(int i, int j)
    {
        if(!exist(i,j) || a[i][j] == 1)
            return;
        if(i == n-1 && j == n-1)
        {
            path++;
            return;
        }
        a[i][j] = 1;
        search(i+1,j);
        search(i-1,j);
        search(i,j+1);
        search(i,j-1);
        a[i][j] = 0;
    }

    public static boolean exist(int i, int j)
    {
        return i>=0 && j >=0 && i < n && j < n;
    }
}

Can anybody recommend a better solution than this or if there are any, please point out the mistakes in this. I made it using simple logic and I don't know much about graph theory.
Is this DFS or BFS?


texts: Simple Javascript Widget without cluttering global namespace?

texts:
I've written some Javascript code with jQuery to display a dialog box on a web page that "floats" in the corder of the page.

(1) It has the following features: the dialog follows as the user scrolls the page.

(2) If the user holds down the [Ctrl] key, the dialog is hidden so that it doesn't obscure content.

I know that I tend to intuitively treat Javascript as if it were C code because it looks like C code and this is a habit I've been working to break.

Also, I'm working to write this code to be reusable and not litter the global namespace with various objects and functions.

I refer to the dialog as the "Little Black Book".

Bearing that in mind, please critique my code:

function getNewLittleBlackBook(blackBookId, blackBookWidth, blackBookHeight) {
    var jQueryBlackBook = $('#' + blackBookId);
    if (jQueryBlackBook.length == 0)
        throw "Could not locate the element specified by blackBookId";
    if (!blackBookWidth > 0 || !blackBookHeight > 0)
        throw "Invalid width or height specified for Little Black Book";

    var LittleBlackBook = {
        id: blackBookId,
        width: blackBookWidth,
        height: blackBookHeight,
        jQueryObj: jQueryBlackBook,

        // Functions to show and hide the little black book
        hide: function () { jQueryBlackBook.hide(); },
        show: function () { jQueryBlackBook.show(); },

        // This setPosition function determines the position based on the document scrolling.
        setPosition: function () {
            var windowHeight = $(self).height();
            var windowWidth = $(self).width();
            var scrollPosition = $(self).scrollTop();
            var newModalTop = windowHeight - this.height + scrollPosition - 40;
            var newModalLeft = windowWidth - this.width - 40;
            this.jQueryObj.css('top', newModalTop + 'px');
            this.jQueryObj.css('left', newModalLeft + 'px');
            this.jQueryObj.css('height', this.height);
            this.jQueryObj.css('width', this.width);
        }, // end setPosition

        handlers: {
            ExternalScroll: function () {
                LittleBlackBook.setPosition();
            },
            // These next two handlers serve to show/hide the Little Black Book when the user holds down the [Ctrl] key.
            ExternalKeyDown: function (e) {
                if (e.keyCode == 17)
                    LittleBlackBook.hide();
            },
            ExternalKeyUp: function (e) {
                if (e.keyCode == 17)
                    LittleBlackBook.show();
            }
        } // end handlers
    };     // end LittleBlackBook object

    // Attach event handlers.
    $(self).scroll(LittleBlackBook.handlers.ExternalScroll);
    $(document).keydown(LittleBlackBook.handlers.ExternalKeyDown);
    $(document).keyup(LittleBlackBook.handlers.ExternalKeyUp);

    LittleBlackBook.setPosition();
    LittleBlackBook.show();

    // Return the object
    return LittleBlackBook;
}


texts: Python: Combining Two Rows with Pandas read_excel

texts:
I am reading an Excel file using Pandas and I feel like there has to be a better way to handle the way I create column names.  This is something like the Excel file I'm reading:

                1       2      # '1' is merged in the two cells above 'a'and 'b'
    Date        a   b   c   d  #  likewise for '2'.  As opposed to 'centered across selection'
1   1-Jan-19    100 200 300 400
2   1-Feb-19    101 201 301 401
3   1-Mar-19    102 202 302 402

I want my to merge the 'a','b','c',and'd' columns heads with the '1'and '2' above them, so I'm doing the following to get my headers the way that I want:

import pandas as pd
import json

xls = pd.ExcelFile(r'C:\Path_to\Excel_Pandas_Connector_Test.xls')
df = pd.read_excel(xls, 'Sheet1', header=[1])  # uses the abcd row as column names

#  I only want the most recent day of data so I do the following
json_str = df[df.Date == df['Date'].max()].to_json(orient='records',date_format='iso')

dat_data = json.loads(json_str)[0]

def clean_json():
    global dat_data
    dat_data['1a']      = dat_data.pop('a')
    dat_data['1b']      = dat_data.pop('b')
    dat_data['2c']      = dat_data.pop('c')
    dat_data['2d']      = dat_data.pop('d')

clean_json()

print(json.dumps(dat_data,indent=4))

My desired output is:

{
"Date": "2019-03-01T00:00:00.000Z",
"1a": 102,
"1b": 202,
"2c": 302,
"2d": 402
}

This works as written, but is there a Pandas built-in that I could have used to do the same thing instead of the clean_json function?


texts:
I'm new to Core Animations, I want to fade out two different layers one after another.I write them in a CATransaction block. I wonder if there is better approach to make such animations.

[CATransaction begin];

    CABasicAnimation *fadeOutLoadingBar = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeOutLoadingBar.fromValue = [NSNumber numberWithFloat:0.3];
    fadeOutLoadingBar.toValue = [NSNumber numberWithFloat:0.];
    fadeOutLoadingBar.fillMode = kCAFillModeForwards;
    fadeOutLoadingBar.beginTime = [_loadingLayer convertTime:CACurrentMediaTime() fromLayer:nil];
    fadeOutLoadingBar.duration = .8;
    fadeOutLoadingBar.removedOnCompletion = NO;
    [_loadingLayer addAnimation:fadeOutLoadingBar forKey:nil];

    [self setupCheckMarkLayer]; //initialize _checkMarkLayer
    CABasicAnimation *fadeOutCheckMark = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeOutCheckMark.fromValue = [NSNumber numberWithFloat:0.3];
    fadeOutCheckMark.toValue = [NSNumber numberWithFloat:0.];
    fadeOutCheckMark.fillMode = kCAFillModeForwards;
    fadeOutCheckMark.beginTime = [_checkMarkLayer convertTime:CACurrentMediaTime() fromLayer:nil] + 0.5;
    fadeOutCheckMark.duration = 1.0;
    fadeOutCheckMark.removedOnCompletion = NO;
    _checkMarkLayer.opacity = 0.;
    [_checkMarkLayer addAnimation:fadeOutCheckMark forKey:nil];

    [CATransaction setCompletionBlock:^{
        self.userInteractionEnabled = YES;
        [self.delegate finishedLoading];
        [self setupLoadingLayer];
    }];

    [CATransaction commit];


texts:
I'm refactoring some "old" Swift code using deprecated UIAlertView and delegates.

I have a UIAlertController with an input textfield inside (and two buttons, OK and CANCEL). The user should insert his email address, then I should validate it anytime he enters a character: when the mail address is valid, the UIAlertController button is enabled, else is disabled.

I got this code perfectly working but for some reason I'm not very happy with this solution. Is there something you would change?

var alertTextField: UITextField!

func textFieldDidChange(){

    if let e = alertTextField.text {
        let alertButton = alertController.actions[0]
        alertButton.isEnabled = !Utils.isValidEmail(testStr: e) ? false : true
    }
}

var alertController = UIAlertController(title: "Insert your email", message: "message", preferredStyle: .alert)

@IBAction func passwordForgot(_ sender: Any) {

    let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
        print("Ok Button was Pressed")
    })
    ok.isEnabled = false

    let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
        print("Cancel Button was Pressed")
    }

    alertController.addAction(ok)
    alertController.addAction(cancel)

    alertController.addTextField { (textField) -> Void in
        self.alertTextField = textField
        self.alertTextField?.placeholder = "mail"
        textField.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControlEvents.editingChanged)
    }

    self.present(alertController, animated: true, completion: nil)

}


texts:
I was reading a Java book and I came up with this kind of problem and I tried to solve it:

  Problem: Write an application that inputs one number consisting of five digits from the user, separates the number into its individual
  digits and prints the digits separated from one another by three
  spaces each. For example,

  Input:

42339

  Output:

4   2   3   3   9

Solution:

package practice;

import java.io.IOException;
import static java.lang.System.in;
import java.util.InputMismatchException;
import java.util.Scanner;

public class practice {

    public static void main(String[] args) throws IOException {
        try(Scanner input = new Scanner(System.in)){

            System.out.print("");
                int a = input.nextInt();

            char[] newString = Integer.toString(a).trim().toCharArray();

            if (newString.length < 5 || newString.length > 5) {

                System.out.println("Input should be exactly 5.");
                return;

            } else {

                for (int i = 0; i < newString.length; i++) {
                    System.out.print(newString[i] + "   ");
                }
            }

            System.out.println();

         } catch (InputMismatchException e){

             System.out.println("Error: Invalid input.");

        } finally {

            in.close();

        }
    }
}

My questions are:

Did I do something wrong?
Is there any way to solve this problem more efficiently?


texts: Implement a fold-like Function in Haskell

texts:
Let's say I need to write a function that applies a function to each item in a List, and then appends it to an accumulator. When the List is empty, return the accumulator.

go :: [a] -> (a -> [b]) -> [b] -> [b]
go [] f acc = acc
go (x:xs) f acc = go xs f (acc ++ f x)

myFold :: [a] -> (a -> [b]) -> [b]
myFold as f = go as f []

I used the go function so that I wouldn't force the myFold caller to have to provide an empty [b] type. Also, I used the go function to achieve tail recursion.

In Scala, I would've put @annotation.tailrec to make the compilation fail if the compiler could not perform tail-call optimization.

Is the above code idiomatic in Haskell?


texts:
I noticed that the C++ version of <complex> has norm.

However, I am programming in C, and there is no cnorm.  So I made one to define before my main function:

#include <complex.h>

double cnorm(double _Complex z)
{
    return cpow(creal(z),2) + cpow(cimag(z),2);
}

How would you improve this definition? Is the name ok?  or will it break when it is eventually added to <complex.h>.  Is the return type appropriate?  Would it be more consistent to use double _Complex?  And is the implementation efficient (for rapid numerical evaluation)?


texts: Insertion sort implementation adapted from the web

texts:
I've found this implementation on the web:

void insertSort(int a[], int length)
{
    int i, j, value;
    int k=0;
    for(i = 1; i < length; i++)
    {
      value = a[i];
        for (j = i - 1; j >= 0 && a[j] > value; j--)
      {
            a[j + 1] = a[j];
            k++;
        }
        a[j+1] = value;
    }

    printf("k=%d", k);
}

I have written this:

#include <stdio.h>

#define SIZE 8

int array1[SIZE] = {77, 33, 44, 11, 88, 22, 66, 55};

void PrintArray()
{
    int i = 0;
    printf("\n");
    for(i=0 ; i<SIZE ; i++)
    {
        printf("%d, ", array1[i]);
    }
}

void Insert(int insertPosition, int insertElementIndex)
{
    int temp = array1[insertElementIndex];
    int i = 0;

    for(i=insertElementIndex ; i>=insertPosition ; i--)
    {
        array1[i] = array1[i-1];
    }

    array1[insertPosition] = temp;
}

void InsertionSort()
{
    int i = 0;
    int j = 0;
    int k = 0;

    for(i=0 ; i<SIZE ; i++)
    {
        for(j=0 ; j<=i ; j++)
        {
            if(array1[i] < array1[j])
            {
                Insert(j, i);
                PrintArray();
            }

            k++;
        }
    }
    printf("k=%d", k);
}

main()
{
    PrintArray();

    InsertionSort();
    //insertSort(array1, SIZE);

    PrintArray();

    getch();
}

Is there any problem with this implementation?


texts: Is there a better way to combine these arrays?

texts:
Is there a better way to do this kind of array combination with a PHP native function like array_combine?  I'm trying to improve my skills, and at certain points I note that I am using too many nested foreach for almost everything.

Using PHP 5.4

   $array = Array(
      'GroupName' => 'Emilio',
      'Moduleid' => Array(
          0 => 15,
          1 => 12,
          2 => 9,
          3 => 1,
          4 => 11,
          5 => 10
      ),
      'Permission' => Array(
          15 => 'W',
          12 => 'R',
          14 => 'W',
          9 => 'W',
          1 => 'R',
          13 => 'W',
          11 => 'W',
          10 => 'R'
      )
  );

  foreach ($array['Moduleid'] as $value) {
    foreach ($array['Permission'] as $key1 => $value1) {
      if ($value == $key1) {
        $result[$key1] = $value1;
      }
    }
  }
  $newArray = array(
      'GroupName' => $array['GroupName'],
      'ModulePermission' => $result
  );
  unset($array);

  echo '<pre>';
  print_r($newArray);
  echo '</pre>';

Output

Array
(
    [GroupName] => Emilio
    [ModulePermission] => Array
        (
            [15] => W
            [12] => R
            [9] => W
            [1] => R
            [11] => W
            [10] => R
        )

)


texts: React: Simple Event Emitter on form example

texts:
I decided to study EventEmitter and play around with it in React JS for on example of a simple form.
I built EventEmitter and added event 'newdata' to it. On event 'newdata' is called function where the data for form's rendering changes. Then event 'newdata' is emitted with the new data.
I repeated emitting of event using setTimeout to better understand how this works.

I will be happy for the tip on improving the code.

class EventEmitter {
  constructor() {
    this.events = {}
  }

  on(eventName, fn) {
    if(!this.events[eventName]) {
      this.events[eventName] = []
    }

    this.events[eventName].push(fn)
    return () => {
      this.events[eventName] = this.events[eventName].filter(eventFn => fn !== eventFn)
    }
  }

  emit(eventName, data) {
    const event = this.events[eventName]
    if (event) {
      event.forEach(fn => {
        fn.call(null, data)
      })
    }
  }
}

let emitter = new EventEmitter()

class App extends React.Component {
  constructor(props){
    super(props)

    this.state = {
      firstName: '',
      isValid: false,
    }
  }

  handleSubmit(e) {
    e.preventDefault()

    let firstName, isValid

    emitter.on('newdata', function(data) {
      firstName = data['firstName']
      isValid = data['isValid']
    })

    emitter.emit('newdata', {
      firstName: 'Kitty',
      isValid: true,
    })

    this.setState({firstName, isValid})

    if (isValid) {
      console.log('success')
    } else {
      console.log('error')
    }

    setTimeout(() => {

      emitter.emit('newdata', {
        firstName: 'Joni',
        isValid: false,
      })

      this.setState({firstName, isValid})

      if (isValid) {
        console.log('success')
      } else {
        console.log('error')
      }

    }, 1000);
  }

  handleValidation(e) {
    this.setState({
      firstName: e.target.firstName
    })
  }

  render() {
    return (
      <form>

          Name:

        <input
          type='text'
          name ='firstName'
          value = {this.state.firstName}
          onChange = {this.handleValidation.bind(this)}
        />
        <button onClick = {this.handleSubmit.bind(this)}>
          Submit
        </button>
      </form>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)


texts:
I use MultiMarkdown tables more than I thought I ever would. In my .md files, I would like the source table code to be neat, evenly spaced, and resemble (in an alignment sense) the final HTML rendered table.

Solution

Select the source of the table, press a hotkey on my computer, replace the untidy table with the tidy table.

Notes:

This script (macro?) is for my own use; I will always write the source table the same way
The script is written for Python 2.7
I use a Mac app that allows me to assign a hot key to an action (e.g. a script), and the following seems to work with that at the moment!

Example

I write something like the following:

| Header 1 | Header 2 | ... | Header m |
| :--- | :--: | :--: | --: |
| $a_{11}$ | $a_{12}$ | ... | $a_{1m}$ |
| ... | ... | ... | ... |
| $a_{n1}$ | $a_{n2}$ | ... | $a_{nm} |

select it, press my hot key, and it is replaced by something like this (in the source):

| Header 1 | Header 2 | ...  | Header m |
| :---     |   :--:   | :--: |      --: |
| $a_{11}$ | $a_{12}$ | ...  | $a_{1m}$ |
| ...      |   ...    | ...  |      ... |
| $a_{n1}$ | $a_{n2}$ | ...  | $a_{nm}$ |

As mentioned, the script seems to work.

How can I improve the script?

I would really appreciate some criticism of the script I've written. I am not a coder, but try on occasion to write little tool type things like this.

The Script

#!/usr/bin/env python

"""MMD Table Formatter.

Silly script that takes a MMD table as a
string and returns a tidied version of the table
"""

import sys
import StringIO

query = sys.argv[1]

# For "cleaned" table entries:
rows = []

# This NEEDS TO BE CLOSED AFTER!!
s_obj = StringIO.StringIO(query)
# Clean the entries:
for line in s_obj:
    l = line.split('|')
    rows.append([entry.strip() for entry in l])`enter code here`
# CLOSE
s_obj.close()

# Max length of each "entry" is what we'll use
# to evenly space "columns" in the final table
cols = zip(*rows)
col_widths = []
for columns in cols:
    row_widths = map(lambda x: len(x), columns)
    col_widths.append(max(row_widths))

# Let's align entries as per intended formatting.
# Second line of input string contains alignment commmands:
# ":---"    left aligned
# "---:"    right aligned
# ":--:"    centered (also accepts "---")
alignment = []
for r in rows[1]:
    if r.startswith(":") and not r.endswith(":"):
        alignment.append("lalign")
    elif r.endswith(":") and not r.startswith(":"):
        alignment.append("ralign")
    else:
        alignment.append("centered")

# Prepare for output string:
out = []
for row in rows:
    for entry_and_width in zip(row, col_widths, alignment):
        if entry_and_width[1] == 0:
            continue
        if entry_and_width[2] == "centered":
            outstring = "| " + entry_and_width[0].center(entry_and_width[1]) + ' '
            out.append(outstring)
        if entry_and_width[2] == "lalign":
            outstring = "| " + entry_and_width[0].ljust(entry_and_width[1]) + ' '
            out.append(outstring)
        if entry_and_width[2] == "ralign":
            outstring = "| " + entry_and_width[0].rjust(entry_and_width[1]) + ' '
            out.append(outstring)
    out.append("|\n")

query = "".join(out)

sys.stdout.write(query)


texts: Controlling permissions in a MVP application

texts:
In a Windows forms payroll application employing MVP pattern (for a small scale client) I'm planing user permission handling as follows (permission based) as basically its implementation should be less complicated and straightforward.

NOTE: System could be simultaneously used by few users (maximum 3) and the database is at the server side.

This is my UserModel. Each user has a list of permissions given for them.

class User
{
    string UserID { get; set; }
    string Name { get; set; }
    string NIC {get;set;}
    string Designation { get; set; }
    string PassWord { get; set; }
    List <string> PermissionList = new List<string>();
    bool status { get; set; }
    DateTime EnteredDate { get; set; }
}

When user login to the system it will keep the current user in memory.

For example in BankAccountDetailEntering view, I can control the permission to access a command button as follows.

 public partial class BankAccountDetailEntering : Form
    {
        bool AccountEditable {get; set;}

        public BankAccountDetailEntering ()
        {
            InitializeComponent();
        }

        private void BankAccountDetailEntering_Load(object sender, EventArgs e)
        {
            cmdEditAccount.enabled = false;

            OnLoadForm (sender, e); // Event fires...

            If (AccountEditable )
            {
                cmdEditAccount.enabled=true;
            }
         }
    }

In this purpose all relevant presenters (like BankAccountDetailPresenter) should aware of UserModel as well in addition to the corresponding business Model it is presenting to the View.

class BankAccountDetailPresenter
{
    BankAccountDetailEntering _View;
    BankAccount _Model;
    User _UserModel;
    DataService _DataService;

    BankAccountDetailPresenter( BankAccountDetailEntering view, BankAccount model, User userModel, DataService dataService )
    {
        _View=view;
        _Model = model;
        _UserModel = userModel;
        _DataService = dataService;
        WireUpEvents();
    }

    private void WireUpEvents()
    {
        _View.OnLoadForm += new EventHandler(_View_OnLoadForm);
    }

    private void _View_OnLoadForm(Object sender, EventArgs e)
    {

        foreach(string s in _UserModel.PermissionList)
        {
            If( s =="CanEditAccount")
            {
                _View.AccountEditable =true;
                return;
            }
        }
    }

    public Show()
    {
        _View.ShowDialog();
    }
}

So I'm handling the user permissions in the presenter iterating through the list. Should this be performed in the Presenter or View? Any other more promising ways to do this?  I'd appreciate it if you could review the code and provide your feedback.


texts:
I want to create a function that takes a string and returns an array of versions of it in which always one pair of characters is transposed (swapped).

I came up with this:

fn transposes(s: &str) -> Vec<String> {
    let mut vec = vec![];

    let b = s.as_bytes();

    for i in 1..b.len() {
        let mut transpose = String::with_capacity(s.len());
        transpose.push_str(&s[..i - 1]);
        transpose.push(s.as_bytes()[i] as char);
        transpose.push(s.as_bytes()[i - 1] as char);
        transpose.push_str(&s[i + 1..]);

        vec.push(transpose);
    }

    vec
}

fn main() {
    let s = "maxi".to_owned();
    println!("{:?}", transposes(&s));
}

Output is:

["amxi", "mxai", "maix"]

That result is what I want, it does:

First swap m and a
Then swap a and x
Then swap i and x

I don't find the code super readable because of the string slicing going on. In C it would be a mere "pointer swap", but my Rust version looks a bit more involved.

Is there a better way to do what I want?

It is a fair assumption that this will only work correctly for ASCII strings.


texts:
I was wondering if anyone could provide some feedback on my solution to Conway's game of life. I tried to solve it without using objects. It returns a dictionary of living points on a grid and points that were alive at some point. I'm wondering if there is a better way to check the surrounding points or if storing the active points in a dictionary is a bad idea.

def list_to_check(x,y):
    return  [(x + 1, y),
             (x - 1, y),
             (x +1, y +1 ),
             (x -1, y -1 ),
             (x +1, y -1 ),
             (x -1, y +1 ),
             (x, y+1),
             (x, y-1)]

def neighbors_count(x,y,cells):
    count = 0
    for item in list_to_check(x,y):
       if item in cells:
           count += cells[item]
    return count

def next_state(cells):
    next_state = {}
    for point in cells.keys():
        alive = cells[point] == 1
        neighbors = neighbors_count(point[0],point[1],cells)
        if not alive and neighbors == 3:
            next_state[point] = 1
        elif neighbors > 3 or neighbors < 2:
            next_state[point] = 0
    return next_state

def add_to_grid_alive(cells):
    to_check = []
    to_add = {}
    for item in cells.keys():
        checking = [ x for x in list_to_check(item[0],item[1]) if x not in to_check and x not in cells ]
        to_check += checking

    for item in to_check:
        if neighbors_count(item[0],item[1],cells) == 3:
            to_add[(item[0],item[1])] = 1
    return to_add

def tick(cells):
    changes = next_state(cells)
    expansions = add_to_grid_alive(cells)
    cells.update(changes)
    cells.update(expansions)
    [ cells.pop(point,None) for point in cells.keys() if cells[point] == 0 ]

def print_grid( size, cells):
    grid = []
    for y in range(size):
        grid.append([])
        for x in range(size):
            grid[y].append(0)
    for point in cells.keys():
        if  0 <= point[0] < size and 0 <= point[1] < size:
            grid[point[1]][point[0]] = cells[point]
    return grid

#testing

def load_list(inputs):
    point_dict = {}
    for point in inputs:
        point_dict[point] = 1
    return point_dict

inputs = [(1,2),(2,2),(3,2),(2,3),(3,3),(4,3),(13,2),(13,3),(12,3),(13,4)]

test_array_dict = load_list(inputs)

for x in range(20):

    print '>>>>>>>>>>>>>>>>>>>>', x + 1

    for item in print_grid(20,test_array_dict)[::-1]:
        print item
    tick(test_array_dict)

Update

I added [ cells.pop(point,None) for point in cells.keys() if cells[point] == 0 ] to the tick function and it really sped up the the code on higher iterations


texts:
I have a very simple code that allows me to keep track of what the user inserts in a raw_input.

The kind of controls I check are if the user inserts "f" the program is finished or if the user inserts nothing, the program keeps on running remembering all the inputs the user has inserted.

It works but I think it's very ugly and rudimental.

I would love to get suggestions from experts so I can learn how to handle correctly simple tasks.

Here's the little code:

#!/usr/bin/python
import os
good_receipts = []
done = False
inserted_text = ''
while not done:
    # This function is os dependent and will work only if you use linux
    os.system('clear')
    inserted_text = raw_input("Insert receipt number (if you finished insert 'f'): ").upper()
    if inserted_text and inserted_text != 'F':
        good_receipts.append(inserted_text)
    while not inserted_text == 'F':
        # This function is os dependent and will work only if you use linux
        os.system('clear')
        if good_receipts:
            print "Here's your receipts:"
            print good_receipts
        if not good_receipts:
            print "You didn't enter a single receipt..."
        inserted_text = raw_input("Insert receipt number (if you finished insert 'f'): ").upper()
        if inserted_text and inserted_text != 'F':
            good_receipts.append(inserted_text)
    done = True
# This function is os dependent and will work only if you use linux
os.system('clear')
print "You did a great job, here's your receipts:"
print good_receipts


texts: All possible values that will match a regular expression

texts:
This is a similar question to this, but I am looking for the set of all possible values that will match a regular expression pattern.

To avoid an infinite set of possible values, I am willing to restrict the regular expression pattern to a subset of the regular expression language.

Here's the approach I took (Python code):

def generate_possible_strings(pattern):
    '''
    input: 'K0[2468]'
    output: ['K02', 'K04', 'K06', 'K08']

    generates a list of possible strings that would match pattern
    ie, any value X such that re.search(pattern, X) is a match
    '''
    query = re.compile(pattern, re.IGNORECASE)
    fill_in = string.uppercase + string.digits + '_'

    # Build a re for a language subset that is supported by reverse_search
    bracket = r'\[[^\]]*\]' #finds [A-Z], [0-5], [02468]
    symbol = r'\\.' #finds \w, \d
    expression = '|'.join((bracket,symbol)) #search query

    tokens = re.split(expression, pattern)
    for c in product(fill_in, repeat=len(tokens)-1):
        candidate = ''.join(roundrobin(tokens, c)) #roundrobin recipe from itertools documentation
        if query.match(candidate):
            yield candidate

Supported subset of regular expressions language

Supports [] set of characters ([A-Z], [0-5], etc)
Supports escaped special characters (\w, \d, \D, etc)

Basically what this does is locate all parts of a regular expression that could match a single character ([A-Z] or [0-5] or [02468] or \w or \d), then for all of the valid replacement characters A-Z0-9_ test to see if the replacement matches the regular expression.

This algorithm is slow for regular expressions with many fields or if fill_in is not restricted to just A-Z0-9_, but at least it guarantees finding every possible string that will match a regular expression in finite time (if the solution set is finite).

Is there a faster approach to solving this problem, or an approach that supports a larger percentage of the standard regular expression language?


texts: Efficient Traversal and Manipulation of the DOM with Native JavaScript Using For/In Loop

texts:
With native JavaScript, I intend to traverse a collection of elements in the DOM that contain a link and an image (and possibly other elements). The image may or may not be inside the link—in most cases the image will be in the link, but in some cases it may be directly adjacent to the link, or it may be a child of another div or span that is adjacent to its relevant link. However, both the link and the image will always be contained within a container element, of which there may be several.

For example, envision a stock photo gallery arranged in a grid layout. The HTML for each item in the gallery's collection may look like any one of the snippets below (simplified for cleanliness and brevity).

It might be:

Or it may be:

  Image Title

Or it may be:

    Image Title

Note: I can't control the given HTML. Nevertheless, I would like to traverse and manipulate the DOM flexibly enough to handle any instance of HTML structure given above. To do so efficiently, I'd first need to build the collection of container elements before traversing, yes?

So this:

var items = document.querySelectorAll('.item');
for(i in items) { ... }                           // more efficient

rather than this:

for(i in document.querySelectorAll('.item')) { ... } // less efficient

as the latter would need to re-query the .item selector again inside the loop, which is inefficient. Right?

However, to manipulate the link and image of each item being looped, I still need to access the link and image of said item. To do that, I could use querySelector() on the .item like so:

var items = document.querySelectorAll('.item');
for(i in items) {
  var link = items[i].querySelector('a'), img = items[i].querySelector('img');
  // manipulate link and img elements
}

But is triggering querySelector() twice per loop-instance the most efficient approach?

Is there a more efficient approach to access the link and image of each .item element being looped-through than by calling querySelector() twice on each looped .item element?

Consider that the primary intent of manipulation is to change the link URL to the image source URL and add some attributes to the link and/or image. Seems simple enough. I just want to make sure the loop logic is efficient. Ideally, the logic will ultimately be used in either a bookmarklet or a browser plugin. The collection of .item elements could potentially number in the thousands, so I'm hoping to keep this traversal and manipulation process as efficient as possible.


texts: Given some integers, return the k most frequent elements

texts:
Given a non-empty array of integers, return the k most frequent elements.

For example, given [1,1,1,2,2,3] and k = 2, return [1,2].

Following is my submission to this problem on Leetcode and it is accepted. Can you please provide feedback on any issue that you see in this code? I am looking for improvements in the quality of the code from both software engineering perspective as well as from algorithmic complexity or space and run-time performance perspective.

#include <algorithm>
#include <map>
#include <vector>

using namespace std;

class Node
{
public:

    int value{};
    unsigned frequency{};

    Node()
    {

    }

    Node (int value, unsigned frequency)
    {
        this->value = value;
        this->frequency = frequency;
    }

    bool operator< (const Node& other)
    {
        return this->frequency < other.frequency;
    }
};

class Solution {
public:

    vector<int> topKFrequent(vector<int>& nums, int k)
    {
        map<int, unsigned> frequency;

        for (auto n : nums )
        {
            if ( frequency.find(n) != frequency.end())
                frequency[n]++;
            else
                frequency[n] = 0;
        }

        vector<Node> heap;

        for ( auto f : frequency )
            heap.push_back(Node(f.first, f.second));

        make_heap(heap.begin(), heap.end());

        vector<int> result;

        unsigned i = 0;
        while ( i < k )
        {
            result.push_back(heap.front().value);
            pop_heap(heap.begin(), heap.end()-i);
            i++;
        }

        return result;
    }
};


texts: Decimal to binary conversion in ARM assembly

texts:
I'm "playing" with ARM assembly on a Raspberry Pi, reading various tutorials and posts to help - no, it's not a college assignment, I'm too old for college! I'm pleased with getting the following code to take a decimal value (between 0 and 255) and output the binary string equivalent to the screen using scanf() and printf() but curious to know though whether those more experienced would consider this a "naive" solution? Are there any "gotchas"? Any better ways of tackling the problem?
I reckon there should be a better way of declaring the string to hold the output and how the string is built from the LSB (using R9)
/* dectobin2.s                                                  */
/* ------------------------------------------------------------ */
/* Converts a decimal number to binary and outputs to screen    */
/* ============================================================ */

.data
.balign 4
value:      .word   0
binStr:     .asciz  "00000000"
output:     .asciz  "%d in binary is %s\n"
title:      .asciz  "DECIMAL TO BINARY CONVERTER\n\n"
lr_temp:    .word   0
lr_local:   .word   0
prompt:     .asciz  "Enter a positive value (0-255) > "
pattern:    .asciz  "%d"

.text
@ function to convert given value into a binary string
decToBin:
    @ save the link register
    ldr     r2, =lr_local
    str     lr, [r2]
    @ set data values
    mov     r4, r0              @ value in r4 for processing
    mov     r9, #7              @ LSB position in output string
_loop:
    @ repeated division by 2 2
    movs    r4, r4, lsr #1      @ divide by 2, set carry
    bcs     _odd                @ if carry set, remainder is 1
_even:
    mov     r5, #0              @ remainder of 0
    b       _toString
_odd:
    mov     r5, #1              @ remainder of 1
_toString:
    add     r5, #48             @ convert remainder to ASCII
    ldr     r1, =binStr         @ address of binary string
    strb    r5, [r1, r9]        @ store remainder in string at pos in r9
    sub     r9, r9, #1          @ move to next position in output string
    cmp     r4, #0              @ reached zero?
    ble     _endloop
    b       _loop

_endloop:
    @ restore the link register
    ldr     lr, =lr_local
    ldr     lr, [lr]
    bx      lr

.global main

main:
    @ store the link register
    ldr     r1, =lr_temp
    str     lr, [r1]

    @ print a title
    ldr     r0, =title
    bl      printf
_getValue:
    @ get the value to convert
    ldr     r0, =prompt         @ prep the arguments for scanf
    bl      printf
    ldr     r0, =pattern
    ldr     r1, =value
    bl      scanf

    @ check for valid input (0-255)
    ldr     r0, =value
    ldr     r0, [r0]
    cmp     r0, #255            @ must be <= 255
    bgt     _getValue
    cmp     r0, #0              @ must be >= 0
    blt     _getValue

_isValid:
    @ call the function, value is in R0
    bl      decToBin

    @ display output
    ldr     r0, =output         @ get address of output string
    ldr     r1, =value          @ get the original value
    ldr     r1, [r1]            @ for first parameter
    ldr     r2, =binStr         @ get the binary string
    bl      printf              @ print the result

    @ restore the link register and exit
    ldr     lr, =lr_temp
    ldr     lr, [lr]
    bx      lr

.global printf
.global scanf
```


texts: Convert mixed-format phone numbers to pure numbers

texts:
I am just getting started with C# and wanted to make sure that I am aware of any errors/inefficiencies in my code.

For this specific project, I wanted to prove to someone that a "bot" could easily understand phone numbers from Craigslist that are mixed (ex. 9eight7six54three2one0).

Here is what I have right now - it successfully outputs a string of numbers when fed a phone number such as the one above.

using System;

namespace Phone_Decoder
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter your mixed-format phone number:");

            string phone = Console.ReadLine();

            char[] b = new char[phone.Length];

            b = phone.ToCharArray();

            string finalphone = string.Empty;

            string number = string.Empty;

I am wondering if this "number" string should be a character array or not. It seems much easier to append a string than to add characters to an array, but I thought I read that strings are more memory-intensive.

            foreach (char c in b)
            {
                if (char.IsDigit(c))
                    finalphone += c;
                if (!char.IsDigit(c))
                {
                    number += c;
                    switch (number.ToLower())
                    {
                        case "zero":
                            finalphone += '0';
                            number = string.Empty;
                            break;
                        case "one":
                            finalphone += '1';
                            number = string.Empty;
                            break;
                        case "two":
                            finalphone += '2';
                            number = string.Empty;
                            break;
                        case "three":
                            finalphone += '3';
                            number = string.Empty;
                            break;
                        case "four":
                            finalphone += '4';
                            number = string.Empty;
                            break;
                        case "five":
                            finalphone += '5';
                            number = string.Empty;
                            break;
                        case "six":
                            finalphone += '6';
                            number = string.Empty;
                            break;
                        case "seven":
                            finalphone += '7';
                            number = string.Empty;
                            break;
                        case "eight":
                            finalphone += '8';
                            number = string.Empty;
                            break;
                        case "nine":
                            finalphone += '9';
                            number = string.Empty;
                            break;
                    }

I am a bit concerned with this switch statement, because there are many repeated lines ("number = string.Empty"). Could I make it more compact somehow?

                }
            }
            Console.WriteLine(finalphone);
            Console.ReadLine();
        }
    }
}


texts: AutoDictionary for objects with a key property

texts:
The normal dictiory separates the key from the value... but what if the key is a part of the item it stores? It then forces you to enter the same things twice, once for the key and agian for the item. I never liked it so I thought I write really simple class that takes this unecessary step away a makes life easier again by allowing you to specify a key selector like the ToDictionary extension does.

public class AutoDictionary<TKey, TItem> : ICollection<TItem>, IEnumerable<TItem>
{
    private readonly Func<TItem, TKey> _keySelector;

    private readonly IDictionary<TKey, TItem> _items;

    public AutoDictionary(Func<TItem, TKey> keySelector)
    {
        _keySelector = keySelector;
        _items = new Dictionary<TKey, TItem>();
    }

    public AutoDictionary(Func<TItem, TKey> keySelector, IEqualityComparer<TKey> equalityComparer)
    : this(keySelector)
    {
        _items = new Dictionary<TKey, TItem>(equalityComparer);
    }

    public AutoDictionary(Func<TItem, TKey> keySelector, IDictionary<TKey, TItem> other)
    : this(keySelector)
    {
        _keySelector = keySelector;
        _items = new Dictionary<TKey, TItem>(other);
    }

    public TItem this[TKey key]
    {
        get { return _items[key]; }
        set { _items[key] = value; }
    }

    public int Count => _items.Count;

    public bool IsReadOnly => false;

    public void Add(TItem item) => _items.Add(_keySelector(item), item);

    public void Clear() => _items.Clear();

    public bool TryGetItem(TKey key, out TItem item) => _items.TryGetValue(key, out item);

    public bool Contains(TItem item) => _items.ContainsKey(_keySelector(item));

    public void CopyTo(TItem[] array, int arrayIndex) { }

    public bool Remove(TItem item) => _items.Remove(_keySelector(item));

    public IEnumerator<TItem> GetEnumerator() => _items.Values.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

I wanted to make all methods use lambdas but the constructor doesn't allow this :-(

Usage:

class Foo
{
    public string Name { get; set; }
    public int Bar { get; set;}
    public double Baz { get; set;}
}

var autoDic = new AutoDictionary<string, Foo>(x => x.Name)
{
    new Foo { Name = "foo1", Bar = 1 },
    new Foo { Name = "foo2", Bar = 2 },
    //new Foo { Name = "foo1", Bar = 1 }, // bam!
};

var foo1 = autoDic["foo1"];

I guess I've reinvented the wheel, haven't I? ;-)


texts:
You might consider this question a follow-up of:

BigInteger check in C from a string

Although, this time, I used C++.

I am on Linux Mint 19.1 with the compiler version:

g++-8 (Ubuntu 8.2.0-1ubuntu2~18.04) 8.2.0

I tried to push myself hard in C, but it obviously requires one of:

more skill / experience
lower-level approach

or both.

That is why I decided to transition to C++, already bought one C++ online course on Udemy, but back to coding, the current version looks straightforward to me, I see no more pointers, etc., which sounds ideal to me:

#include <iostream>
//#include <string> // I don't get why it compiles without this header

bool string_contains_integer(std::string str)
/*
    This function iterates through an array of chars,
    and checks each character to be a digit;
    optionally including a starting "+/-" sign.

    Returns true if the string contains a number (string of digits);
    Returns false if the string contains another character(s).

    Starting "+/-" gets ignored, as we accept all integer numbers.
*/
{
    // if the string is empty, return right away
    if ( str.empty() ) return false;

    // I'd like to avoid repeated length() calls
    unsigned long long string_length = str.length();

    // find out if there is a "+/-" sign
    bool sign_present = ( (str[0] == '-') || (str[0] == '+') );

    // check if there is the sign only
    if ( sign_present && (string_length == 1) ) return false;

    // iterate through all characters in the string
    for (unsigned long long i = 0; i < string_length; i++)
    {
        // skip the digit check for the sign at the beginning
        if ( (i == 0) && sign_present ) continue;

        // this is actually the core part checking on digits
        if ( ! std::isdigit( (unsigned char) str[i] ) ) return false;
    }

    // If we got here, then all the characters are digits,
    // possibly starting with a sign.
    return true;
}

int main(void)
{
    if ( string_contains_integer("-123456789123456789123456789123456789123456789123456789123456789") )
    {
        std::cout << "PASS: Input is a number.\n";
        return 0;
    }
    else
    {
        std::cerr << "FAIL: Input is not a number!\n";
        return 1;
    }
}

This program I compile as follows:

g++-8 -std=c++17 -Wall -Wextra -Werror -Wpedantic -pedantic-errors -o bigInteger bigInteger.cpp


texts:
Given the following task:

  Use Newton's method to compute the square root of a number.  Newton's
  method involves successive approximation.  You start with a guess, and
  then continue averaging successive guesses until you reach a
  satisfactory level of precision.

I wrote the following (rough) solution in Scheme.  Can you help me make it better?

(define (abs x) ((if (< x 0) - +)  x))
(define (almost-equal x y delta)
    (> delta (abs (- x y))))

(define (sqrt-prime x last-x)
  (let ((next-x (/ (+ x last-x) 2)))
        (if (almost-equal next-x x 0.000001) x
            (sqrt-prime next-x x))))

(define (sqrt x) (sqrt-prime x 1))


texts: Coq proof that type isomorphism relationship is transitive

texts:
The following code is in Coq, a proof assistant by INRIA implemented in OCaml.

I'm defining two types as being isomorphic when there exists two functions f : s -> t and g : t -> s such that, for all x, f (g x) = x. The function compose is just a helper function to make it easier to write terms in my typeclass.

I'm trying to prove that the isomorphism relation that I'm defining is transitive.

My proof is kind of ugly, I'm using inversion twice to get a whole bunch of terms "in scope".

Here's all the stuff that I introduce:

1 subgoal
A : Type
B : Type
C : Type
X : Isomorphism A B
X' : Isomorphism B C
from0 : A -> B
to0 : B -> A
from_to0 : forall x : B, from0 (to0 x) = x
to_from0 : forall x : A, to0 (from0 x) = x
from1 : B -> C
to1 : C -> B
from_to1 : forall x : C, from1 (to1 x) = x
to_from1 : forall x : B, to1 (from1 x) = x
______________________________________(1/1)
Isomorphism A C

Then I'm using refine with two holes _ in order to introduce two further goals:

refine({|
  from := compose from1 from0;
  to := compose to0 to1;
  from_to := _;
  to_from := _
|}).

I'm constructing from and to explicitly, and allowing from_to and to_from to become goals, like this:

______________________________________(1/2)
forall x : C, compose from1 from0 (compose to0 to1 x) = x
______________________________________(2/2)
forall x : A, compose to0 to1 (compose from1 from0 x) = x

And then for each of those cases I unfold to get rid of compose, and then get rid of adjacent froms and tos by rewriting.

This whole thing seems more complicated than it needs to be. Is there a more direct way to show that Isomorphism A B -> Isomorphism B C -> Isomorphism A C is inhabited?

Here is the complete source code for reference:

Class Isomorphism A B :=
  {
    from: A -> B;
    to: B -> A;
    from_to x: from (to x) = x;
    to_from x: to (from x) = x
  }.

Definition compose {T T' T''} (f : T' -> T'') (g : T -> T') (x : T) : T'' :=
  f (g x).

Definition trans { A B C }: Isomorphism A B -> Isomorphism B C -> Isomorphism A C.
intros X X'.
inversion X.
inversion X'.
refine({|
  from := compose from1 from0;
  to := compose to0 to1;
  from_to := _;
  to_from := _
|}).
{
  intros.
  unfold compose.
  rewrite -> from_to0.
  rewrite -> from_to1.
  reflexivity.
}
{
  intros.
  unfold compose.
  rewrite -> to_from1.
  rewrite -> to_from0.
  reflexivity.
}
Qed.


texts:
The following problem is currently taking more than 8 seconds to execute. Please help me to modify the program, so that execution time will be reduced.

var yourself = {
fibonacci : function(n) {
    if (n === 0) {
        return 0;
    }
    if (n === 1) {
        return 1;
    }
    else {
        return this.fibonacci(n - 1) +
            this.fibonacci(n - 2);
    }
}
};


texts:
This game that I semi coded is a little bulky and kind of boring. I want to know if there is anything simple I can do to shrink it and add a little spice to the code.

# Word Jumble
#
# The computer picks a random word and then "jumbles" it
# The player has to guess the original word

import random

# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")

print(
"""
           Welcome to Word Jumble!

   Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)

play=input("Do you want to play? (yes or no)")
while play=="yes":
    # pick one word randomly from the sequence
    word = random.choice(WORDS)
    # create a variable to use later to see if the guess is correct
    correct = word

    # create a jumbled version of the word
    jumble =""
    while word:
        position = random.randrange(len(word))
        jumble += word[position]
        word = word[:position] + word[(position + 1):]

    print("The jumble is:", jumble)
    points=100
    guess = input("\nYour guess: ")
    while guess != correct and guess != "":
        print("Sorry, that's not it.")
        hint=input("Do you need a hint?")
        if hint=="yes":
            points=int(points)-10
            if correct=="python":
                print("Its a snake...")
            elif correct=="jumble":
                print("Rhymes with rumble")
            elif correct== "easy":
                print("This one is so simple!")
            elif correct=="difficult":
                print("This is a hard one... its very ________________")
            elif correct=="answer":
                print("You cant find it? the _________ is ___________")
            elif correct=="xylophone":
                print("It is a toy...")
            print("Thanks for takeing the hint, idiot...")
        guess = input("Your guess: ")

    if guess == correct:
        print("That's it!  You guessed it!\n")
        print("Your score is: "+str(points))
        play=input("Do you want to play again? (yes or no)")
    elif guess== "":
        print("You failed...")
        play=input("Do you want to play again? (yes or no)")

print("Thanks for playing.")

input("\n\nPress the enter key to exit.")


texts: SASS mixin for a font-awesome before/after usage

texts:
In my SASS I use font-awesome declarations all over the place. I'm in love with it. I've created a SASS mixin for the usage:

I started with the following:

@mixin font-awesome-icon($type, $unicode, $size, $margin, $color, $weight) {
  @if $type == 'after'{
    &:after {
      content:$unicode;
      font-family:"FontAwesome";
      font-size:$size;
      color:$color;
      font-weight:$weight;
      margin:$margin;
      @content;
    }
  }
  @if $type == 'before' {
    &:before {
      content:$unicode;
      font-family:"FontAwesome";
      font-size:$size;
      color:$color;
      font-weight:$weight;
      margin:$margin;
      @content;
    }
  }
}

I then scaled it down further to the following:

@mixin font-awesome-icon($type, $unicode, $size, $margin, $color, $weight) {
  $beforeOrAfter:'';

  @if $type == 'after' {
    $beforeOrAfter:'after';
  }
  @else if $type == 'before' {
    $beforeOrAfter:'before';
  }

  &:#{$beforeOrAfter} {
      content:$unicode;
      font-family:"FontAwesome";
      font-size:$size;
      color:$color;
      font-weight:$weight;
      margin:$margin;
      @content;
    }
}

The usage would something like:

.tater {
@include font-awesome-icon(before,'\f0de',2.1em,0 0 0 3em,orange,300);
}

But I feel I could make the before/after part cleaner. I basically need to determine if it is a 'before' or 'after'.


texts:
This is an extension method to get a string that is truncated to a maximum length.

Any comments?

public static class StringExtensions
{
    public static string WithMaxLength(this string value, int maxLength)
    {
        if (value == null)
        {
            return null;
        }

        return value.Substring(0, Math.Min(value.Length, maxLength));
    }
}


texts:
I have an application which requests data from a REST endpoint 50 items at a time and displays results in the UI. I would like to paginate each API response into smaller arrays for display and then request a new API resource when the user reaches the end of the children arrays.

I have a working CodePen demo using the SWAPI and paginating results (5 at a time) and I'm wondering if there is a better/more efficient way to achieve the same result.

// See the CodePen for a working demo using these HTMl elements
const container = document.querySelector('#container');
const start = document.querySelector('#button');

let planetArrays = [];
let nextPage;
let refresh = true;

async function request(url) {

  // Call specific page of results if provided
  url = url || 'https://swapi.co/api/planets';

  var data = await fetch(url);
  var json = await data.json();

  return json;

}

async function getData() {

  let data = await request(nextPage)

  // Store the next page for future calls
  nextPage = data.next;

  // Split the big array into smaller arrays
  for(var d of data.results) {
    planetArrays.push(data.results.splice(0, 5));
  }

  // Return the spliced Array
  return planetArrays;

}

async function next() {
  var childPage, response;

  // Define which child array in smallArrays to display
  var inSmallArray = isNaN(parseInt(start.dataset.page));

  childPage = (!inSmallArray) ? parseInt(start.dataset.page) : 0;

  // hit the API if it's a refresh call
  if(refresh) {
    var response = await getData(nextPage);
    refresh = false;
  } else {
    // if it's NOT the first call, get the stored array
    response = planetArrays;
  }

  // Do a check to see if we're on the last page in memory
  if(childPage >= planetArrays.length-1) {
    // Make a refresh call on the next click
    refresh = true;
  }

  container.innerText = "";

  for(var c = 0; c < response[childPage].length; c++) {
    var p = document.createElement('p');
    p.innerText = response[childPage][c].name;
    container.appendChild(p);
  }

  // iterate the planetArrays
  var newPage = childPage + 1;
  start.dataset.page = newPage;

}

start.addEventListener("click", next)


texts:
This is a simple mixed drink calculator written in Haskell.

There are two input files. The drinks file contains a list of simply formatted recipes for mixed drinks:

screwdriver:vodka,orange juice
white russian:vodka,coffee liqueur,cream
greyhound:gin,grapefruit juice
...

The ingredients file contains a line-separated list of presently available ingredients:

vodka
gin
rum
orange juice
cranberry juice
grapefruit juice
...

The calculator parses the drinks file and the ingredients file, determines which mixed drinks can be created with the available ingredients, and pretty-prints the results to screen:

Screwdriver: Vodka, Orange juice
Greyhound: Gin, Grapefruit juice
...

It's a simple program, but I want to improve my code style and make my Haskell more idiomatic.

import Text.ParserCombinators.Parsec
import Data.Char
import Data.List

type Drink = (DrinkName, [Ingredient])
type DrinkName = String
type Ingredient = String

-- parsing the file of drink recipes
drinksFile ∷ GenParser Char st [Drink]
drinksFile = endBy drink (char '\n')

-- parsing each drink recipe
drink ∷ GenParser Char st Drink
drink = do first ← drinkName
           next ← recipe
           return (first, next)

-- parsing the drink name
drinkName ∷ GenParser Char st DrinkName
drinkName = do name ← many (noneOf ":")
               sep ← many (char ':')
               return name

-- parsing the recipe into a list of ingredients
recipe ∷ GenParser Char st [Ingredient]
recipe = sepBy (many (noneOf ",\n")) (char ',')

-- returns true iff the drink can be made with the given ingredients
canMake ∷ [Ingredient] → Drink → Bool
canMake ingredients drink = all (flip elem ingredients) recipe
                            where recipe = snd drink

-- returns the drinks that can be made with the given ingredients
filterByIngredients ∷ [Drink] → [Ingredient] → [Drink]
filterByIngredients drinks ingredients = filter (canMake ingredients) drinks

-- pretty prints a drink with its recipe
printDrink ∷ Drink → String
printDrink (drinkName, recipe) = intercalate " " (map capitalize (words drinkName)) ++
                                ": " ++
                                intercalate ", " (map capitalize recipe)
                                where capitalize (x : xs) = toUpper x : xs

main = do drinks ← readFile "drinks"
          ingredients ← readFile "ingredients"
          case parse drinksFile "drinksFile" drinks of
               Left error → do putStrLn "Error parsing drinks file."
               Right parsedDrinks → mapM_ (putStrLn ∘ printDrink)
                                          (filterByIngredients parsedDrinks
                                                               (lines ingredients))


texts: Populate null fields in an object through reflection

texts:
I have recently implemented this utility class for going through an instance's member fields recursively and assigning them default values if they are null. Here is the implementation in the NullHandler class:

public static class NullHandler
{
    public static void PopulateNullFields<T>(T obj)
    {
        var fields = obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);

        foreach(var field in fields)
        {
            var defaultValue = field.GetValue(obj);

            if(defaultValue == null)
            {
                defaultValue = GetDefaultValue(field.FieldType);
            }

            var subFields = field.FieldType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);

            if(subFields.Count() > 0 && !field.FieldType.IsValueType && field.FieldType != typeof(string))
            {
                PopulateNullFields(defaultValue);
            }

            field.SetValue(obj, defaultValue);
        }
    }

    public static object GetDefaultValue(Type t)
    {
        if(Nullable.GetUnderlyingType(t) != null)
        {
            t = Nullable.GetUnderlyingType(t);
        }

        if(t == typeof(string))
        {
            return "";
        }
        else if(t == typeof(DateTime))
        {
            return new DateTime();
        }
        else if (t.IsValueType)
        {
            return Activator.CreateInstance(t);
        }
        else if(t.IsArray)
        {
            var cinfo = t.GetConstructors().FirstOrDefault(x => x.GetParameters().Count() == 1);

            if(cinfo != null)
            {
                return cinfo.Invoke(new object[] { 0 });
            }
            else
            {
                throw new InvalidOperationException("Unable to find array constructor for this array type.");
            }
        }
        else if(t.IsEnum)
        {
            return Enum.GetValues(t).GetValue(0);
        }
        else
        {
            var cinfo = t.GetConstructors().Where(x => x.GetParameters().Count() == 0).FirstOrDefault();
            if (cinfo != null)
            {
                return Activator.CreateInstance(t);
            }
            else
            {
                throw new InvalidOperationException("No default constructor with no parameter is found for the type.");
            }
        }
    }
}

The code is currently in use in our XML serialization routine, where we have a requirement for another system that expects an XML file with null values included. The .NET XmlSerializer class omits null properties in the generated XML unless the properties are decorated with the XmlElement(IsNullable = true) attribute.

While we would have rather added the attributes to the model class itself, the model class is (a) created from code-generation, and we would lose the changes if we needed to regenerate the model class, and (b) the generated model class is at least ~3000 LOC, making it time-consuming to manually add the needed attributes ourselves.

Here is a sample of how the NullHandler utility class is in use on our project:

using (var stringWriter = new StringWriter())
using (var xmlStringWriter = XmlWriter.Create(stringWriter, settings))
{
     NullHandler.PopulateNullFields(item.Result.Payee);
     serializer.Serialize(xmlStringWriter, item.Result);

     // ...save XML to database
}

I would like to get feedback if there are areas where the code can be improved. I would specifically like to know how I can improve the reusability of the NullHandler class by accounting for any possibly missed cases (most especially in the GetDefaultValues method). Feedback to improve the class's readability would be appreciated as well.


texts:
I am the half-robot side of syb0rg that will be posting the recent answers of Code Review to the CR Answers chatroom.  Here is the list of review suggestions I would like, in order of preference:

Efficiency (with API requests, speed of login and posting answers, etc.)
Security issues
Best practices

For feature requests regarding the chat bot, please see this meta post.

Any and all reviews are acceptable however.  Don't be too harsh please, this is one of my first times using Ruby.

ACCESS_TOKEN = '<insert key>'
# get your access token here:
# https://stackexchange.com/oauth/dialog?client_id=2666&redirect_uri=http://keyboardfire.com/chatdump.html&scope=no_expiry
$root = 'http://stackexchange.com'
$chatroot = 'http://chat.stackexchange.com'
$room_number = 12723
site = 'codereview'
email = '<insert email>'
password = '<insert password>'

require 'rubygems'
require 'mechanize'
require 'json'
require 'net/http'

loop
{
    begin

    $agent = Mechanize.new
    $agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE

    login_form = $agent.get('https://openid.stackexchange.com/account/login').forms.first
    login_form.email = email
    login_form.password = password
    $agent.submit login_form, login_form.buttons.first
    puts 'logged in with SE openid'

    meta_login_form = $agent.get($root + '/users/login').forms.last
    meta_login_form.openid_identifier = 'https://openid.stackexchange.com/'
    $agent.submit meta_login_form, meta_login_form.buttons.last
    puts 'logged in to root'

    chat_login_form = $agent.get('http://stackexchange.com/users/chat-login').forms.last
    $agent.submit chat_login_form, chat_login_form.buttons.last
    puts 'logged in to chat'

    $fkey = $agent.get($chatroot + '/chats/join/favorite').forms.last.fkey
    puts 'found fkey'

    def send_message text
        loop
        {
            begin
            resp = $agent.post("#{$chatroot}/chats/#{$room_number}/messages/new", [['text', text], ['fkey', $fkey]]).body
            success = JSON.parse(resp)['id'] != nil
            return if success
            rescue Mechanize::ResponseCodeError => e
            puts "Error: #{e.inspect}"
            end
            puts 'sleeping'
            sleep 3
        }
    end

    puts $ERR ? "An unknown error occurred. Bot restarted." : "Bot initialized."

    last_date = 0
    loop
    {
        uri = URI.parse "https://api.stackexchange.com/2.2/events?pagesize=100&since=#{last_date}&site=#{site}&filter=!9WgJfejF6&key=thqRkHjZhayoReI9ARAODA((&access_token=#{ACCESS_TOKEN}"
        http = Net::HTTP.new(uri.host, uri.port)
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
        data = JSON.parse http.get(uri.request_uri).body
        events = data['items']

        data['items'].each do |event|
            last_date = [last_date, event['creation_date'].to_i + 1].max
            if ['answer_posted'].include? event['event_type']
                send_message "[tag:rob0t] New answer detected:"
                send_message event['link']
                puts "Answer posted."
            end
        end
        puts "#{data['quota_remaining']}/#{data['quota_max']} quota remaining"
        sleep(40 + (data['backoff'] || 0).to_i) # add backoff time if any, just in case
    }

    rescue => e
        $ERR = e
        p e
    end
}

(Attribution to original author, code above is a modified version of it.)


texts:
When I read the community challange, I couldn't wait. So here I go with the very first Four tiles game:

import pygame as pg
import sys
import random
import time
import tkMessageBox

if sys.version_info.major == 3:
    import tkinter as tk
else:
    import Tkinter as tk

from pygame.locals import *

def game(LENGHT):
    pg.init()
    pg.display.set_caption("Four tiles game")

    WIDTH = 600
    HEIGHT = 400
    DISPLAY = pg.display.set_mode((WIDTH, HEIGHT), 0, 32)

    WHITE = (255, 255, 255)
    RED = (255, 0, 0)
    green = (0, 255, 0)
    blue = (0, 0, 255)
    yellow = (255, 255, 0)
    COLORS = [RED, blue, green, yellow]

    WAITING_TIME = 500

    def generate_correct_sequence(length):
        return [random.randint(1, 4) for _ in range(length)]

    def draw_button(n, color):
        if n == 1:
            pg.draw.rect(DISPLAY, color, (0, 0, WIDTH / 2, HEIGHT / 2))
        if n == 2:
            pg.draw.rect(DISPLAY,color,
            (WIDTH / 2, 0, WIDTH / 2, HEIGHT / 2))
        if n == 3:
            pg.draw.rect(DISPLAY,color,
            (0, HEIGHT / 2, WIDTH / 2, HEIGHT / 2))
        if n == 4:
            pg.draw.rect(DISPLAY,color,
            (WIDTH / 2, HEIGHT / 2, WIDTH / 2, HEIGHT / 2))

    def draw_buttons():

        for i in range(1, 5):
            draw_button(i, COLORS[i - 1])

    def what_button_is_clicked(mouse_pos):
        """
        The buttons are numbered in the following way
            1 | 2
            _____

            3 | 4
        """
        if mouse_pos[0] < WIDTH / 2 and mouse_pos[1] < HEIGHT / 2:
            return 1

        if mouse_pos[0] > WIDTH / 2 and mouse_pos[1] < HEIGHT / 2:
            return 2

        if mouse_pos[0] < WIDTH / 2 and mouse_pos[1] > HEIGHT / 2:
            return 3

        elif mouse_pos[0] > WIDTH / 2 and mouse_pos[1] > HEIGHT / 2:
            return 4

    def flash(button_number, waiting_time):
        draw_button(button_number, WHITE)
        pg.display.update()
        pg.time.wait(waiting_time)
        draw_button(button_number, COLORS[button_number - 1])
        pg.display.update()

    def inform_user(correct_sequence, delay):
        for button in correct_sequence:
            flash(button, delay)

    draw_buttons()
    correct_sequence = generate_correct_sequence(LENGHT)
    inform_user(correct_sequence, WAITING_TIME)

    while True:
        for event in pg.event.get():
            if event.type == QUIT:
                pg.quit()
            if event.type == pg.MOUSEBUTTONUP:
                mouse_pos = pg.mouse.get_pos()
                if what_button_is_clicked(mouse_pos) == correct_sequence[0]:
                    correct_sequence.pop(0)
                else:
                    tkMessageBox.showinfo("LOSE", "You are the loser...")
                    pg.quit()

        if correct_sequence == []:
            tkMessageBox.showinfo("WIN", "You are the winner!!!")
            pg.quit()

if __name__ == "__main__":
    root = tk.Tk()
    root.wm_title("Four tiles game")

    def play():
        game(w.get())

    INTRODUCTION = tk.StringVar()
    INTRODUCTION.set("""Welcome to the four tiles game.
You will see some tiles light up one after the other.
Afterwards, you must click them in the same order they lit up before.""")
    tk.Message(root, textvariable=INTRODUCTION, width=500, font=30).pack()

    tk.Label(root, text="Select the lenght down here", font=30).pack()
    w = tk.Scale(root, from_=1, to=15, orient=tk.HORIZONTAL, length=400)
    w.pack()

EDIT: If you want to look at the game with added functionalaties and features and with nicer style go to this GitHub repo.


texts: Converting a Website Into a Single Page App

texts:
I want to convert my website into a single page app. This function does the trick:

$(document).ready(function(){
    $("body").delegate("a", "click", function(){
        var href = $(this).attr("href");
            $.get(href,function(data){
            var newDoc = document.open("text/html", "replace");
            newDoc.write(data);
            newDoc.close();
        });
        return false;
    });
});

Assuming I have no redirects other than <a> tags, it should work fine, right? It feels so wrong and yet so right...


texts:
I am trying to find an algorithm to solve the following problem with python.
Given a list of integers, check if after dropping two elements of the list, is posible to divide the list in 3 where the sum of the consecutive numbers are equals.
For example: A = [1, 3, 4, 2, 2, 2, 1, 1, strong text2] should return TRUE because we would drop the elements in bold the list can be slit in [1, 3], [2, 2], [2, 1, 1] where all sum 4
B = [1, 1, 1, 1, 1, 1] should return FALSE
C = [1, 1, 3, 1, 1, 1034, 5, 9900, 1, 2] should also return FALSE because eventhough after droping the numbers in bold you can sum have the numbers to sum 5 (1,1,3), (5), (1, 1, 1, 2) the list should be sorted first and that's not allowed.
I have come with a solution that seems to work but it is very, very bad and not sure if always work, and the complexity is too high when should be O(n). I am doing it removing two elements each iteration and putting them back if the condition is not TRUE
for i in A:
        try:
            d1=A[i]
            A.pop(i)
        except:
            break

        for j in A:
            sumA=0
            try:
                d2=A[j]
                A.pop(j)
            except:
                break

but this gives me complexity of O(n^2), how else can it be done?


texts:
This is my version of the binary search method. What more can I do to optimize this?

I have written comments throughout to guide anyone who might find this code helpful through how it operates. But I would like to update it if it can be made faster/cleaner.

def bSearch(arr, val, first, last):

    #Find the index of the middle array value.
    mid = (len(arr)-1)//2

    #If there are no more numbers to search through
    if first >= last:

        #Check if the last number is the number being searched for.
        if (arr[mid] == val):
            print("TRUE")
        else:
            print("FALSE")

    #If there are still numbers to search through
    #check array at index (mid) for the desired value.
    elif (arr[mid] == val):
        print("TRUE")

    elif (arr[mid] < val):
        #nArr = new array = greater half of the original array.
        nArr = arr[len(arr)//2:]
        bSearch(nArr, val, 0, len(nArr)-1)

    elif (arr[mid] > val):
        #nArr = new array = lesser half of the original array.
        nArr = arr[:len(arr)//2]
        bSearch(nArr, val, 0, len(nArr)-1)

#The array used for testing.
a = [1,2,3,4,6,7,8,10]

print("Test One")
#Search for 5 in array a. Should return false.
bSearch(a, 5, 0, len(a)-1)

print("Test Two")
#Search for 2 in array a. Should return true.
bSearch(a, 2, 0, len(a)-1)

print("Test Three")
#Search for 8 in array a. Should return true.
bSearch(a, 8, 0, len(a)-1)

print("Test Four")
#Search for 1 in array a. Should return true.
bSearch(a, 1, 0, len(a)-1)

print("Test Five")
#Search for 15 in array a. Should return false.
bSearch(a, 15, 0, len(a)-1)


texts: Meta-circular interpreter for lambda calculus in Haskell

texts:
For learning purpose, I've written a simple lambda calculus interpreter (plus 'Add'). I would like it to be the cleanest and most idiomatic possible.

Bonus question: how would you use deriving (Show) for Val, just having to define show for Fun (Val -> Val)?

-- Lambda calculus interpreter example.

import qualified Data.Map.Lazy as Map

data Val = Num Integer | Fun (Val -> Val) | Wrong
data Term = Cons Integer | Var String | Lam String Term | App Term Term | Add Term Term
type Env = Map.Map String Val

add :: Val -> Val -> Val
add (Num x) (Num y) = Num (x+y)
add _ _ = Wrong

apply :: Val -> Val -> Val
apply (Fun f) v = f v
apply _ _ = Wrong

instance Show Val where
  show (Num x) = show x
  show (Fun f) = "function"
  show Wrong = "Wrong"

interp :: Term -> Env -> Val
interp (Cons x) e = Num x
interp (Var s) e = Map.findWithDefault Wrong s e -- Equivalent to:
-- interp (Var s) e = maybe Wrong id (Map.lookup s e)
interp (Lam s t) e = Fun (\v -> interp t (Map.insert s v e))
interp (App f t) e = apply (interp f e) (interp t e)
interp (Add a b) e = add (interp a e) (interp b e)

expr = App (Lam "x" (Add (Var "x") (Var "x"))) (Add (Cons 10) (Cons 11))
res = interp expr Map.empty

main = putStrLn (show res)


texts:
Normally I do this:

if (Animal is Dog)
{
    Doc d = (Dog)Animal;
    // d. etc..
}
else if (Animal is Cat)
{
    Cat c = (Cat)Animal;
    // c. ....
}

Is this a good way or are there better ways to implement this code above (performance, ...) ?

Should it be like this?:

Dog d = Animal as Dog;

if (d != null;)
{
    // d. etc..
}
else if (Animal is Cat)
{
    Cat c = (Cat)Animal;
    // c. ....
}

Or maybe like this?:

Dog d = Animal as Dog;
Cat c;

if (d != null;)
{
    // d. etc..
}
else if ((c = Animal as Cat) != null)
{
    // c. ....
}

Or maybe something else?


texts: SICP Exercise 1.3: Sum of squares of two largest numbers out of three, Rust Version

texts:
The exercise 1.3 of the book Structure and Interpretation of Computer Programs asks the following:

  Exercise 1.3.  Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

My answer is this:

#![feature(core)]
use std::cmp;

fn sum_square_largest(x:f64, y:f64, z:f64) -> f64 {
    match partial_min_three(x, y, z) {
        Some(a) =>  x * x + y * y + z * z - a * a,
        None => 0.0_f64/0.0_f64
    }
}

fn partial_min_three<T>(v1: T, v2: T, v3: T) -> Option<T> where T: PartialOrd<T> {
    match cmp::partial_min(v2, v3) {
        Some(x) => cmp::partial_min(v1, x),
        None => None
    }
}

Rust is the language I know less, I would really appreciate your advice.


texts: Create a list of all possible combinations of elements into n-groups from a set of size k

texts:
I'm trying to write a Java program that, given a particular number of groups and number of total participants, creates a list of all possible ways to fill that number of groups evenly using all the participants. The group number/order doesn't matter. For instance, if {} denotes one possible way to create a set of groups, [] denotes a group, and each individual is represented by a number, the groupings {[1,2],[3,4,5]} and {[4,3,5],[1,2]} should be considered equivalent and are both valid groupings for an input of 5 participants and 2 groups.

So far I've written the following code, which works by recursively finding all possible permutations and removing any duplicates (like in the example above). This works fine for small input values, but becomes extremely slow quickly. Can anyone give my any ideas on how to either optimize this code or for a more efficient way to do this (and if the latter, pseudo or java code would be great)? I know that there might not be an extremely fast way to do this, but I'd like to at least be able to run it with some reasonably small numbers and have it finish in a relatively short time period and not take up more RAM than it has too.

Let me know if the above explanation is unclear! Thanks!

private int numParticipants, numGroups, maxParticipantsPerGroup;
private ArrayList<ArrayList<ArrayList<Integer>>> participantGroups = new ArrayList<ArrayList<ArrayList<Integer>>>();

private void generateParticipantGroupings() {
    ArrayList<ArrayList<Integer>> groupings = new ArrayList<ArrayList<Integer>>();
    for (int i = 0; i < numGroups; i++)
            groupings.add(new ArrayList<Integer>());

    buildParticipantGrouping(1, groupings);
}

private void buildParticipantGrouping(int currentParticipant, ArrayList<ArrayList<Integer>> grouping) {
    if (currentParticipant > numParticipants) {
        boolean match = false;
        for (int j = 0; j < participantGroups.size(); j++) {
            int numMatches = 0;
            for (int k = 0; k < numGroups; k++) {
                for (int m = 0; m < numGroups; m++) {
                    if (grouping.get(k).equals(participantGroups.get(j).get(m))) {
                        numMatches++;
                        break;
                    }
                }

            }

            if (numMatches >= numGroups) {
                match = true;
                break;
            }
        }

        if (!match)
            participantGroups.add(grouping);
    }
    else {
        for (int i = 0; i < numGroups; i++) {
            if (grouping.get(i).size()  < maxParticipantsPerGroup)  {
                ArrayList<ArrayList<Integer>> tempGroupings = new ArrayList<ArrayList<Integer>>();
                for (int a = 0; a < numGroups; a++) {
                    tempGroupings.add(new ArrayList<Integer>());

                    for (Integer x : grouping.get(a))
                        tempGroupings.get(a).add(x);
                }

                tempGroupings.get(i).add(currentParticipant);

                buildParticipantGrouping(currentParticipant + 1, tempGroupings);
            }
        }
    }
}

EDIT: Yes, I have searched to see if I can find a previous post that asks the same question. I have not found any. If you can find a previous post asking the same question (that has answers) then I'd love to see it, but otherwise please make sure that a question is actually the same as mine before suggesting it as a duplicate.


texts: Using attributes with properties in asp.net MVC

texts:
I have an auto generated partial class in my Model folder with lots of properties and I need to modify some of the setters in these properties(annotate property), to ensure that I don't repeat myself in the future (after a refresh) I have another partial class with the same properties by use of attributes, where these properties cannot be modified, only via provided attributes.

So I have built a custom attribute class to modify those properties. Now my question is, am I doing this correctly or am I just creating a mess. Is there a better or another way to achieve my goal?
Please explain how to approach this delicate matter.

This is an auto generated class in Models folder:

public partial class Stud
{
    public string Property1{ get; set; }
    public string Property20{ get; set; }
}

This is the class for mine metadata with properties that I want to modify:

public class MetadataClasses
{

    public class StudMetadata
    {
        [Required, DisplayName("Property one"), UpperCaseAttribute]
        public string Property1 { get; set; }

        [Required, DisplayName("Property two"), ReplaceNrAttribute]
        public string Property2{ get; set; }
    }
}

This is an custom attribute class in different folder called Attributes:

public class UpperCaseAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        try
        {
            validationContext
                .ObjectType
                .GetProperty(validationContext.MemberName)
                .SetValue(validationContext.ObjectInstance, value.ToString().ToUpper(), null);
        }
        catch (System.Exception)
        {
        }
        return null;
    }
}

This is an partial class named "PartialClasses.cs" in Models folder:

[MetadataType(typeof(MetadataClasses.StudMetadata))]
public abstract partial class Stud
{
}


texts:
I'm writing my server and now I'm creating a controller for each route so I could use the same controller in different apis rather than rewrite the same code over and over. Below is my code example of two different controllers that are used together in the same route.

module.exports = {
addUser : function(record,schoolId){
    return new Promise(function(resolve,reject){
    var newUser = new User({
        phone_number : record.phone_number,
        email : record.email,
        name :  record.name_of_user,
        password: "123",
        type: 3,
        refid: record.bus._id,
        school_id: schoolId
    });
    newUser.save(function(err,user){
        if(err){
            reject(user)
        }else{
            resolve(user);
        }
    });
    }).catch(function(error){
            if(error){
                res.json({status:"error", message :"error saving user"});
                return;
            }
        });
     }
};

The other controller is the bus controller.

var Bus = require('../models/bus');

         module.exports= {
addBus : function(record,schoold){
    return new Promise(function(resolve,reject){
        var bus_number = record.bus_number,
            trips = record.trips,
            location = record.location,
            language = record.language,
            name = record.name,
            license = record.license[0],
            age = record.age,
            capacity = record.capacity,
            maker = record.maker,
            model = record.model,
            plate_number = record.plate_number;

        var newBus = new Bus({
            language: language ? language : "",
            bus_number: bus_number  ? bus_number : "",
            bus_driver: bus_driver  ? bus_driver : {},
            bus_details: bus_details ,
            trips: trips ? trips : [],
            school_id: schoold,
            location: location ? location : {}
        });
        newBus.save(function(err,bus){
            if(err){
                reject(bus);
            }else{
                resolve(bus);
            }
        });
    }).catch(function(error){
            if(error){
                res.json({status:"error", message :"error while saving bus"});
                return;
            }
        });
      }
    };

In my route I should create a bus and then the create a user for the bus, the user has to have the bus id as a ref id.
What is the best way to organize my code? should I call the addBus from the route and then call the add user from the bus controller?
or should I call both from the route? and if so how do I return the created bus id from the addBus to the route?

I've tried the following but it didn't work!

router.post('/add',Validation, function (req, res) {

var record = req.body.record;
record.name_of_user =  "باص رقم"+ ' ' +record.bus_number;
console.log(record);
var schoolId = req.body.schoolId;
BusController.addBus(record,schoolId).exec().then(function(){
    return UserController.addUser(record,schoolId);
}).then(function(){
    res.json({status:"success", message : "bus successfully created"});

}).catch(function(error){
        if(error){
            console.log(error);
            res.json({status:"error",message:"error while creating bus"});

            return;
        }
    });


texts:
I recently had an interview where I was asked to reverse the second half of a linked list. The driver program was unknown to me, I just needed to write the method to do this. The method was supposed to behave as follows:

1 -> 2 -> 3 -> 4 becomes 1 -> 2 -> 4 -> 3
1 -> 2 -> 3 -> 4 -> 5 becomes 1 -> 2 -> 5 -> 4 -> 3

The function signature was as follows:

public static void reverseList(ListNode node)

I don't remember verbatim the code I submitted, but I wrote something up that follows very closely to what I submitted. The code follows:

public static void reverseList(ListNode node) {
    if(node == null) return;
    int size = size(node);
    if(size == 1) return;
    int i = 0;
    ListNode middleOfList = null;
    ListNode currentNode = node;
    //traverse the first half of the list
    while(i < size/2) {
        middleOfList = currentNode;
        currentNode = currentNode.getNext();
        i++;
    }
    ListNode previous = null;
    //reverse the second half of the list
    while(currentNode != null) {
        ListNode next = currentNode.getNext();
        currentNode.setNext(previous);
        previous = currentNode;
        currentNode = next;
    }
    //reattach first and second halves of the list
    middleOfList.setNext(previous);
}

public static int size(ListNode node) {
    ListNode current = node;
    int count = 0;
    while(current != null) {
        count++;
        current = current.getNext();
    }
    return count;
}

While I don't think this is a terrible approach for an internship interview, I'm nervous because the solution seems to be \$O(n^2)\$ since I first traverse the entire list to get the size and then traverse it again to do the actual reversal.

Is there a more efficient solution? Any general feedback on style is also appreciated.


texts:
I wrote this login program as part of my project for school. Should I use my implementation of a login program, or is there some standardized patterns of login programs, like the ones in encryption where we use made packages instead of writing our own?

Also, please correct me if am doing anything wrong or if there is a faster and more elegant way.

users = []

"""
    Look of data.txt

    john|mckinly|tree|ssap321
    elie|rose|sweet|pass123

"""

def loadData():
    with open('data.txt','r') as data:
        for line in data:
            user = makeUser(line)
            users.append(user)
    return True

def saveData():
    with open('data.txt','w') as data:
        for user in users:
            print(user['name']+'|'+user['surname']+'|'+user['username']+'|'+user['password'],file = data)

def makeUser(line):
    name, surname, username, password = line.split('|')
    if password[-1:] == '\n':
        password = password[:-1]
    return {'name':name,
            'surname':surname,
            'username':username,
            'password':password
            }

def register():
    name = input('Name:')
    surname = input('Surname:')
    while True:
        username = input('Username:')
        if checkLen(username):
            break

    while True:
        password = input('Password:')
        if checkLen(password):
            break
    users.append({'name':name,'surname':surname,'username':username,'password':password})

def checkLen(info):
    if len(info) > 0:
        return True
    else:
        print('Can\'t be blank!')

def login(state):
    while state:
        username = input('Username:')
        password = input('Password:')
        for user in users:
            if user['username'] == username and user['password'] == password:
                print('You are logged in.')
                state = False
                break
        else:
            print('Wrong input.')

def main():
    state = loadData()

    print('1) Login')
    print('2) Register')
    print('x - Exit')
    choice = input('>')

    while choice not in ['1','2','x']:
        choice = input('>')

    if choice == '1':
        login(state)
    elif choice == '2':
        register()
        main()
    elif choice == 'x':
        saveData()
        quit()

        if __name__ == '__main__':
    main()


texts: Reading Database, scraping Barchart and uploading prices to DB

texts:
This is my first real excursion into Python, coming from C#. I wanted to see if my code is well-formatted and efficient.

The following will read the needed codes from a Database Table, then submit the codes to an API, store them in individual objects, and then dump them back into another table in the Database.

import ondemand
import pyodbc
import datetime

#Code purposes
#1.) Get the desired barchart codes for the year
#2.) Load quotes into an array from Barchart API
#3.) Submit quotes to database for today's date

#Qute Class - Stores the quotes as objects
class Quote():
    def __init__(self, seq_dimDate, symbol, month, year, price, crop, ficalYear):
        self.seq_dimDate = seq_dimDate
        self.symbol = symbol
        self.month = month
        self.year = year
        self.price = price
        self.crop = crop
        self.fiscalYear = ficalYear

#Establish a connection to the database
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MyComputer\\SQLEXPRESS;DATABASE=MarketDB')
cursor = cnxn.cursor()

#get the Date and Fiscal Year
now = datetime.datetime.now().strftime('%m/%d/%Y')
dateRow = cursor.execute('SELECT * from dbo.dimDate WHERE [Date] = ?', now).fetchone()
seqDimDate = dateRow.Sequence
fiscalYear = dateRow.FiscalYear
print('Sequence for %s is %s with a fiscal year of %s' % (now, seqDimDate, fiscalYear))

#Query the Barchart Codes Table
cursor.execute('SELECT * FROM dbo.Codes WHERE [Year] = %s' % (fiscalYear))

#Generate a list of codes to send to API
quotesToQuery = ''

for row in cursor.fetchall():
    for x in range(3,len(row)):
        quotesToQuery = quotesToQuery + ',' + row[x]

#Open connection to the API
od = ondemand.OnDemandClient(api_key='123', end_point='https://marketdata.websol.barchart.com/')

#Get quotes
quotes = od.quote(quotesToQuery)['results']
lQuotes = []

#load the quotes into our array of objects
for q in quotes:
    #Get the Symbol, month, year and price of the quote
    symbol = q['symbol']
    dt = datetime.datetime.strptime(q['tradeTimestamp'], '%Y-%m-%dT00:00:00-%H:%M')
    month = dt.month
    year = dt.year
    price = q['lastPrice']

    #Get the Sequence for the Crop
    if q['name'] == 'Corn':
        crop = 1
        price = price / 100
    elif q['name'] == 'Soybean Meal':
        crop = 2
    else:
        crop = 3

    #create a new Quote object and add it to the collection
    nq = Quote(seqDimDate, symbol, month, year, price, crop, fiscalYear)
    lQuotes.append(nq)

#Double Check of Quotes
print('%s total Quotes Collected' % (len(lQuotes)))

#Delete any Prices in the Database for this date sequence
cursor.execute('DELETE FROM dbo.MarketPrice WHERE Seq_dimDate = ?', seqDimDate)
cursor.commit()
print('MarketPrice table cleared of records with Date Sequence %s...' % (seqDimDate)) #confirm records were deleted

#Submit the Quotes to the Database
for n in lQuotes:
    cursor.execute('INSERT INTO dbo.MarketPrice (Seq_dimDate, Seq_Crop, [Month], FiscalYear, Price, Comments) VALUES(?,?,?,?,?,?)', n.seq_dimDate, n.crop, n.month, n.fiscalYear, n.price, n.symbol)
    cursor.commit()
    print('%s Uploaded to MarketPrice Table in Hedging2' % (nq.symbol)) #confirm update

I submit myself to your critique!


texts:
I have a few confusions about writing Java code, and I need some clarifications:

import java.util.Scanner;

public class NameAbbreviation {

private static String  fullName;
private static Scanner nameInput;

public NameAbbreviation(String name) {
    NameAbbreviation.fullName = name;
}

public char getInitialLetterOfFirstName() {
    char initialletterOfFirstName = fullName.charAt(0);
    //System.out.println(initialletterOfFirstName);
    return initialletterOfFirstName;
}

public String getInitialLetterOfLastName() {
    int space = fullName.lastIndexOf(" ");
    String initialletterOfLastName = fullName.substring(space + 1,
            space + 2);
    //System.out.println(initialletterOfLastName);
    return initialletterOfLastName;
}

public static void main(String[] args) {

    nameInput = new Scanner(System.in);
    String name = nameInput.nextLine();
    NameAbbreviation na = new NameAbbreviation(name);
    System.out.println(na.getInitialLetterOfFirstName() + " "
            + na.getInitialLetterOfLastName());

     }
}

I have class variables fullName and nameInput. If I make nameInput local, it shows: Resource leak: nameInput is never closed. So I just follow the Eclipse suggestion and make it a field. What should I need to follow?
I have 2 methods - getInitialLetterOfFirstName() and getInitialLetterOfLastName(), the return types of which are char and String respectively. I could eventually make the return type as void. What are the advantages or disadvantages if I have void or specific return type? As both the way of code works, what do I need to follow or does it depend on how I am writing the code?
Both the methods getInitialLetterOfFirstName()and getInitialLetterOfLastName() don't have any parameters/arguments. I could eventually create the method with argument like:

getInitialLetterOfFirstName(String name) {
        this.fullName = name;    .......}

getInitialLetterOfLastName(String name) {
        this.fullName = name;    .......}

If I create the methods with arguments, I need to pass the value during the instantiation of the object. So I avoid it here, and prefer to have only once to pass the argument value.

Is there any rule  to follow, like to make the methods with parameters or not, as here both are possible with or without argument methods?

What do I need to follow as good practice, code performance issues, etc.?


texts: Vega lite plot rendering with Yew (rust + wasm)

texts:
I wanted to render some Vega plots in a rust+wasm web application I've been building with Yew. I'm a bit new to Rust, so I'm looking for feedback on runtime safety and stylistic issues.
I was specially skeptical of the spawn_local I copied from someone's GitHub and the amount of unwraps thrown around.
use std::collections::HashMap;
use vega_lite_4::*;
use wasm_bindgen_futures::*;
use wasm_bindgen::prelude::*;
use yew::prelude::*;

#[wasm_bindgen]
extern {
    fn vegaEmbed(
        el: web_sys::Element,
        spec: JsValue,
        opts: JsValue,
    ) -> js_sys::Promise;
}

pub fn vega_embed(
    node_ref: &NodeRef,
    spec: &Vegalite,
    opts: &Option<HashMap<String, String>>,
) -> Result<(), Box<dyn std::error::Error>> {
    let el = node_ref.cast::<web_sys::Element>().unwrap();
    let spec = JsValue::from_serde(spec)?;
    let opts = match &opts {
        Some(x) => JsValue::from_serde(x)?,
        None => JsValue::from(js_sys::Object::new()),
    };
    let embed: JsFuture = vegaEmbed(el, spec, opts).into();
    spawn_local(async move { embed.await.unwrap(); });
    Ok(())
}

#[derive(Properties, Clone)]
pub struct Props {
    pub spec: Vegalite,
    pub opts: Option<HashMap<String, String>>,
}

pub struct VegaLiteChart {
    node_ref: NodeRef,
    spec: Vegalite,
    opts: Option<HashMap<String, String>>,
}

impl Component for VegaLiteChart {
    type Message = ();
    type Properties = Props;

    fn create(props: Self::Properties, _link: ComponentLink<Self>) -> Self {
        VegaLiteChart {
            node_ref: NodeRef::default(),
            spec: props.spec,
            opts: props.opts,
        }
    }

    fn view(&self) -> Html {
        html! {

 }
    }

    fn update(&mut self, _msg: Self::Message) -> ShouldRender {
        false
    }

    fn change(&mut self, _props: Self::Properties) -> ShouldRender {
        false
    }

    fn rendered(&mut self, _first_render: bool) {
        vega_embed(&self.node_ref, &self.spec, &self.opts).unwrap();
    }
}

```


texts:
I want to write a cleaner version of this code. It's about two different rows consisting of numbers that have to be weaved. I have already asked this question at this link, but I have translated my code in English so that it's maybe easier to help me improve it.

It's for an assignment for a course I'm currently following:

Traveler, if riches are to be achieved, the solution only has to be weaved.
5,4 4,5 8,7
Weave 6,3 3,2 9,6 4,3
Weave 7,6
Weave 9,8
Weave 5,5 7,8 6,5 6,4

I have to start with the coordinates on the first row, weave the coordinates of the second row through the first row, then weave the coordinates of the third row through the resulting row etc. Note, if two rows of unequal length have to be woven, the two rows are woven as far as possible. After the elements of the shortest row have been exhausted, the row is completed by adding the remaining elements of the longest row.

The input is this (my code already returns the desired output):

5,4 4,5 8,7=6,3 3,2 9,6 4,3=7,6=9,8=5,5 7,8 6,5 6,4

The output has to be like this:

6,4
6,5
10,8
8,8
8,6
7,5
7,3
7,4
5,5
4,2
9,7
10,6
5,3

Coordinate.py

class Coordinate:
    def __init__(self, x_coord, y_coord):
        self.x_coord = x_coord
        self.y_coord = y_coord

    def calculate_new_coord(self):
        self.x_coord += 1
        self.y_coord += 0
        return self.x_coord, self.y_coord

CoordinateRow.py

class CoordinateRow:
    def __init__(self, row):
        self.row = row

    def append(self, coord):
        self.row += [coord]

    def extend(self, row):
        for coordinate in row:
            self.row += [coordinate]

    def weave(self, weaveRow):
        result = CoordinateRow([])
        for i in range(len(self.row)):
            if i < len(self.row):
                result.append(self.row[i])
            if i < len(weaveRow.row):
                result.append(weaveRow.row[i])
        if len(weaveRow.row) > len(self.row):       #Als 2e rij(te weaven door 1e rij) groter dan 1e rij(bestaande rij)
            result.extend(weaveRow.row[len(self.row):])  #voeg het verschil toe aan result
        return result

Excerpt of the main code

file_input = file.read()
strip_file = file_input.strip()
splits_file = strip_file.split("=")

from Coordinate import Coordinate
from CoordinateRow import CoordinateRow

def get_weaved_rows(splits_bestand):
    rows = []
    for i in range(len(splits_bestand)):
        rows += [CoordinateRow(splits_bestand[i].split())]
    previous_row = rows[0]

    for row in rows[1:]:
        previous_row = previous_row.weave(row)
    return previous_row

def get_new_coordinates(weaved_rows):
    for coordinate in weaved_rows.row:
        current_coordinates = Coordinate(int(coordinate[0]), int(coordinate[2])) #coordinaat x[0] en y[2] worden int(x,y)
        new_coordinates = current_coordinates.calculate_new_coord() #coordinaten (x,y) na verwerking
        print '%d,%d' %(new_coordinates[0], new_coordinates[1])

weaved_rows = get_weaved_rows(splits_file)
get_new_coordinates(weaved_rows)