SASS + Compass - File Structure and @Import order I recently started using SASS and Compass in my projects. So far I am using the file structure shown below.

  sass/
    |
    |– base/
    |   |– _reset.scss       # Reset/normalize
    |   |– _typography.scss  # Typography rules
    |   ...                  # Etc…
    |
    |– components/
    |   |– _buttons.scss     # Buttons
    |   |– _carousel.scss    # Carousel
    |   |– _cover.scss       # Cover
    |   |– _dropdown.scss    # Dropdown
    |   |– _navigation.scss  # Navigation
    |   ...                  # Etc…
    |
    |– helpers/
    |   |– _variables.scss   # Sass Variables
    |   |– _functions.scss   # Sass Functions
    |   |– _mixins.scss      # Sass Mixins
    |   |– _helpers.scss     # Class & placeholders helpers
    |   ...                  # Etc…
    |
    |– layout/
    |   |– _grid.scss        # Grid system
    |   |– _header.scss      # Header
    |   |– _footer.scss      # Footer
    |   |– _sidebar.scss     # Sidebar
    |   |– _forms.scss       # Forms
    |   ...                  # Etc…
    |
    |– pages/
    |   |– _home.scss        # Home specific styles
    |   |– _contact.scss     # Contact specific styles
    |   ...                  # Etc…
    |
    |– vendors/
    |   |– _bootstrap.scss   # Bootstrap
    |   |– _jquery-ui.scss   # jQuery UI
    |   ...                  # Etc…
    |
    |
    `– main.scss             # primary Sass file

I am happy with the file structure (unless anyone would like to comment on how it could be improved)

My issue is: I am not entirely sure what the best practice is for ordering my @Imports in Primary SCSS file.

I was wondering if anyone could advise me on the best way to import.

I have not yet put together my imports for this new file structure, yet I will show my imports for a previous project.

Previous Project's Primary SCSS file:

@import "partials/defaults";
@import "partials/typography";
@import "partials/grids";
@import "partials/buttons";
@import "partials/headers";
@import "partials/footers";

I want to know which practice is best for organizing my new file structure.

Any help or advice is appreciated.

Your way works, but it is not very scalable, since you have to compile all the sass files every time you make a change, this is time consuming when the project gets bigger.

here you watch all the files via grunt/gulp, but only compile the _watchables, the _procompiled file is compiled upon start of server only, not during file watch.

when building for production, use build.scss to build the final css file, the build contains the watchables and precompiled files.

the _globals file will contain global configurations, styleguide variables, and functions/mixins. the global file does not have css in it, only utilities and functions, and is imported in both watchables and precompiled files.

Structure

.style
├── build.scss
├── _globals.scss
├── _watchables.scss
├── _precompiled.scss
├── vendors
|   ├── index.scss
|   └── _bootstrap.scss
├── helpers
|   ├── index.scss
|   └── _variables.scss

build.scss

@include '_globals.scss';
@include '_precompiled.scss';
@include '_watchables.scss';

_precompiled.scss

//contains vendor files and other unchanged scss files.
@include '_globals.scss';
@include 'vendor/_index.scss';

_watchables.scss

//contains the files you want to build everytime you save
@include '_globals.scss';
@include 'pages/homepage.scss';

any index.scss file

//include everything in the folder.
@include '_bootstrap.scss';

I developed this way while working on a big project with my company, the build time got reduced from 8ms per file save to less than a second. i was compiling only the pages folder in my watchables.scss file, since the rest of the files are almost always stable, but sometimes i include a component in my watchables to develop the component then put it back to the precompiled file.


Scaling the last column in a table (with input) to match the container I recently ran in to a problem with the presentation of data related to a graph. Each series of data has values that define the 'curve'. There can be a lot of these values, and I decided that there was not enough space in the 'legend' to include all the details for the curve. I decided to have a 'details' area, and users could select a curve/series, and the details would be displayed in an area under the graph. This is because there would otherwise be too much data to show in the legend.

The details consist of 4 items, a colour "patch", a series name, the series accuracy, and the data points in the series. A table is what I chose to display these values in.

I want the details area to occupy the base of the screen underneath the graph, and to grow/shrink as the chart grows/shrinks. The last column in the table, the data points, are the largest part of the data, and would 'flood' the area. I want to make it possible to select all the data, but not necessarily make it all visible, a scrolling system would be fine.

In essence, I have this:

What I want reviewed in this question, though, is just the dynamic nature of the 4-column, 1-row table at the bottom, this:

Although the table scales well when the screen-size changes, I believe there must be a better way to implement it.

Here is my extraction of the relevant code, with some test data:

.container {
    width: 80%;
    margin: 0 auto;
    border: 2px solid black;
}

#dummy {
    width: 100%;
    background-color: lightgreen;
}

.details {
    width: 100%;
    border-collapse: collapse;
}

.details td {
    border: 1px black solid;
    padding: 3px;
}

.details td:last-child {
    width: 100%;
    background-color: lightblue;
    padding-right: 7px;
}

.details td:last-child input {
    width: 100%;
}

text to show where a graph would be

    Manual visualization

          Series
          <input id="seriesName" type="text" size="15" readonly="readonly" value="Manual Sizing" >

          RSquared
          <input id="seriesRSquare" type="text" size="10" readonly="readonly" value="0.98765432" >

          Description
          <input id="seriesDetail" type="text" readonly="readonly"
            value="[1,23],[2,20],[4,20],[8,21],[16,23],[32,22],[64,26],[128,28],[256,41],[512,55],[1024,81],[2048,136],[4096,244],[8192,474],[16384,959],[32768,1987],[65536,3613],[131072,6957],[262144,14250],[524288,28215],[1048576,55882],[2097152,116210],[3145728,175000],[4194304,229976],[5242880,291501],[6291456,347649],[7340032,399349],[8388608,485512]">

My specific concerns for this are:

The 'input' in the last column has width: 100% because otherwise it is too small. The input area unfortunately extends past the td border though, so I have had to add a manual padding of 7 px to the right side of the td to make it work. This seems counter-intuitive
the use of read-only input members allows the data to be shown, and scrolled-through, if needed, but is it the 'right way'?

I am open to any suggestions on how to best present this data.

The 7px padding issue can be solved by adding box-sizing: border-box to the input. That'll make the input's 100% width include the input's border and padding.

As for using a read-only input, I'd say that's a fine solution - at least for the data. Besides scrolling without requiring a scrollbar, it also let's you use a select all command, without it selecting the entire page.

The series name and r2 stuff doesn't need to be labels and inputs, though. They can be spans if you want to style their values, but basically I'd suggest something like this:

  Series

  Manual Sizing

The trick, then, is to add the following to .details td:

width: 1%;
white-space: nowrap;

This will prevent the text wrapping on the space in "Manual Sizing", but the explicit break tag is still respected. And, because the cell is set to 1% width (or some other low, low value), it'll shrink to its smallest size, leaving more room for the data.

Again, if you use spans to separately style name and value within the two cells, you can apply the nowrap rule to the spans alone, while the 1% width can remain on the enclosing  to squish it.

In the end I get:

#dummy {
    width: 100%;
    background-color: lightgreen;
}

.details {
    width: 100%;
    border-collapse: collapse;
}

.details td {
    border: 1px black solid;
    padding: 3px;
    width: 1%;
    white-space: nowrap;
}

.details td:last-child {
    width: 100%;
    background-color: lightblue;
}

.details td:last-child input {
    box-sizing: border-box;
    width: 100%;
}

text to show where a graph would be

    Manual visualization

          Series

          Manual Sizing

          RSquared

          0.98765432

          Description

          <input id="seriesDetail" type="text" readonly
            value="[1,23],[2,20],[4,20],[8,21],[16,23],[32,22],[64,26],[128,28],[256,41],[512,55],[1024,81],[2048,136],[4096,244],[8192,474],[16384,959],[32768,1987],[65536,3613],[131072,6957],[262144,14250],[524288,28215],[1048576,55882],[2097152,116210],[3145728,175000],[4194304,229976],[5242880,291501],[6291456,347649],[7340032,399349],[8388608,485512]">

I've dropped the  tag for the data input, but that's just me.

Lastly, the readonly attribute doesn't need to have a value; it just needs to be "mentioned", so to speak. It's presence is its value. Giving it a value is fine too, of course. Just thought I'd mention it.

The downside of squishing the cells is of course that the layout will shift a little for different content. E.g. a longer series name will push things around.

Again, if you use a span, you can add something like this to limit its size:

display: inline-block; /* allows the span to respect a max-width */
max-width: 100px; /* or something */
overflow: hidden;
text-overflow: ellipsis;

That'll truncate the text to fit 100px (e.g. you'd get "Manual S…" or something).

The gotcha is that the text-overflow literally chops off some of the text, so it's no longer selectable. On my screen the snippet below shows the series name as "Manual…", while selecting it and copying only copies "Manual" (leaving out both the truncated text, and the ellipsis that replaced it).

.details {
    width: 100%;
    border-collapse: collapse;
}

.details td {
    border: 1px black solid;
    padding: 3px;
    width: 1%;
    white-space: nowrap;
}

.details td:last-child {
    width: 100%;
    background-color: lightblue;
}

.details td:last-child input {
    box-sizing: border-box;
    width: 100%;
}

.details td span {
    display: inline-block;
    max-width: 64px;
    overflow: hidden;
    text-overflow: ellipsis;
}

          Series

          Manual Sizing

          RSquared

          0.98765432

          Description

          <input id="seriesDetail" type="text" readonly
            value="[1,23],[2,20],[4,20],[8,21],[16,23],[32,22],[64,26],[128,28],[256,41],[512,55],[1024,81],[2048,136],[4096,244],[8192,474],[16384,959],[32768,1987],[65536,3613],[131072,6957],[262144,14250],[524288,28215],[1048576,55882],[2097152,116210],[3145728,175000],[4194304,229976],[5242880,291501],[6291456,347649],[7340032,399349],[8388608,485512]">

Edit: Thinking about it some more, you probably should go for having a separate table header section:

      Series
      RSquared
      Description

      Manual Sizing
      0.98765432
      data...

It's more semantically correct, and it also gives you better opportunities to apply styling without requiring extra span elements or classes or what have you.

Depending on your setup, you could even add all the series as rows, and simply hide/show them as needed.


Parsing integers safely Background

I'm writing user input validation for a client-side JavaScript web application. Users enter numerals representing an integer into an <input>. As part of validation, the application must check that parseInt(input.value, 10) will result in the integer represented by the user's input.

In JavaScript, all numbers are floating-points. Within the interval [-253, 253], all integers have exact representations. The challenge is to guarantee that the user has provided a number within the interval. parseInt() doesn't work:

// Yields true
parseInt('9007199254740993', 10) === 9007199254740992;

I'm looking for any feedback. Firstly, correctness, then performance.

Current Solution

var isSafeIntegerString = function() {
  'use strict';

  // The digits of the greatest and least safe integers, 2**53 and
  // -2**53 respectively.
  var limDigits = [9, 0, 0, 7, 1, 9, 9, 2, 5, 4, 7, 4, 0, 9, 9, 2];

  // The number digits in the safe integer limits.
  var limLength = limDigits.length;

  // The structure of safe integers.
  //
  //   ^...$  The entire string must match the structure
  //
  //   [-+]?  May be preceded by either a '-' or a '+'
  //
  //   0*     May have leading zeros
  //
  //   (\d{1, limLength}) Must contains between 1 and limLength digits

  var safeIntegerStructure = new RegExp('^[-+]?0*(\\d{1,' + limLength + '})$');

  return function(str) {
    // If str is not a string, it cannot be a safe integer string.
    if (Object.prototype.toString.call(str) !== '[object String]') {
      return false;
    }

    // If str doesn't have the structure of a safe integer string, it
    // can't be one.
    var match = str.match(safeIntegerStructure);
    if (match === void 0) {
      return false;
    }

    // str has a safe integer structure. The RE captured the
    // significant digits (i.e., without the sign or leading zeros).
    var numerals = match[1];
    var numeralsLength = numerals.length;

    // If str contains less significant digits than the limit, it is
    // less and therefore is safe.
    if (numeralsLength < limLength) {
      return true;
    }

    // If str contains more significant digits than the limit, it is
    // greater and therefore is not safe.
    if (numeralsLength > limLength) {
      return false;
    }

    // str and the limit contain the same number of digits. So, compare
    // each digit, starting from the most significant.
    for (var i = 0; i < numeralsLength; ++i) {
      var digit = parseInt(numerals.charAt(i), 10);
      var limDigit = limDigits[i];
      if (digit < limDigit) {
        return true;
      }
      if (digit > limDigit) {
        return false;
      }
    }

    // str is equal to a safe integer limit.
    return true;
  };
}();

Tests

(function() {
  var test = function(str, isSafe) {
    console.log(str, isSafe, isSafeIntegerString(str));
  };

  var schemata = [
    [                 '0', true ],
    [                '-0', true ],
    [                 '1', true ],
    [                '-1', true ],
    [   '900719925474099', true ],
    [   '900719925474099', true ],
    [  '9007199254740991', true ],
    [  '9007199254740991', true ],
    [  '9007199254740992', true ],
    [ '-9007199254740992', true ],
    [ '09007199254740992', true ],
    ['-09007199254740992', true ],
    [  '9007199254740993', false],
    [ '-9007199254740993', false],
  ];

  for (var i = 0; i < schemata.length; ++i) {
    var schema = schemata[i];
    test(schema[0], schema[1]);
  }
}());

// The digits of the greatest and least safe integers, 2**53 and
// -2**53 respectively.
var limDigits = [9, 0, 0, 7, 1, 9, 9, 2, 5, 4, 7, 4, 0, 9, 9, 2];

As Flambino mentioned already it's probably not a good idea to store the actual digits of 253 in the source code. At least it's confusing. It's hard to tell if there's a typo. I would use a math function like Math.pow since it's so easy to read and does exactly what the comment says:

var lim = Math.pow(2, 53);
var limDigits = String(lim);

var safeIntegerStructure = new RegExp('^[-+]?0*(\\d{1,' + limLength + '})$');

I suggest using the RegExp constructor as little as possible because it's confusing. It's only necessary if you need to use dynamic expressions. Otherwise it adds much clutter from the escape sequences and string concatenations. In fact in this case you wanted to have a dynamic expression. But it's not really necessary. You can check the length of the capture group way easier.

var safeIntegerStructure = /^[-+]+0*(\d+)$/;

// If str is not a string, it cannot be a safe integer string.
if (Object.prototype.toString.call(str) !== '[object String]') {
  return false;
}

This looks pretty good. Depending on the use of the function it might make sense. And I have too little experience to argue with it. It's not even that important since I think <input> only ever has string values. Still you might consider to accept other types and coerce them to a string. I think it's pretty easy to read and to me it seems to be the usual approach in many libraries etc. when a function expects a string.

str = String(str);

Of course if you only want to accept strings this doesn't work. And since typeof str === 'string' doesn't work with String objects your way of using Object.prototype.toString looks like the best approach.

var match = str.match(safeIntegerStructure);

I've never used String#match this way. In my opinion the real purpose of this method is to get an array of all matches with a global regexp. For obtaining a single match I use RegExp#exec. But I suppose this might be just a personal preference since both versions have the exact same results.

var match = safeIntegerStructure.exec(str);

if (match === void 0) {
  return false;
}

I think this is a bug. Both String#match and RegExp#exec should return null when there is no match. But void anything is undefined. On the other hand when there is a match they return an array. I found checking the truth value to be the easiest to write and review.

if (!match) {
  return false;
}

var numerals = match[1];
var numeralsLength = numerals.length;
if (numeralsLength < limLength) {
  return true;
}
if (numeralsLength > limLength) {
  return false;
}
for (var i = 0; i < numeralsLength; ++i) {
  var digit = parseInt(numerals.charAt(i), 10);
  var limDigit = limDigits[i];
  if (digit < limDigit) {
    return true;
  }
  if (digit > limDigit) {
    return false;
  }
}

The for-loop iterates through the individual digits to compare them and stops at the first difference. Essentially this is exactly the same thing as the built-in string comparison operators do. So after making sure the entered number and the limit have the same number of digits you can compare them lexicographically:

var digits = match[1];
if (
  limDigits.length < digits.length ||
  limDigits.length === digits.length && limDigits < digits
) {
    return false;
}

Actually though it's a matter of opinion if the range of safe integers should be defined as [-253;+253] or [-(253-1);+(253-1)]. For example the ES6 draft defines Number.MAX_SAFE_INTEGER as 253-1. This makes sense considering that 253 already is ambiguous:
Math.pow(2, 53) === Math.pow(2, 53) + 1

Using this alternative definition of "safe integer" you could safely use parseInt (or simple type coercion), removing the need for lexicographic comparison.

var lim = Math.pow(2, 53) - 1;
var value = +match[1];
if (lim < value) {
  return false;
}

So ultimately the function could become very short and therefore even easier to read in my opinion:

function isSafeInteger(str) {
  var match = /^[-+]?0*(\d+)$/.exec(String(str));
  return !!match && +match[1] < Math.pow(2, 53);
}


Clean way to remove an identical nested object in javascript can you give me some feedback about my approach to remove an idential element from following data structure?
const items = {
  'Sun Mar 07 2021': [
     { id: 2 },
     { id: 1 }
  ],
  'Sat Mar 06 2021': [
     { id: 1 } // remove me
  ]
}

const id = 1 // filter by id 1
const newDate = 'Sun Mar 07 2021' // filter by newDate

let oldDate = ''
// Find the duplicate date and
// save it in oldDate to splice it afterwards
Object.keys(items).forEach(date => {
  items[date].forEach(item => {
    const match = item.id === id
    if (match && date !== newDate) {
      oldDate = date
    }
  })
})

const idx = items[oldDate].findIndex(el => el.id === id)
// remove the old item from matched array
if (oldDate) items[oldDate].splice(idx, 1)

I think it can be simplified or solved differently. Unfortunately I can't get any further, do you have any ideas?

I think it can be simplified or solved differently.

That's good intuition. That's called a code smell. Something "smells" funny, off, or wrong but not sure what it is. Pay attention to that feeling!!

Unfortunately I can't get any further

This is an even stronger code smell.

do you have any ideas?

Re-examine the date object design.

date and IDs should be in one object
Put the date objects into an array. Array is designed for easy handling of multiple objects.
Using Array's provided methods should eliminate external variables and functions.

This code demonstrates overall structural changes after fixing the objects. Algorithm details not shown.
const dates = [
  { date : 'Sun Mar 07 2021',
     IDs : [ 1, 2 ]
  },
  { date : 'Sat Mar 06 2021',
     IDs : [ 1 ]
  }
]

const dupeDate = { date : 'Sun Mar 07 2021', IDs : [ 1 ] }

dates.forEach( date => {

  if( date.date === dupeDate.date ) return;

  if( date.IDs.includes( dupeDate.IDs[0] )) {
    // algorithm details here. Should be function calls as much as possible,
    // not dozens of lines of nested, nested code.
  }
});


Javascript browser charset rendering detection I am attempting to polyfill the broken character encoding system in javascript. For example, characters such as , have a length of 2 and are treated as 2 separate characters in regular expressions when they should have a length of 1 and be treated as a single character in regular expressions. This may not seem important, but I don't want to have a programming nightmare when I deploy my site multilingually with asian and african languages. I am attempting to polyfill the whole thing, but since I can't find any articles, this is the best I can do. I am attempting to detect the encoding based on the size of different characters since that is what I am, in essence, doing: polyfilling the size of the characters.

<script>
 // Charset Polyfiller
 let   charsettransfer = Object.create(null),
        maxUniChar = String.fromCodePoint(0x10ffff);
  let   needsPolyfill = true;

  if ('\xE2'.length === '\xE1'.length*2){
    charsettransfer.to = 'GB 18030';
    if ('\xE1'.length === 2){
      charsettransfer.from = 'ascii';
    } else if ('\xE1'.length === 1) {
      charsettransfer.from = 'UCS-16';
    }
  } else if ('\x7f'.length === 1 && '\x80'.length === 2){
    charsettransfer.from = 'ascii';
    charsettransfer.to = 'utf-7';
  } else if (maxUniChar.length === 4){
    charsettransfer.from = 'ascii';
    if ('\0'.length <= 1){
      charsettransfer.to = 'utf-8';
    } else if ('\u9999'.length === 3 && '\0'.length === 3){
      charsettransfer.to = 'utf-20';
    } else if ('\u9999'.length === 4) {
      charsettransfer.to = 'utf-32';
    } else {
      charsettransfer.to = 'utf-16';
    }
  } else if (maxUniChar.length === 3) {
    charsettransfer.from = 'ascii';
    charsettransfer.to = 'utf-24';
  // utf-24 is my own nickname for when a browser uses only the minimal
  // 24 bits for utf-32 (like python)
  } else if (maxUniChar.length === 2) {
    charsettransfer.from = 'ucs-16';
    charsettransfer.to = 'utf-16';
  } else if (maxUniChar.length === 1) {
    charsettransfer.from = 'ucs-32';
    charsettransfer.to = 'utf-32';
    needsPolyfill = false;
  }

 /*if ('\u9999'.length === 3){
  charsettransfer.from = 'ascii';
  charsettransfer.to = 'utf-8';
 } else if ('\0'.length === 4) {
  charsettransfer.to = 'utf-32';
    charsettransfer.from = 'ascii';
 } else if ('\0'.length === 3) {
  charsettransfer.to = 'utf-24';
  charsettransfer.from = 'ascii';
 } else if ('\0'.length === 2) {
  charsettransfer.to = 'utf-16';
  // utf-24 is my own nickname for when a browser uses only the minimal
  // 24 bits for utf-32 (like python)
  charsettransfer.from = 'ascii';
 } else if ('\uD83D\uDE12'.length === 1){
  charsettransfer.from = 'ucs-32';
  charsettransfer.to = 'utf-32';
 }*/

  document.write('Your browser is attempting to render ' + charsettransfer.to
       + ' in ' + charsettransfer.from + '.\<br /> Your browser needing the polyfill is ' + needsPolyfill + '.');
</script>

How did I do? Am I on the right track? Are there any things I could add? Any improvements I could make? Any bugs that should be fixed? (sorry if i'm ranting, but i'm really concerned about this segment of code because LOTS of days of work are gonna depend on it, and I can't seem to find any helpful articles reguarding it).

Just don't. Standard practice is to use UTF-8 everywhere possible, and get rid of all other encodings. Especially if you have a multilingual system, dealing with multiple legacy encodings is a huge headache — just like this code above.


Stopwatch class without using System.Diagnostics in C# Design a class called Stopwatch. The job of this class is to simulate a stopwatch. It should
  provide two methods: Start and Stop. We call the start method first, and the stop method next.
  Then we ask the stopwatch about the duration between start and stop. Duration should be a
  value in TimeSpan. Display the duration on the console.
  We should also be able to use a stopwatch multiple times. So we may start and stop it and then
  start and stop it again. Make sure the duration value each time is calculated properly.
  We should not be able to start a stopwatch twice in a row (because that may overwrite the initial
  start time). So the class should throw an InvalidOperationException if its started twice.

  The aim of this exercise is to make you understand that a class should be
  always in a valid state. We use encapsulation and information hiding to achieve that. The class
  should not reveal its implementation detail. It only reveals a little bit, like a blackbox. From the
  outside, you should not be able to misuse a class because you shouldn’t be able to see the
  implementation detail.

That is the information given to me from the tutorial I am taking to teach myself C#.  I have completed this and looking for ways to improve my code and/or learn something new here.  I have tested this and to my knowledge is working as expected.  Any help is appreciated.

using System;

namespace ExerciseOne
{
    public static class Stopwatch
    {
        private static DateTime TimeStart { get; set; }
        private static DateTime TimeStop { get; set; }
        private static bool isStarted = false;
        private static bool isStopped = false;

        private static void StartTimer(DateTime start)
        {
            if (isStarted)
            {
                throw new InvalidOperationException("Unable to start a stopwatch twice in a row.");
            }
            else
            {
                isStarted = true;
                isStopped = false;
                TimeStart = start;
            }
        }

        private static void StopTimer(DateTime stop)
        {
            if (isStopped)
            {
                throw new InvalidOperationException("Unable to stop a stopwatch twice in a row.");
            }
            else
            {
                isStarted = false;
                isStopped = true;
                TimeStop = stop;
            }
        }

        private static string ElapsedTimer() => (TimeStop - TimeStart).ToString();

        private static void Begin()
        {
            StartTimer(DateTime.Now);
            System.Console.WriteLine(" - Stopwatch has begun.");
        }
        private static void End()
        {
            StopTimer(DateTime.Now);
            Console.WriteLine($" - Stopwatch has stopped. Elapsed Time: {ElapsedTimer()}");
        }

        public static void RunProgram()
        {
            Console.WriteLine("Stopwatch program.");
            Console.WriteLine("Type \"S\" to start the program. Type \"T\" to stop the program. Type \"E\" to end the program.");

            while (true)
            {
                ConsoleKeyInfo cki = Console.ReadKey(false);

                if (cki.Key == ConsoleKey.E)
                {
                    Console.WriteLine(": \"E\" key was pressed.  Progam exited.");
                    return;
                }
                else if (cki.Key == ConsoleKey.S)
                {
                    Begin();
                }
                else if (cki.Key == ConsoleKey.T)
                {
                    End();
                }
                else
                {
                    Console.WriteLine("\nPlease type either \"S\" to start the program, \"T\" to stop the program, \"E\" to end the program.");
                }
            }
        }
    }
}

using System;

namespace ExerciseOne
{
    class Program
    {
        static void Main() => Stopwatch.RunProgram();
    }
}

public static void RunProgram()
{
   ....
}

Why do you run the application as a method on the Stopwatch class it self?

You have made all the methods (StartTimer(), StopTimer()) private. This means that they only can be run from your RunProgram method, which occupy the main thread of the program and measures nothing. This set up makes the entire effort rather useless. I would expect a stopwatch being able to measure something in a way like:

  Stopwatch stopwatch = Stopwatch.StartNew();

  // TODO: execute something you want to measure
  Thread.Sleep(5000);

  stopwatch.Stop();

  Console.WriteLine($"Duration: {stopwatch.Duration}");

    private static bool isStarted = false;
    private static bool isStopped = false;

These flags can be combined into one isRunning, used like:

    private static void StartTimer(DateTime start)
    {
        if (isRunning)
        {
            throw new InvalidOperationException("Unable to start a stopwatch twice in a row.");
        }
        else
        {
            isRunning = true;
            TimeStart = start;
        }
    }

and

    private static void StopTimer(DateTime stop)
    {
        if (!isRunning)
        {
            throw new InvalidOperationException("Unable to stop the stopwatch because it is not running.");
        }
        else
        {
            isRunning = false;
            TimeStop = stop;
        }
    }

    private static void Begin()
    {
        StartTimer(DateTime.Now);
        System.Console.WriteLine(" - Stopwatch has begun.");
    }

You shouldn't write to the console in class methods of any object, unless it's explicitly meant to be a console application. The above message is useless in a WinForm application.

  private static void StartTimer(DateTime start)

I don't se why you have a start time as argument to StartTimer. Why not just call DateTime.Now inside it? And likewise in StopTimer.

You were told to provide the result as a TimeSpan, but you actually return a string:

  private static string ElapsedTimer() => (TimeStop - TimeStart).ToString();

  public static class Stopwatch

The major problem with your implementation is though, that you make it static. That means that you only can run one "instance" at a time. In this way you aren't able to measure on two treads at the same time - or have nested measurements.

I would remove all the static stuff and only have one static method - starting a new Stopwatch instance, that then can be stopped by calling Stop() on the returned object like I showed above. So the public interface of the object would be:

  public class Stopwatch
  {
    public TimeSpan Duration { get; }

    public void Start() { }
    public void Stop() { }
    public static Stopwatch StartNew() { }
  }

I think you have misunderstood the concepts of "encapsulation and information hiding" slightly. An object must have a public interface through which clients can communicate with it, but they shouldn't be allowed to manipulate the objects internal state (for instance the StartTime member of your watch) - only through the public interface. The client shouldn't know about how you measure the time internally, they are only interested in the final result, when they stop the watch by calling Stop().


Creating a 2-D array whose first elements come from a 1-D array I am trying to full one dimensional array in two dimensional array in Java.I did it using this way, is there another way better than this? .

public double[][] getResult(double[] data, int rowSize) {
int columnSize = data.length;
double[][] result = new double[columnSize][rowSize];
for (int i = 0; i < columnSize; i++) {
    result[i][0] = data[i];
}
return result;
}

For the most part, what you are doing is fine (like @Ashwin commented on your question).

About the only thing I really don't like is the name of the function getResult. That name is just really useless. How about convert2D or something? Your other variable names are well put together, and make sense.

Another issue you may run in to is if someone specifies bad input values. Your code will fail with a NoSuchElementException if someone sets a rowSize of 0.

From a performance perspective, I expect that your code is pretty much as fast as it can be too - in a single-threaded process.

Using a Java 8 stream you can possibly make the process a bit more parallel, but it would be more complicated to read. Still, I thought it would be an interesting thing to see..... though, in a production system, I would be happy to see your code instead (i.e. the following code is just a thought, not a recommendation):

public static double[][] convert2D(double[] data, int rowSize) {
    return IntStream.range(0, data.length)
        .parallel()
        .mapToObj(i -> {
            double[] row = new double[rowSize];
            row[0] = data[i];
            return row;
        })
        .toArray(s -> new double[s][]);
}

The above has the advantage that each row may be created in a different thread, and "all CPUs" on your system will be creating rows. I did some performance benchmarks, and, if the rowSize is small (10 or so) then your code is faster. If the row size starts getting larger (like 1000 or so) then the parallel code starts getting faster.

Even though the stream code can sometimes be faster, I would still probably prefer to use your code.

If you want raw numbers (Note the unit for the 10-size row is MicroSeconds, and for 1000 size row is MilliSeconds), this is the timing for row-size of 10 for 1000 rows, run 1000 times:

Task 1d2d -> Single: (Unit: MICROSECONDS)
  Count    :      1000      Average  :   62.9370
  Fastest  :   41.4460      Slowest  : 1383.5230
  95Pctile :   95.9190      99Pctile :  124.3400
  TimeBlock : 91.553 72.914 55.230 65.829 66.551 48.998 60.405 49.428 63.745 54.717
  Histogram :   887   109     3     0     0     1

Task 1d2d -> Stream: (Unit: MICROSECONDS)
  Count    :       1000      Average  :   145.3900
  Fastest  :    20.9210      Slowest  : 85596.0480
  95Pctile :   115.2600      99Pctile :   317.3620
  TimeBlock : 983.900 101.962 61.807 49.069 57.070 36.698 32.841 34.045 45.761 50.754
  Histogram :   519   339   116    17     4     0     4     0     0     0     0     1

This is the timing for row-size 1000 for 1000 rows run 1000 times:

Task 1d2d -> Single: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   1.3570
  Fastest  :   1.1601      Slowest  :   7.7698
  95Pctile :   2.5799      99Pctile :   4.2958
  TimeBlock : 2.175 1.387 1.284 1.225 1.217 1.244 1.253 1.314 1.260 1.211
  Histogram :   948    44     8

Task 1d2d -> Stream: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   0.9919
  Fastest  :   0.5680      Slowest  :  92.7422
  95Pctile :   2.2405      99Pctile :   4.0231
  TimeBlock : 2.672 1.074 0.742 0.811 0.763 0.773 0.762 0.733 0.772 0.817
  Histogram :   932    19    45     3     0     0     0     1


Form with a country list statically or dynamically generated I want to create a form with a country drop down list so I can just google and get all the countries but the question should I just encode it statically or generate dynamically with PHP. (Note it doesn't have to be necessary country list just any static list with lots of data)

HTML Example:

<select>
  <option value="AF">Afghanistan</option>
  <option value="AX">Åland Islands</option>
  <option value="AL">Albania</option>
  ...
</select>

or use php array i.e.

$countries = array (
    'AF' => 'Afghanistan',
    'AX' => 'Åland Islands',
    'AL' => 'Albania',
    ...
    );

and generate html

<!--Method 1-->
<select>
  <?php foreach($countries as $id => $country) echo "<option value='$id'>$country</option>\n" ?>
</select>

Also which method of generating is preferred or is more readable?

<!--Method 2-->
<select>
  <?php foreach($countries as $id => $country):?>
  <option value="<?php echo $id; ?>"><?php echo $country; ?></option>
  <?php endforeach; ?>
</select>

And finally should I escape variables with htmlspecialchars even though I know the output will be valid?

This depends on your plans for maintaining the software. If it will not be maintained, it does not matter much. If it will be maintained irregularly and manually, not a big issue unless the country code list is used elsewhere, too, e.g. in a database where you store some submitted information or that contains some data per country. But other things being equal, it is better to generate a large dropdown from a table rather than hard-code it. And if the software will be regularly maintained by checking, among other things, the country list and country names against a reliable source, then a table is surely better. It is easier to generate just a table from the reference data.

Note that reliable and useful data can be difficult to find and the set of countries will change (and is subject to political debate). In your example, the second entry does not refer to a country but to an autonomous area. There are definitions of “country codes” that include many non-country entries for various purposes.


Is there a better way to call the same method with different parameters? I have a method(C#) which takes an XmlNodeList and a String and saves the xml data into a database. That code isn't the problem (at least for the moment), but because I have multiple XmlNodeLists, each needing a different String (the heading), I end up with code like

saveToDB(students, "Students");
saveToDB(teachers, "Teachers");
saveToDB(workers, "Workers");

...etc, there's about 8 of those in total. It all works okay, but I wonder if there's a better way to call the function, rather than doing it 8 times? I guess I could wrap all of the data into an object, but I'd still have to set it up, and pull the data out before and afterwards, so that's surely just moving the problem elsewhere? Or is there simply no real way around this, and the issue lies with how I've approached this method in the first place?

I look forward to your responses.

I think you could create a new saveToDB method that requires a Dictionary<string, XmlNodeList> inside this new method you could cycle through the Keys (string) and for each one call the current saveToDB(string, XmlNodeList).

Yes, it only move your problem: you've to prefill the dictionary, but I really think there's no other options... at one point you HAVE to enumerate your datas.


Nested LINQ Nightmare, calculating %completed This code horrifies and scares me. I wrote this.

public IQueryable<StudentTrack> StudentTracks(int employeeId)
{

    IQueryable<StudentTrack> EducationPortalStudentTracks =
        from studentTrack in _dbContext.EducationPortalStudentTracks
        join track in _dbContext.EducationPortalTracks on studentTrack.TrackId equals track.Id
        orderby track.Id
        where studentTrack.EmployeeId == employeeId
        select new StudentTrack
        {
            Id = studentTrack.Id,
            TrackId = studentTrack.TrackId,
            Name = track.Name,
            Deadline = studentTrack.Deadline,

            // this is where it gets bad
            PercentComplete = (from doesntMatter in _dbContext.EducationPortalStudentCourses
                               let courses = (from studentCourse in _dbContext.EducationPortalStudentCourses
                                              join studentTrack_ in _dbContext.EducationPortalStudentTracks on studentCourse.TrackId equals studentTrack_.TrackId
                                              where studentTrack.Id == studentTrack.Id && studentTrack.EmployeeId == studentCourse.EmployeeId
                                              select studentCourse)
                               select courses.Where(x => x.Status == true).Count() * 100 / courses.Count()).FirstOrDefault()

        };
    return EducationPortalStudentTracks;
}

Let me explain how this fits in to the rest of the application. On the top level, a Kendo Grid control calls an MVC controller for its data. That controller calls another controller, which calls this. So this method returns the data which populates a grid in the UI. That grid lists all of the StudentTracks in the database. In order to return the StudentTracks, this method does a little bit of Linq and returns a series of StudentTrack objects.

So the problem starts with the PercentComplete field. To calculate the value for that field, we first find all of the children StudentCourses. We then figure out how many of the StudentCourses are complete (a.k.a. have True in the Status column) and divide that by the total number of StudentCourses.

Anyway, this is what I came up with. I'm not pleased with it, but I don't know how to do it any better. Any ideas on how I can make this a little more elegant?

Break it down into more methods. StudentTracks has multiple responsibilities, you could extract a private method whose job would be to CalculatePercentCompletion(studentTrack), making your method look like this:

public IQueryable<StudentTrack> StudentTracks(int employeeId)
{
    IQueryable<StudentTrack> EducationPortalStudentTracks =
        from studentTrack in _dbContext.EducationPortalStudentTracks
        join track in _dbContext.EducationPortalTracks on studentTrack.TrackId equals track.Id
        orderby track.Id
        where studentTrack.EmployeeId == employeeId
        select new StudentTrack
        {
            Id = studentTrack.Id,
            TrackId = studentTrack.TrackId,
            Name = track.Name,
            Deadline = studentTrack.Deadline,
            PercentComplete = CalculatePercentCompletion(studentTrack)
        };

    return EducationPortalStudentTracks;
}

Then CalculatePercentCompletion could look like this:

private int CalculatePercentCompletion(StudentTrack studentTrack)
{
    return (from doesntMatter in _dbContext.EducationPortalStudentCourses
            let courses = (from studentCourse in _dbContext.EducationPortalStudentCourses
                           join studentTrack_ in _dbContext.EducationPortalStudentTracks on studentCourse.TrackId equals studentTrack_.TrackId
                           where studentTrack.Id == studentTrack.Id && studentTrack.EmployeeId == studentCourse.EmployeeId
                           select studentCourse)
            select courses.Where(x => x.Status == true).Count() * 100 / courses.Count()).FirstOrDefault();
}

...Which is still horrible.

Why are you using the query syntax? If you have navigation properties on your entities (assuming EF), I find this would be much easier to parse:

public IQueryable<StudentTrack> StudentTracks(int employeeId)
{
    return _dbContext.EducationPortalStudentTracks
                     .Where(studentTrack => studentTrack.EmployeeId == employeeId)
                     .OrderBy(studentTrack => studentTrack.Track.Id)
                     .Select(studentTrack =>
                         new StudentTrack
                         {
                             Id = studentTrack.Id,
                             TrackId = studentTrack.TrackId,
                             Name = studentTrack.Track.Name,
                             Deadline = studentTrack.Deadline,
                             PercentComplete = CalculatePercentCompletion(studentTrack)
                         });
}

In CalculatePercentCompletion the doesntMatter part makes it pretty confusing, I'm not sure but I think this could be equivalent:

private int CalculatePercentCompletion(StudentTrack studentTrack)
{
    var courses = _dbContext.EducationPortalStudentCourses
                            .Where(course => course.TrackId == studentTrack.Id
                                          && course.EmployeeId == studentTrack.EmployeeId)
                            .ToList();
    return courses.Count(course => course.Status == true) * 100 / courses.Count
}

Why the .ToList() call? You want to materialize your query only when you need to - this method needs to know what the courses are for a given studentTrack, in order to count the number of courses with Status == true, multiply that by 100 and divide by the total number of courses.

Your code iterates courses twice, in the two Count() calls.

And the intent is not exactly clear because of the doesntMatter in the from clause, and the .FirstOrDefault() call makes it look like we're looking at an IEnumerable<int> when we're really all materialized at that point and we either have zero or one values selected (if I get this correctly).

The status == true part is confusing. Normally I would have written it as .Where(course => course.Status) to avoid comparing a Boolean with a Boolean value, but Status is really a poor name and doing that would have made it harder to understand what's going on. I suggest you rename Status to whatever IsCompleted, so the where condition can read as .Where(course => course.IsCompleted), which is crystal-clear.

I think exposing IQueryable<T> to your UI is a bad idea. StudentTracks should return an IEnumerable<StudentTrack> instead, your grid should be able to work off that just as well.

I would leave the last Select to Linq-to-Objects, and materialize the query just after the OrderBy call:

public IEnumerable<StudentTrack> GetStudentTracks(int employeeId)
{
    return _dbContext.EducationPortalStudentTracks
                     .Where(studentTrack => studentTrack.EmployeeId == employeeId)
                     .OrderBy(studentTrack => studentTrack.Track.Id)
                     .ToList()
                     .Select(studentTrack =>
                         new StudentTrack
                         {
                             Id = studentTrack.Id,
                             TrackId = studentTrack.TrackId,
                             Name = studentTrack.Track.Name,
                             Deadline = studentTrack.Deadline,
                             PercentComplete = CalculatePercentCompletion(studentTrack)
                         });
}

The problem with exposing IQueryable<T> to your client code, is that you allow that code to modify the SQL being generated, and potentially to break your query with calls that Linq-to-Entities cannot translate to SQL. The grid in your UI doesn't need an IQueryable<T>.


Selecting subset of size k using recursion Sometimes I need to implement recursive algorithms that pass a certain state from one recursive call to another. For example, a greedy subset selection: we have a set of candidate objects, and we select a subset of size k greedily, one-by-one. The choice depends on the already selected objects and some constantly re-computed state. This state (and the set of candidates) can be discarded, once the selection is complete.

type O /* Individual objects */
type S /* Intermediate state */

def selectSubset(candidates: Seq[O], k: Int): Seq[O] =
    selectRec(candidates, Seq[O](), k, initialState(candidates))._2

def selectRec(candidates: Seq[O], acc: Seq[O], k: Int, state: S): (Seq[O], Seq[O], Int, S) =
    if (k > 0 && candidates.nonEmpty) {
        val next = selectNext(candidates, acc, state)
        selectRec(candidates - next, acc + next, k - 1, computeState(state, next))
    } else {
         (null, acc, null, null) /* (Early) termination */
    }

/* Implemented by library users */
def initialState(candidates: Seq[O]): S

def selectNext(candidates: Seq[O], alreadySelected: Seq[O], state: S): O

def computeState(previousState:S, lastSelected:O): S

Is recursion a good choice here?
Is there a neat alternative to Tuple as the return type of the recursive function? E.g. a case class might be more readable. In principle, candidates, i, and state can be merged into a single variable, but that also doesn't seem neat.
How to "express" (early) termination with tuples? We don't care about anything but acc at this point, but nulls look ugly.

Your logic is good, and the API is pretty solid as well. There are a few point that could use some work.

Organization

selectRec can be moved inside of selectSubset to simplify the structure slightly.

It's also tail recursive, so you might as well add the annotation. I cannot recall if this is required, but even if it's not, it's a good habit to get into.

For readability, I'd recommend reversing the if so that the one-liner is in the if clause rather than the else clause. Generally speaking, it's easier to keep track of what part of the code it belongs to, the closer it is to the construct - particularly if there is a bunch of nesting. Here it doesn't make a big difference, but as a matter of course I'd swap them.

Return Types & Misc

As you are forgetting everything except acc when we return, we can actually simplify the return type to just Seq[O].

I'm going to assume that Seq was intended, so candidates - next, acc + next needs to become candidates.filter(_ == next), acc :+ next.

As the name of the trait was dropped from the question, I'm going to use GreedySubset.

Early Termination

What you have marked as an "early termination" is just "termination", it's the base case. Limiting this to the length of candidates isn't really early termination. A similar effect could be achieved by replacing k in the selectRec call inside selectSubset with k min candidates.length.

If you want to the library users to terminate early, which is not a bad idea, one way is to have selectNext return Option[O] rather than just O.

Refactored Version

import scala.annotation.tailrec

trait GreedySubset {
  type O /* Individual objects */
  type S /* Intermediate state */

  def selectSubset(candidates: Seq[O], k: Int): Seq[O] = {
    @tailrec
    def loop(candidates: Seq[O], acc: Seq[O], count: Int, state: S): Seq[O] =
      if (candidates.isEmpty || count <= 0) acc
      else selectNext(candidates, acc, state) match {
        case Some(next) =>
          loop(candidates.filterNot(_ == next),
            acc :+ next,
            count - 1,
            computeState(state, next))
        case None => acc
      }
    loop(candidates, Seq[O](), k, initialState(candidates))
  }

  /* Implemented by library users */
  def initialState(candidates: Seq[O]): S

  def selectNext(candidates: Seq[O], alreadySelected: Seq[O], state: S): Option[O]

  def computeState(previousState:S, lastSelected:O): S
}

Alternate Implementation

Another alternative, which is arguably simpler, is to implement this as a case class with function arguments. This implementation is exactly equivalent to the refactored version above, and is arguably simpler and easier to use.

case class GreedySelector[E,S](
  initialState: Seq[E] => S,
  selectNext: (Seq[E], Seq[E], S) => Option[E], // First argument is candidates
  computeState: (S, E) => S) {

  def selectSubset(candidates: Seq[E], k: Int): Seq[E] = {
    @tailrec
    def loop(candidates: Seq[E], acc: Seq[E], count: Int, state: S): Seq[E] =
      if (candidates.isEmpty || count <= 0) acc
      else selectNext(candidates, acc, state) match {
        case Some(next) =>
          loop(candidates.filterNot(_ == next),
            acc :+ next,
            count - 1,
            computeState(state, next))
        case None => acc
      }
    loop(candidates, Seq[E](), k, initialState(candidates))
  }
}


Compare two Excel sheets by Cell Content This code is a result of a lot of help from this community.
What does it do?
It compares two excel sheets cell by cell and copies the differences into another excel file.

I’m trying to modify the Code so it does the following:

It goes to “Name” and then searches for that name is the other file. If it doesn’t find the file it just copies that entire row including all the columns to the report file (file that is created)
In case it does find the name, then it compares all the columns of that row and if something different it shows the difference in report with color red.

The pictures below show what I'm trying to achieve with this code

Sheet1

Sheet2

Report

Sub Compare2WorkSheets(ws1 As Worksheet, ws2 As Worksheet)
  Dim ws1row As Long, ws2row As Long, ws1col As Integer, ws2col As Integer
  Dim maxrow As Long, maxcol As Integer, colval1 As String, colval2 As String
  Dim Report As Workbook, difference As Long
  Dim row As Long, col As Integer
  Dim Arr1 As Variant, Arr2 As Variant, Arr3 As Variant, Rng As Range
  Dim tm As Double
  tm = Timer

  'Application.ScreenUpdating = False
  'Application.Calculation = xlCalculationManual
  'Application.EnableEvents = False

  With ws1.UsedRange
    ws1row = .Rows.Count
    ws1col = .Columns.Count
  End With

  With ws2.UsedRange
    ws2row = .Rows.Count
    ws2col = .Columns.Count
  End With

  maxrow = ws1row
  maxcol = ws1col
  If maxrow < ws2row Then maxrow = ws2row
  If maxcol < ws2col Then maxcol = ws2col

  Debug.Print maxrow, maxcol
  Arr1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(maxrow, maxcol)).Formula
  Arr2 = ws2.Range(ws2.Cells(1, 1), ws2.Cells(maxrow, maxcol)).Formula
  ReDim Arr3(1 To UBound(Arr1, 1), 1 To UBound(Arr1, 2))

  difference = 0

  For col = 1 To maxcol
    For row = 1 To maxrow
      If Arr1(row, col) <> Arr2(row, col) Then
      difference = difference + 1
      Arr3(row, col) = Arr1(row, col) & "<> " & Arr2(row, col)
      Else
      Arr3(row, col) = ""
      End If
    Next row
  Next col

  Debug.Print " Calc secs " & Timer - tm
  If difference > 0 Then
  Set Report = Workbooks.Add

  With Report.ActiveSheet
  .Range("A1").Resize(UBound(Arr3, 1), UBound(Arr3, 2)).Value = Arr3
  .Columns("A:B").ColumnWidth = 25
  Set Rng = .Range(Report.ActiveSheet.Cells(1, 1), Report.ActiveSheet.Cells(UBound(Arr3, 1), UBound(Arr3, 2)))
  End With

  With Rng
  .FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:="=""""" '""""""""
  .FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
   With .FormatConditions(1)
        .Interior.Color = 255
        .Font.Bold = True
        .Font.ColorIndex = 2
    End With
   End With

  Debug.Print "Report Generated secs " & Timer - tm
  End If
 'Set Report = Nothing
  'Application.ScreenUpdating = True
  'Application.Calculation = xlCalculationAutomatic
  'Application.EnableEvents = True

  MsgBox difference & " cells contain different data! ", vbInformation, "Comparing Two       Worksheets"
End Sub

How do I run this code?

I add the code into a module and then create a button and do the following.

The first picture shows how I call the sub to compare the two sheets

The second pictures shows how I open up another file and compare two Excel files.

This answer assumes that all Names in the data are unique. There is no
  provision in this example to handle duplicate Names except to issue a
  note in the debug output.

This answer will involve Dictionaries. Please review this website for complete information on how and why they are an efficient way to store unique data. The short answer is that you can create a large dictionary by looking at a unique "key", which is a string that uniquely represents some data that you want to track. In your case, you've asserted that all of the Names are unique. Dictionaries exist for speedy access to any single entry -- no looping through 200k entries to find the one you want. Use your unique key string and you have near-instant access to the data associated with that key.

For your situation, my example builds two Dictionaries, one for each set of data. The keys are the Names. The values associated with each key (Name) is the row number on which each Name is used. The row numbers will play a major role later on.

As with the other Code Review for your previous version of code, I'll reiterate:

Identify your function parameters ByRef or ByVal
Declare your variables as close to their first use as possible.

As an example:

Dim arr1 As Variant
Dim arr2 As Variant
arr1 = BuildDataArrays(ws1, startRow:=2)
arr2 = BuildDataArrays(ws2, startRow:=2)

You'll see that there is a call to a BuildDataArrays function. That brings me to

Functional Isolation. When your routine starts getting very long, that is the perfect time to begin breaking parts of the logic out into separate functions/subs. This is especially useful if you have repetitive logic where only the variable is different. This is the case for BuildDataArrays.

Give this function a worksheet and optionally the starting row or column and it determines the range of available data, returning a memory-based array. Breaking out code into separate routines is very helpful because it makes your main logic easier to follow.

Private Function BuildDataArrays(ByRef ws As Worksheet, _
                                 Optional ByVal startRow As Long = 1, _
                                 Optional ByVal startCol As Long = 1) As Variant
    '--- assumes all rows and columns are valid data
    Dim lastRow As Long
    Dim lastCol As Long
    Dim dataArea As Range
    Dim data As Variant
    With ws
        lastRow = .Cells(.Rows.Count, startRow).End(xlUp).row
        lastCol = .Cells(startCol, .Columns.Count).End(xlToLeft).Column
        Set dataArea = .Cells(startRow, startCol).Resize(lastRow - startRow + 1, _
                                                         lastCol - startCol + 1)
        data = dataArea
    End With
    BuildDataArrays = data
End Function

Use Dictionaries to collect your data. As with the previous point, this is a perfect opportunity to isolate the logic in a separate function.

The BuildDataDictionary function will accept your memory-based array and use the selected column of data as a unique key (currently defaulted to column "I").

Private Function BuildDataDictionary(ByRef data As Variant, _
                                     Optional ByVal keyColumn As Long = 8) As Dictionary
    Dim row As Long
    Dim name As String
    Dim names As Dictionary
    Set names = New Dictionary
    For row = LBound(data, 1) To UBound(data, 1)
        name = Trim$(data(row, keyColumn))
        If Len(name) > 0 Then
            If Not names.Exists(name) Then
                '--- add the new name to the dictionary and save the row number
                names.Add name, row
            Else
                '--- if you get here, it means that the Name is NOT unique
                '    and you'll have to change your logic, or change the name
                Debug.Print "ERROR: Duplicate name detected on " & _
                            " on row " & row & ": '" & name & "'"
            End If
        End If
    Next row
    Set BuildDataDictionary = names
End Function

Next we'll build the resulting report data. According to your description, the report will consist of all data rows (each with a unique Name), with any differences noted in the data itself. In your original post, you are assuming that the larger of the two row counts for the sheets will be your output array. This isn't true.

Consider that, by definition, all of the data from Sheet1 is unique (because each row's Name is unique). That means if you have 10 rows of data on Sheet1, your output data will have at least ten rows. It's possible that your data on Sheet2 also has ten rows of data, and only one of those rows repeats a Name on Sheet1. So your resulting report of data will have 19 rows.

Dim totalRows As Long
totalRows = ws1Names.Count

'--- now add on the number of unique rows from the other sheet
Dim name As Variant
For Each name In ws2Names
    If Not ws1Names.Exists(name) Then
        '--- name is unique
        totalRows = totalRows + 1
    Else
        '--- name is not unique
    End If
Next name
Debug.Print "There are " & totalRows & " unique Names between the sheets"

'--- now build a correctly sized output array
'    ASSUMES both arrays have the same number of columns!!
Dim reportData As Variant
ReDim reportData(1 To totalRows, 1 To UBound(arr1, 2))

Now that we're about to generate the report data, we have to consider how to make note of any errors encountered. For this I'm using a Collection, which is a simple way to generate a running list of items. In this case, for each difference I'm adding a string that notes the row and column of each difference in the data arrays. I can use this later on to highlight the difference cells.

'--- and create an object to list which cells are different
Dim diffCells As Collection
Set diffCells = New Collection

After that, we simply move the data over to the report array, making note of any differences.

'--- we know that all Names are unique in sheet1, so move the all that
'    data from sheet1 into the report array
Dim row As Long
Dim col As Long
Dim ws1row As Long
Dim ws2row As Long
row = 1
For Each name In ws1Names
    If ws2Names.Exists(name) Then
        '--- this row will have a difference because the Names match!
        '    so get the rows for each sheet that match the name
        ws1row = ws1Names(name)
        ws2row = ws2Names(name)
        For col = 1 To UBound(reportData, 2)
            If arr1(ws1row, col) = arr2(ws2row, col) Then
                reportData(row, col) = arr1(ws1row, col)
            Else
                '--- note the different values in the cell and add the
                '    row and column to the difference list
                reportData(row, col) = arr1(ws1row, col) & " <> " & _
                                       arr2(ws2row, col)
                diffCells.Add CLng(row) & "," & CLng(col)
            End If
        Next col
    Else
        '--- this is a unique row, so a straight copy of all columns
        For col = 1 To UBound(reportData, 2)
            reportData(row, col) = arr1(row, col)
        Next col
    End If
    row = row + 1
Next name

'--- the remaining data are the unique rows that exist in sheet2
'    the "row" variable count is continued in this loop
For Each name In ws2Names
    If Not ws1Names.Exists(name) Then
        '--- this is a unique row, so a straight copy of all columns
        ws2row = ws2Names(name)
        For col = 1 To UBound(reportData, 2)
            reportData(row, col) = arr2(ws2row, col)
        Next col
        row = row + 1
    End If
Next name

The final step is to output the report data. In my example, I am not creating a new workbook, but only creating a new worksheet. You can un-comment some code lines there to change it back for your purposes.

If diffCells.Count > 0 Then
    Dim report As Workbook
    Dim reportWS As Worksheet
    'Set report = Workbooks.Add           'un-comment to report to a new workbook
    'Set reportWS = report.ActiveSheet    'un-comment to report to a new workbook
    Set reportWS = ThisWorkbook.Sheets.Add   'comment to report to a new workbook

    '--- copy the resulting report to the worksheet
    Dim reportArea As Range
    Set reportArea = reportWS.Range("A1").Resize(UBound(reportData, 1), UBound(reportData, 2))
    With reportArea
        .Value = reportData
        .Columns("A:B").ColumnWidth = 25

        '--- now highlight the cells that are different
        Dim rowcol As Variant
        Dim parts() As String
        For Each rowcol In diffCells
            parts = Split(rowcol, ",")
            With .Cells(CLng(parts(0)), CLng(parts(1)))
                .Font.Bold = True
                .Font.ColorIndex = 3
            End With
        Next rowcol
    End With
    Debug.Print "Report Generated secs " & Timer - tm
End If

Here is the whole code module in one block:

Option Explicit

Sub test1()
    Compare2WorkSheets Sheet1, Sheet2
End Sub

Sub Compare2WorkSheets(ByRef ws1 As Worksheet, ByRef ws2 As Worksheet)
    Dim tm As Double
    tm = Timer

    'Application.ScreenUpdating = False
    'Application.Calculation = xlCalculationManual
    'Application.EnableEvents = False

    '--- establish the data in the arrays, skip the header row
    Dim arr1 As Variant
    Dim arr2 As Variant
    arr1 = BuildDataArrays(ws1, startRow:=2)
    arr2 = BuildDataArrays(ws2, startRow:=2)

    '--- buidl a dictionary of Names for each worksheet
    Dim ws1Names As Dictionary
    Dim ws2Names As Dictionary
    Set ws1Names = BuildDataDictionary(arr1)
    Set ws2Names = BuildDataDictionary(arr2)

    '--- we don't know how many rows the report will be, so compare
    '    names between the two sheets to find out. it's basically
    '    the sum of the number of unique names between the sheets
    Dim totalRows As Long
    totalRows = ws1Names.Count

    '--- now add on the number of unique rows from the other sheet
    Dim name As Variant
    For Each name In ws2Names
        If Not ws1Names.Exists(name) Then
            '--- name is unique
            totalRows = totalRows + 1
        Else
            '--- name is not unique
        End If
    Next name
    Debug.Print "There are " & totalRows & " unique Names between the sheets"

    '--- now build a correctly sized output array
    '    ASSUMES both arrays have the same number of columns!!
    Dim reportData As Variant
    ReDim reportData(1 To totalRows, 1 To UBound(arr1, 2))

    '--- and create an object to list which cells are different
    Dim diffCells As Collection
    Set diffCells = New Collection

    '--- we know that all Names are unique in sheet1, so move the all that
    '    data from sheet1 into the report array
    Dim row As Long
    Dim col As Long
    Dim ws1row As Long
    Dim ws2row As Long
    row = 1
    For Each name In ws1Names
        If ws2Names.Exists(name) Then
            '--- this row will have a difference because the Names match!
            '    so get the rows for each sheet that match the name
            ws1row = ws1Names(name)
            ws2row = ws2Names(name)
            For col = 1 To UBound(reportData, 2)
                If arr1(ws1row, col) = arr2(ws2row, col) Then
                    reportData(row, col) = arr1(ws1row, col)
                Else
                    '--- note the different values in the cell and add the
                    '    row and column to the difference list
                    reportData(row, col) = arr1(ws1row, col) & " <> " & _
                                           arr2(ws2row, col)
                    diffCells.Add CLng(row) & "," & CLng(col)
                End If
            Next col
        Else
            '--- this is a unique row, so a straight copy of all columns
            For col = 1 To UBound(reportData, 2)
                reportData(row, col) = arr1(row, col)
            Next col
        End If
        row = row + 1
    Next name

    '--- the remaining data are the unique rows that exist in sheet2
    '    the "row" variable count is continued in this loop
    For Each name In ws2Names
        If Not ws1Names.Exists(name) Then
            '--- this is a unique row, so a straight copy of all columns
            ws2row = ws2Names(name)
            For col = 1 To UBound(reportData, 2)
                reportData(row, col) = arr2(ws2row, col)
            Next col
            row = row + 1
        End If
    Next name

    Debug.Print " Calc secs " & Timer - tm
    If diffCells.Count > 0 Then
        Dim report As Workbook
        Dim reportWS As Worksheet
        'Set report = Workbooks.Add           'un-comment to report to a new workbook
        'Set reportWS = report.ActiveSheet    'un-comment to report to a new workbook
        Set reportWS = ThisWorkbook.Sheets.Add   'comment to report to a new workbook

        '--- copy the resulting report to the worksheet
        Dim reportArea As Range
        Set reportArea = reportWS.Range("A1").Resize(UBound(reportData, 1), UBound(reportData, 2))
        With reportArea
            .Value = reportData
            .Columns("A:B").ColumnWidth = 25

            '--- now highlight the cells that are different
            Dim rowcol As Variant
            Dim parts() As String
            For Each rowcol In diffCells
                parts = Split(rowcol, ",")
                With .Cells(CLng(parts(0)), CLng(parts(1)))
                    .Font.Bold = True
                    .Font.ColorIndex = 3
                End With
            Next rowcol
        End With
        Debug.Print "Report Generated secs " & Timer - tm
    End If
    'Application.ScreenUpdating = True
    'Application.Calculation = xlCalculationAutomatic
    'Application.EnableEvents = True

    If diffCells.Count > 0 Then
        Debug.Print diffCells.Count & " cells contain different data!"
    Else
        Debug.Print "No differences found between the sheets."
    End If
End Sub

Private Function BuildDataArrays(ByRef ws As Worksheet, _
                                 Optional ByVal startRow As Long = 1, _
                                 Optional ByVal startCol As Long = 1) As Variant
    '--- assumes all rows and columns are valid data
    Dim lastRow As Long
    Dim lastCol As Long
    Dim dataArea As Range
    Dim data As Variant
    With ws
        lastRow = .Cells(.Rows.Count, startRow).End(xlUp).row
        lastCol = .Cells(startCol, .Columns.Count).End(xlToLeft).Column
        Set dataArea = .Cells(startRow, startCol).Resize(lastRow - startRow + 1, _
                                                         lastCol - startCol + 1)
        data = dataArea
    End With
    BuildDataArrays = data
End Function

Private Function BuildDataDictionary(ByRef data As Variant, _
                                     Optional ByVal keyColumn As Long = 8) As Dictionary
    Dim row As Long
    Dim name As String
    Dim names As Dictionary
    Set names = New Dictionary
    For row = LBound(data, 1) To UBound(data, 1)
        name = Trim$(data(row, keyColumn))
        If Len(name) > 0 Then
            If Not names.Exists(name) Then
                '--- add the new name to the dictionary and save the row number
                names.Add name, row
            Else
                '--- if you get here, it means that the Name is NOT unique
                '    and you'll have to change your logic, or change the name
                Debug.Print "ERROR: Duplicate name detected on " & _
                            " on row " & row & ": '" & name & "'"
            End If
        End If
    Next row
    Set BuildDataDictionary = names
End Function

  EDIT: added an example on how to call the routine from a button click

It seems that you're adding an ActiveX command button to your worksheet. In this case, the CommandButton1_Click() method will be executed in the Sheet1 module. Take the code above with the Compare2WorkSheets routine and paste it into a regular code module. Then, in your sheet1 module, fix up your button-click code like this:

Option Explicit

Private Sub CommandButton1_Click()
    Dim myWorkbook1 As Workbook
    Dim myWorkbook2 As Workbook

    '--- if Sheet1 is contained in the workbook where the code is running, use this
    Set myWorkbook1 = ThisWorkbook

    '--- if Sheet1 is in a different -- but already open -- workbook, use this
    Set myWorkbook1 = Workbooks("the-already-open-workbook-filename.xlsx")

    '--- if Sheet1 is in a different -- but unopened -- workbook, use this
    Set myWorkbook1 = Workbooks.Open("the-workbook-filename-to-open.xlsx")

    '--- you can make the same decisions for setting myWorkbook2
    Set myWorkbook2 = Workbooks.Open("C:\Temp\testreport1.xlsx")

    Compare2WorkSheets myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1")

    myWorkbook1.Close
    myWorkbook2.Close
End Sub


Write a class for Team which should have function to prints players details I have written it using aggregation but i feel its not the best way we can do this. Please suggest is there any other way to do this. I think we can also built this without using player class, just store players details in nested list or dict. Please suggest what is the best way.

class Player(object):
    def __init__(self, name, age, skills, style=None):
        self.name = name
        self.age = age
        self.skills = skills
        self.style = style

    def get_player(self):
        print(self.name,self.age,self.skills,self.style)

class Team(object):
    def __init__(self, name):
        self.name = name
        self._players = []

    def add_player(self, obj):
        if isinstance(obj, Player):
            self._players.append(obj)
        else:
            print("Please provide player object")

    def get_players(self):
        for player in self._players:
            player.get_player()

if __name__ == "__main__":

    p1 = Player("Mahendra", 46, "Wicket Kipper", "Right-Hand Batsman")
    p2 = Player("Sachin", 35, "Batsman", "Right-Hand Batsman")
    p3 = Player("Saurabh", 44, "Batsman", "Left-Hand Batsman")
    p4 = Player("Zahir", 38, "Bauwller", "Medium Pace Bauwller")
    p5 = Player("Yuvraj", 43, "All rounder")

    t = Team("India")
    t.add_player(p1)
    t.add_player(p2)
    t.add_player(p3)
    t.add_player(p4)
    t.add_player(p5)

    t.get_players()

You should learn about Python's magic (or dunder) methods. They allow your custom class to interact with the built-in functions (by e.g. defining what a + b means for objects of your class, or, which is relevant here, what print(team) or print(player) mean.

For this I would add two methods, first the __iter__ method, which allows you to iterate over your team and get each player, and the __str__ method, which defines how your class prints:

class Player:
    def __init__(self, name, age, skills, style=None):
        self.name = name
        self.age = age
        self.skills = skills
        self.style = style

    def __str__(self):
        return f"{self.name} {self.age} {self.skills} {self.style or ''}"

class Team:
    def __init__(self, name, players=None):
        self.name = name
        if players is not None:
            self._players = list(players)
        else:
            self._players = []

    def add_player(self, obj):
        if isinstance(obj, Player):
            self._players.append(obj)
        else:
            print("Please provide player object")

    def __iter__(self):
        return iter(self._players)

    def __str__(self):
        out = [f"Team name: {self.name}", "Players:"]
        out.extend(str(player) for player in self)
        return "\n".join(out)

if __name__ == "__main__":

    players = [Player("Mahendra", 46, "Wicket Kipper", "Right-Hand Batsman"),
               Player("Sachin", 35, "Batsman", "Right-Hand Batsman"),
               Player("Saurabh", 44, "Batsman", "Left-Hand Batsman"),
               Player("Zahir", 38, "Bauwller", "Medium Pace Bauwller"),
               Player("Yuvraj", 43, "All rounder")]

    india = Team("India", players)
    print(india)

    # equivalent:
    print("Team name:", india.name)
    print("Players:")
    for player in india:
        print(player)

I also added an optional keyword argument to the Team constructor to allow passing in a list of players right away.

I also removed the explicit inheritance from object, which is not needed anymore in Python 3 (only for backwards compatibility with Python 2), as all classes are new-style classes.


Creating lightning bolt effects Which one of these are better for the memory?

protected static List<Line> CreateBolt(Vector2 source, Vector2 dest, float thickness)
{
    //...

    for (int i = 1; i < positions.Count; i++)
    {
        float pos = positions[i];
        float scale = (length * Jaggedness) * (pos - positions[i - 1]);
        float envelope = pos > 0.95f ? 20 * (1 - pos) : 1;
        float displacement = Rand(-Sway, Sway);
        displacement -= (displacement - prevDisplacement) * (1 - scale);

        // ,,,
    }
    //...
}

protected static List<Line> CreateBolt(Vector2 source, Vector2 dest, float thickness)
{
    //...
    float pos;
    float scale;
    float envelope;
    float displacement;

    for (int i = 1; i < positions.Count; i++)
    {
        pos = positions[i];
        scale = (length * Jaggedness) * (pos - positions[i - 1]);
        envelope = pos > 0.95f ? 20 * (1 - pos) : 1;
        displacement = Rand(-Sway, Sway);
        displacement -= (displacement - prevDisplacement) * (1 - scale);

        // ,,,
    }
    //...
}

Should I declare variables before or inside a for loop? Does it even make a difference at all?

Both of your versions will probably generate the same IL code. See: https://stackoverflow.com/a/7383090/2655508

The first version is still better, because you should declare variables as near as possible to their usage.

You shouldn't shorten variable names. You already have positions[] so why do you have pos instead of position?

You have some magic numbers in your code which should be extracted to some constants with meaningful names.


Naive Implementation of Automatic Memoisation I wrote code to (naively) perform automatic memoisation. I tried to write it in a functional programming style, and so did not make use of any global variables.
My Code
def naive_memoise(caches):
    def memoise(f):
        nonlocal caches
        def mem_f(n):
            nonlocal caches, f
            if f not in caches:
                caches[f] = {}
            if n not in caches[f]:
                caches[f][n] = f(n)
            return caches[f][n]
        return mem_f
    return memoise

Sample Usage
def fib(n):
    if n in [0, 1]:
        return n
    return  fib(n - 2) + fib(n - 1)

mem = naive_memoise({})
fib = mem(fib)

This looks good to me and I have nothing important to add.

the nonlocal are not required here
in the code sample, you could use the @decorator syntax
maybe you could write something more generic than just functions taking a single parameter.


Beginner Project: Bunny City I am a Java programmer, and I just recently started learning Scala for fun. I found a group of projects here, and I tried to do the graduation excercise. The problem is, my code looks a lot like java, and I want to make this code more styled to fit scala, though I'm not sure what that entails. (Making it more functional?)

This is my main game class:

object Game {

  def main(args: Array[String]): Unit = {
    val list : ListBuffer[Bunny] = ListBuffer.fill(5)(BunnyFactory.getInitial)

    while(list.size != 0){

      var iterator = 0;
      //make sure we have one male for mating
      var males = 0;
      //keep track of females for mating
      var females : ListBuffer[Bunny] = new ListBuffer

      for(i <- list){
        i.update(list)

        if(i.dead){
              println(s"Bunny ${i.name} died at age ${i.age}!")
              list.remove(iterator)
        }
        else {
          if(i.gender == Gender.Male && i.adult){
            males += 1;
          }else if (i.gender == Gender.Female && i.adult){
              females += i;
          }
          println(i)
        }
        iterator += 1;
      }
      if(males >= 1){
        for(i <- females){

          val child = BunnyFactory.getChild(i);
          println(s"Bunny ${child.name} was born!")
          list += child
        }
      }
      println(s"There are ${list.size} bunnies!")

      Thread.sleep(500)
    }

  }
}

My Bunny class (I'm not sure if my variable naming follows conventions here):

class Bunny(inColor : Color.Value, inGender : Gender.Value, inAge : Int, inName : String, radioactive : Boolean){
    private val _color = inColor;
    private val _gender = inGender;
    private val _name = inName;
    private var _radioactive = radioactive;
    private var _age = inAge;

    def gender = _gender
    def age = _age
    def name = _name
    def adult : Boolean = {_age >= 2 && !(_radioactive)}
    def color  = _color

    def dead : Boolean = {
      if(_radioactive){
        _age > 50;
      }else{
        _age > 10;
      }
    }

    def infect : Unit = {_radioactive = true}

    def update(list : ListBuffer[Bunny]) : Unit = {
      _age += 1
      if(_radioactive){
         list((Math.random() * list.length).toInt).infect
      }
    }
    override def toString() : String = {
      return s"${_color} ${_gender} Bunny ${_name}, ${_age} years old, Radioactive: ${_radioactive}"
    }
}

Bunny Factory class:

object BunnyFactory {
    def getInitial : Bunny = {
      return new Bunny(
                    Color.getRandom,
                    Gender.getRandom,
                    0,
                    getName,
                    false)
    }
    def getChild(mom : Bunny) : Bunny = {
      val rand = (Math.random() * 100).toInt
      return new Bunny(mom.color, Gender.getRandom, 0, getName, rand <= 2)
    }
    val names : ListBuffer[String] = {
      val source = Source.fromFile("res/names.txt")
      val lines : List[String] = source.getLines.toList
      source.close
      lines.to[ListBuffer]
    }
    def getName : String = {
      val rand = (Math.random() * names.size).toInt
      return names(rand)
    }
}

Gender object:

object Gender extends Enumeration{
  type Gender = Value
  val Male, Female = Value

  def getRandom() : Gender = {
        val rand : Int = (Math.random() * values.size).toInt
        return this.apply(rand)
      }
}

Color object:

object Color extends Enumeration{
  type Color = Value
  val White, Brown, Black, Spotted = Value

  def getRandom() : Color = {
    val rand : Int = (Math.random() * values.size).toInt
    return this.apply(rand)
  }
}

Let me start with some suggestions to improve your code a little bit in regards of scala/functional style. I will start with by class with the points that catched my eyes first and i might edit my post later on and add additional points.

Class structure and constructors

Instead of going with

class Bunny(inColor : Color.Value, inGender : Gender.Value, inAge : Int, inName : String, radioactive : Boolean){
    private val _color = inColor;
    private val _gender = inGender;
    private val _name = inName;
    private var _radioactive = radioactive;
    private var _age = inAge;

you can write it more concise like this:

class Bunny(val color : Color.Value, val gender : Gender.Value, var age : Int, val name : String, var radioactive : Boolean){

No need to declare them with other names inside the class. Notice however, that public getters and setters (for vars) will be created automatically. Going private val color : Color.Value on the other hand will create a private getter.

Instead of creating the adult variable on the fly (def adult : Boolean = {_age >= 2 && !(_radioactive)}) it may be better to make the main constructor accept an adult variable and to create a second constructor (which calls the main constructor) that does the logic above. One important benifit is, that it will be more easy to test when you can pass in the adult variable as is.

The getChild method in your BunnyFactory class seems to belong to your Bunny class. You could consider making a class for male and female bunnies because they behave different although they are both bunnies. Traits could be a good option here to add a functionality only to the female bunny class for creating new child bunnies.

Naming

In your Bunny class you have a method update(list : ListBuffer[Bunny]) : Unit. I would call that different. Maybe infectNeighbours or similar.

In your BunnyFactory class you could call the getInitial method createRandomBunny or so. Because getInitial makes me think "huh? What does it do?". Same for getChild

In your main game class don't use list but rather existingBunnies or something like this.

Shortcuts

In the toString method of Bunny class you use return s"${_color} ${_gender} Bunny ${_name}, ${_age} years old, Radioactive: ${_radioactive}".
The more scalaish way to do this is to omit the "return". It is not needed. The result of the last expression is used as return value anyways. Same goes for most of the other returns.

Now to your main game class.
I personally prefer using list methods instead of the for comprehension in most cases. So instead of for(i <- list){ I would do a list.forEach. But first what do we want? For example, do we really want our already dead bunnies to infect other bunnies before we remove them from the list?

Here comes the "functional thinking" into to game (assuming our var list is called existingBunnies):

//lets first get a list of bunnies that are still alive
val livingBunnies = existingBunnies.filter{ bunny =>
    if (bunny.dead)
        println(s"Bunny ${bunny.name} is dead with an age of ${bunny.age}!")

    bunny.dead == false
}

//Now create a list of bunnies that are born new. That can be solved using not var but val in a more pure functional style but to me that will make it more complicated so i stayed with the if condition.
var newBornBunnies = List() //We have no new born bunnies by default

//But if there is at least one mal left, each female bunny will create a child
if(livingBunnies.count(_.gender == Gender.Male) >= 1) {
    newBornBunnies = livingBunnies.filter( _.adult && _.gender == Gender.Female ).map( _ createChild )
}

//We add the new born bonnies to the existing living ones
existingBunnies = livingBunnies ++ newBornBunnies

//At the end with our new list of existing bunnies we let them infect each other
existingBunnies forEach (_ infectNeighbours existingBunnies)


Number of maximal PAIRS-values I had an interview question like this:

  In a company there are different people. One can measure how well they
  suits for pair coding as follows:

  First, let us compute the PAIRS-value which is the number of letters
  P, A, I, R, S given in two people names. Then compute the sum of
  consecutive digits and sum of digits if the result is over 9.

  Then do the same for the numbers one got in previous step: sum two
  adjacent numbers and again, compute the sum of digits of every number
  if that number is > 10. Repeat this until you have only two digits,
  which measures the goodness of pairs. For example, "Erkki Esimerkki"
  and "Matti Meikäläinen" has PAIRS-value 58:

  First [P = 0, A = 1, I = 6, R = 2, S = 1] and then

[0 + 1 = 1, 1 + 6 = 7, 6 + 2 = 8, 2 + 1 = 3]
[1 + 7 = 8, 7 + 8 = 15 => 1 + 5 = 6, 8 + 3 = 11 => 1 + 1 = 2]
[8 + 6 = 14 => 1 + 4 = 5, 6 + 2 = 8]
[5, 8] = 58%

  Now, there are many worker names given in
  http://reaktor.fi/wp-content/uploads/2014/08/fast_track_generoitu_nimilista.txt
  . Find the number of perfect pairs, i.e. those who have PAIRS-value
  99%.

Is there a faster way to solve as the following code:

import urllib.request

def sum_digits(number):
    while number > 9:
       temp = number
       y1 = number//10
       y2 = temp % 10
       number = y1 + y2
    return number

def compute_percent(pairs):
    x1 = sum_digits(pairs[0] + pairs[1])
    x2 = sum_digits(pairs[1] + pairs[2])
    x3 = sum_digits(pairs[2] + pairs[3])
    x4 = sum_digits(pairs[3] + pairs[4])
    x5 = sum_digits(x1 + x2)
    x6 = sum_digits(x2 + x3)
    x7 = sum_digits(x3 + x4)
    x8 = sum_digits(x5 + x6)
    x9 = sum_digits(x6 + x7)
    return 10*x8+x9

if __name__ == '__main__':
    address1 = 'http://reaktor.fi/wp-content/uploads/2014/08/'
    address2 = 'fast_track_generoitu_nimilista.txt'
    address = address1 + address2
    agents1 = 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36'
    agents2 = '(KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36'
    agents = agents1 + agents2

    req = urllib.request.Request(address, headers={'User-Agent': agents})
    r = urllib.request.urlopen(req)
    datas = r.read().decode('utf8')

    name = ""
    names = list()
    pairs = [0] * 5
    matches = list()
    for i in range(0,len(datas)):
        if (datas[i] == "\n"):
            names.append(name)
            name = ""
        else:
            name += datas[i]

    for i in range(0,len(names)):
        for j in range(i + 1,len(names)):
            common = names[i].lower() + names[j].lower()
            for i in range(0,len(common)):
                if (common[i]) == "p":
                    pairs[0] += 1
                if (common[i]) == "a":
                    pairs[1] += 1
                if (common[i]) == "i":
                    pairs[2] += 1
                if (common[i]) == "r":
                    pairs[3] += 1
                if (common[i]) == "s":
                    pairs[4] += 1
                for i in range(0,len(pairs)):
                    pairs[i] = sum_digits(pairs[i])

                percent = compute_percent(pairs)
                if percent == 99:
                    pari = "" + names[i] + " and " + names[j]
                    matches.append(pari)
    matches = list(set(matches))
    print(len(matches))

There is a significant flaw in your code; this line:

pairs = [0] * 5

only occurs once, and I couldn't spot pairs being emptied anywhere.

The code to create the list of names is very inefficient, this:

name = ""
names = list()
...
for i in range(0,len(datas)):
    if (datas[i] == "\n"):
        names.append(name)
        name = ""
    else:
        name += datas[i]

Could be written as:

names = data.split("\n")

Note also that for char in data would have been a more Pythonic loop construct.

You can use itertools.combinations to get pairs of names:

for name1, name2 in combinations(names, 2):

You can use collections.Counter to simplify getting the initial numbers:

counter = Counter(name1.lower())
counter.update(name2.lower())
pairs = [sum_digits(counter[c]) for c in "pairs"]

Your compute_percent only works when exactly five letters are chosen, you can make it much more general (and shorter):

def compute_percent(pairs):
    while len(pairs) > 2:
        pairs = [sum_digits(n1+n2) for n1, n2 in zip(pairs, pairs[1:])]
    return (10 * pairs[0]) + pairs[1]

I would split the if __name__ == "__main__" section into more, smaller functions, something like:

get_names to extract the names from the file;
perfect_pairs to pair them off; and
score_pair to calculate the score.

Then all you have in the last block is:

print(len(perfect_pairs(get_names())))


Recursive Contains Method The method below recursively checks if a string contains another string. Example: contains(hello, lo, 0) should return true, while contains(hello, eh, 0) should return false. The method itself works, but I was wondering how it could be made more efficient/generally better.

Method:

public static boolean contains(String word1, String word2, int index)
{
    if((word1 == null) || (word2 == null)){
        return false;
    }

    if(index + (word2.length() - 1) >= word1.length()){
        return false;
    }

    int count = 0, j = 0;

    for(int i = index; i < (word2.length() + index); i++){
        if(word1.charAt(i) == word2.charAt(j)){
            if((i != 0) && (j != 0)){
                if(word1.charAt(i - 1) == word2.charAt(j - 1)){
                    count++;
                }
            } else {
                count++;
            }
        }
        j++;
    }

    if(count == word2.length()){
        return true;
    }

    return contains(word1, word2, index + 1);
}

For proper recursive 'style', you shouldn't use a for-loop inside the function. Each pass through the function should perform one test and then set up the next pass. This also frees you from needing to track the index as an argument.

Consider that:

contains("hello", "lo") ==
contains("ello", "lo") ==
contains("llo", "lo") ==
contains("lo", "lo")


Duplicate detection and reporting in a BST For the purpose of this problem, the BST is defined to allow duplicates, and the duplicate values will always follow to the right-side of the parent nodes with the same value. For example, with the data:

 1, 2, 2, 2, 2

if the root node has the value 2 (as opposed to 1) then the tree will look like:

          2
         / \
        1   2
             \
              2
               \
                2

The following code scans the tree, identifies any values that are duplicated, and prints the duplicate values, as well as how many times that value is duplicated.

public class DuplicateCountInBST {

    private TreeNode root;

    private class TreeNode {
        TreeNode left;
        int item;
        TreeNode right;

        TreeNode (TreeNode left, int item, TreeNode right) {
            this.left = left;
            this.item = item;
            this.right = right;
        }
    }

    private class DuplicateInfo {
        int item;
        int count;

        public DuplicateInfo(int item, int count) {
            this.item = item;
            this.count = count;
        }
    }

    public void print () {
        if (root == null) {
            return;
        }
        // find right most node.
        TreeNode rightMostNode = root;
        while (rightMostNode.right != null) {
            rightMostNode = rightMostNode.right;
        }

        printHelper (root, root.item, new DuplicateInfo(0, 0), rightMostNode);
    }

    // inorder traversal
    // rightmostnode is a guard against skewed trees.
     private void printHelper (TreeNode node, int prevValue, DuplicateInfo duplicateInfo, TreeNode rightMostNode) {
         if (node == null) {
             return;
         }

         printHelper(node.left, node.item, duplicateInfo, rightMostNode);

         if (node.item == duplicateInfo.item) {
             duplicateInfo.item = node.item;
             duplicateInfo.count++;

         }
         if (node.item != duplicateInfo.item || node == rightMostNode) {
             if (duplicateInfo.count > 1) {
                 System.out.println(duplicateInfo.item + " : " + duplicateInfo.count);
             }
             duplicateInfo.item = node.item;
             duplicateInfo.count = 1;
         }

         printHelper(node.right, node.item, duplicateInfo, rightMostNode);
     }
 }

General

Your code style here is good, the variable names are nice and descriptive, and the algorithm you implement is easy to identify and follow. This is good-looking code. There are a few of nit-picks:

the TreeNode class should be a 'static' class ... private static ... because it has no reason to keep a reference to the outer class.
Your TreeNode.item should be final even though it is an internal class. final variables make for more apparent logic.
this is an opinion thing, but I prefer there to be getter/setter methods even on internal classes. With modern IDE's like Eclipse, IntelliJ and NetBeans, there really is no 'lazy' excuse for it. I prefer methods like node.getRight() instead of node.right
your method print() should have a better name like printDuplicates()

Algorithm

The solution you have for this problem appears to work. The algorithm relies on passing a token around, and relies on first walking the right-edge of the tree to create a 'stop-gate'. These two items detract from the solution. There are 'simpler' ways to do this recursive problem without the overheads you have. Consider the functions:

public void printDuplicates() {
    printDuplicatesHelper(root, 0, 0);
}

private void printDuplicatesHelper(final TreeNode node, final int parentval, final int parentcount) {
    if ((node == null || node.item != parentval) && parentcount > 1) {
        System.out.printf("Item %d was duplicated %d times\n", parentval, parentcount);
    }
    if (node == null) {
        return;
    }
    // make sure the parentcount is 0 going left.
    printDuplicatesHelper(node.left, 0, 0);
    printDuplicatesHelper(node.right, node.item, node.item == parentval ? (parentcount + 1) : 1);
}

The above functions also do an in-order scan of the data. The difference is that the recursion is designed to go past the leaf node, and to treat the null node as if it was the end of a duplicate streak. By doing it this way, and by pushing the duplicate-detecting values down with the recursion, you can detect the end-of-duplicates in a much easier pattern.

I created a 'main method' that compares the above code with yours:

 public static void main(String[] args) {
     TreeNode left = new TreeNode(null, 1, new TreeNode(null, 1, null));
     TreeNode right = new TreeNode(
              new TreeNode(null, 5, new TreeNode(null, 5, null)), 6, new TreeNode(null, 6, new TreeNode(null, 6, null)));
    TreeNode top = new TreeNode(left, 3, right);

    DuplicateCountInBST tree = new DuplicateCountInBST();
    tree.root = top;
    tree.print();
    tree.printDuplicates();
}

And the results I get from running the two calls are:

1 : 2
5 : 2
6 : 3
Item 1 was duplicated 2 times
Item 5 was duplicated 2 times
Item 6 was duplicated 3 times