Find the most common number in an array of numbers Exercise description:

Find the most common number in an array of numbers.

Create a software that takes an array of numbers as parameter.
The return of the function shall be the most common number.

Example:
Assume that the list is ... 1, 5, 1, 3, 5, 5, 2.

The program will output 5, because this is the most common number.

Note that if there is more than one most common number, the program
will just print one of the most common numbers.

My solution (written in TypeScript):

let numbers: number[] = [1, 5, 1, 3, 5, 5, 2];

namespace Main {
  export function searchMostCommonNumber(arr: number[] = []): number {
    let current: number = 0;
    let max: number = 0;
    let mostCommonNumber: number = 0;
    let i: number;

    for (i = 0; i < arr.length - 1; i++) {
      let current: number = 1;
      let j: number;

      for (j = i + 1; j < arr.length; j++) {
        if (arr[i] === arr[j]) {
          current++;
        }
      }

      if (current > max) {
        max = current;
        mostCommonNumber = arr[i];
      }
    }

    return mostCommonNumber;
  }
}

console.log(Main.searchMostCommonNumber(numbers));

Live demo (with compiled code):

var numbers = [1, 5, 1, 3, 5, 5, 2];
var Main;
(function(Main) {
  function searchMostCommonNumber(arr) {
    if (arr === void 0) {
      arr = [];
    }
    var current = 0;
    var max = 0;
    var mostCommonNumber = 0;
    var i;
    for (i = 0; i < arr.length - 1; i++) {
      var current_1 = 1;
      var j = void 0;
      for (j = i + 1; j < arr.length; j++) {
        if (arr[i] === arr[j]) {
          current_1++;
        }
      }
      if (current_1 > max) {
        max = current_1;
        mostCommonNumber = arr[i];
      }
    }
    return mostCommonNumber;
  }
  Main.searchMostCommonNumber = searchMostCommonNumber;
})(Main || (Main = {}));
console.log('The most common number is :', Main.searchMostCommonNumber(numbers));

What do you think about my solution?

Is there a better way to accomplish the task? What would you have done differently?

Looking forward to reading your comments and answers.

For small arrays as input your script's performance is very good. Let me show you a different approach which might especially improve readability and might also increase performance for larger inputs and multiple runs.

.reduce()

Instead of iterating through the elements manually, I've used Array.prototype.reduce():

  The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

The function has two steps now which both use reduce():

Reduce the input into an object that holds each number and its count as key/value-pairs.
Reduce this object to find the key with the highest value.

function findMode(numbers) {
    let counted = numbers.reduce((acc, curr) => {
        if (curr in acc) {
            acc[curr]++;
        } else {
            acc[curr] = 1;
        }

        return acc;
    }, {});

    let mode = Object.keys(counted).reduce((a, b) => counted[a] > counted[b] ? a : b);

    return mode;
}

Performance

In the comments we had a lot of discussion about performance about this and other solutions.

One requested improvement was to calculate the mode directly in the first reduce call. It could look like this:

function findModeAlternative(numbers) {
    let max = 0;
    let mode = null;
    let counted = numbers.reduce((acc, curr) => {
        if (curr in acc) {
            acc[curr]++;
        } else {
            acc[curr] = 1;
        }

        if (max < acc[curr]) {
            max = acc[curr];
            mode = curr;
        }

        return acc;
    }, {});

    return mode;
}

Unfortunately it didn't improve performance in Chrome and Firefox.

Then Blindman67 suggested the naive approach with this solution:

function findCommon(arr) {
    var max = 1,
        m = [],
        val = arr[0],
        i, x;

    for(i = 0; i < arr.length; i ++) {
        x = arr[i]
        if (m[x]) {
            ++m[x] > max && (max = m[i], val = x);
        } else {
            m[x] = 1;
        }
    } return val;
}

Which will increase performance significantly in Firefox, but performs about the same in Chrome. Keep in mind, that functions like reduce, map etc. come with some overhead.

Finally the approach using map in Gerrit0's answer also increases the performance drastically opposed to the original.

Test

I've created a test, so you can check the performance of each variant yourself. The test uses two different arrays with ca. 500 elements each and runs every function 100000 times:

test array A is kind of mixed
test array B contains mostly one number with a few exceptions

These are the results from Chrome 61 on macOS:

array A "findMode": 1000ms
array B "findMode": 950ms
array A "findModeAlternative": 1200 ms
array B "findModeAlternative": 1100 ms
array A "findCommon": 930 ms
array B "findCommon": 960 ms
array A "mostCommonNumber": 1700 ms
array B "mostCommonNumber": 1300 ms
array A "searchMostCommonNumber": 12697 ms
array B "searchMostCommonNumber": 13400 ms

Try it yourself

Of course you can tweak the test and try different inputs etc.

The functions's name

As this is called mode in statistics, you could use a shorter function name like findMode()

Unfortunately this doesn't improve performance. This is just a personal preference

I only included the ES6 version of the script in this answer. I didn't add the check whether the array is an array and not empty, as this will be added when compiling from TypeScript to JavaScript


PHP login cookie authentication I have the following code to do remember-me style login:

<?php
session_start();
if(!isset($_SESSION['login'])) $_SESSION['login'] = 0;
if(isset($_COOKIE['web_login_cookie']) && $_SESSION['login'] == 0) {
    $sql = mysql_query("SELECT * FROM users");
    while($row = mysql_fetch_array($sql)) {
        $pass = sha1($row['password'] . '@#$%$#%dsf@#$SDFg');
        if($_COOKIE['web_login_cookie'] == $pass) {
            $_SESSION['userID'] = $row['userID'];
            $_SESSION['login'] = 1;
            if($row['level'] == 1) {
                $_SESSION['admin'] = 1;
            }
        }
    }
    if(mysql_num_rows($sql) == 0) {
        setcookie("web_login_cookie", "", time()+(60*60*24*14));
        session_destroy();
    }
}
?>

I have this code in my header file. Is this secure enough or will it pose any security risks in the future?

I don’t like the idea of storing the password hash in a cookie. It is easy to steal and grants unlimited access. The cookie is transmitted with every single HTTP request. I would prefer using an access token with limited lifetime. Anyway most people store passwords in their browser and this is easy to steal as well – so this seems not to be a massive security break.

The bigger problem is that your login only relies on the password – you don’t need to know the corresponding username to login. This makes brute forcing a lot easier. And more important: your login will break, if two users use the same password. Then user2 will (unintentionally) gain access to user1’s account.

PS: As mentioned in comments, don’t loop over every line in your table, use a WHERE clause instead. And I don’t understand, what you are trying to achieve with your mysql_num_rows code block…


Ruby code refactoring I have n-times similar statements

    if trigger_data.tt_closed
      unless trouble_ticket.changes.key?(:status)
        @run = 0
        break
      end
      unless trouble_ticket.changes[:status][1] == "Closed"
        @run = 0
        break
      end
    end

    if trigger_data.tt_assignee
      unless trouble_ticket.changes.key?(:assigned_to)
        @run = 0
        break
      end
      unless trouble_ticket.changes[:assigned_to][1] == trigger_data.tt_assignee
        @run
        break
      end
    end

How to refactoring that code? Maybe dynamic statement build with pass some hash to input. I'm newbie in metaprogramming. Give me advise please

Are you inside a loop? Here is a possible way of doing it

def check(td, tt, trigger, key, ticket_changes)
    if td.send(trigger)
      unless tt.changes.key?(key)
        @run = 0
        return true
      end
      unless tt.changes[key][1] == ticket_changes
        @run = 0
        return true
      end
    end
    return false
end

def metacheck(td, tt)
    [[:tt_closed, :status, "Closed"],
     [:tt_assignee, :assigned_to, td.tt_assignee]].each do |k|
        return if check(td, tt, k[0], k[1], k[2])
     end
end

metacheck(trigger_data, trouble_ticket)

I have used an array of triplets to check the conditions.
The check can further be simplified as

def check(td, tt, trigger, key, ticket_changes)
    return false unless td.send(trigger)
    if !tt.changes.key?(key) or (tt.changes[key][1] != ticket_changes)
        @run = 0
        return true
    end
    return false
end

We can join all the conditions together. But I think this captures the original intension best.


Number to Roman Numeral var romanArray = [];
var toRoman = {

    analyze: function(number){
        romanArray = [];
        if (number >= 1000) {
            return this.thousands(number);
        }else if (number >= 100){
            return this.hundreds(number);
        }else if (number >= 10) {
            return this.tens(number);
        }else{
            return this.last_number(number);
        }
    },

    thousands: function(number){
        var remainder = number % 1000;
        var thousands = Math.floor(number / 1000);
        for(var e = 0; e < thousands; e++) {
            romanArray.push('M');
        }
        return this.hundreds(remainder);
    },

    hundreds: function(number){
        var remainder = number % 100;
        var hundreds = Math.floor(number / 100);
        if (hundreds === 4){
            romanArray.push('CD');
        }else if(hundreds === 9){
            romanArray.push('CM');
        }else if(hundreds >= 5 && hundreds < 9){
            romanArray.push('D');
            for(var i = 0; i < (hundreds % 5); i++) {
                romanArray.push('C');
            }
        }else if (hundreds > 0 && hundreds < 4){
            for(var e = 0; e < hundreds; e++) {
                romanArray.push('C');
            }
        }else{

        }
        return this.tens(remainder);
    },

    tens: function(number){
        var remainder = number % 10;
        var tens = Math.floor(number / 10);
        if (tens === 4){
            romanArray.push('XL');
        }else if(tens === 9){
            romanArray.push('XC');
        }else if(tens >= 5 && tens < 9){
            romanArray.push('L');
            for(var i = 0; i < (tens % 5); i++) {
                romanArray.push('X');
            }
        }else if (tens > 0 && tens < 4){
            for(var e = 0; e < tens; e++) {
                romanArray.push('X');
            }
        }else{

        }
        return this.last_number(remainder);
    },

    last_number: function (number){
        if (number === 4){
            romanArray.push('IV');
        }else if(number === 9){
            romanArray.push('IX');
        }else if(number >= 5 && number < 9){
            romanArray.push('V');
            var remainder = number % 5;
            for(var i = 0; i < remainder; i++) {
                romanArray.push('I');
            }
        }else if (number > 0 && number < 4){
            for(var e = 0; e < number; e++) {
                romanArray.push('I');
            }
        }else{

        }
        return romanArray.join('');
    }
};

console.log(toRoman.analyze(1000));
console.log(toRoman.analyze(2999));
console.log(toRoman.analyze(2555));

I'm wondering if this JavaScript can be refactored using some sort of base/template function.
For Example:

base_function: function (number, four, nine, five, one){
    if (number === 4){
        romanArray.push(four);
    }else if(number === 9){
        romanArray.push(nine);
    }else if(number >= 5 && number < 9){
        romanArray.push(five);
        var remainder = number % 5;
        for(var i = 0; i < remainder; i++) {
            romanArray.push(one);
        }
    }else if (number > 0 && number < 4){
        for(var e = 0; e < number; e++) {
            romanArray.push(one);
        }
    }else{

    }
    return romanArray;
},

How can I improve this code?

You may be aware that there are simpler answers to this problem, such as:

function toRoman(n) {
    var r = '',
        decimals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
        roman = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
    for (var i = 0; i < decimals.length; i++) {
        while (n >= decimals[i]) {
            r += roman[i];
            n -= decimals[i];
        }
    }
    return r;
}

Bearing this in mind it might be useful to explain what exactly you are trying to achieve with your refactoring? E.g. is it to practice using more complicated language patterns?


Python 2.7 Powerball Game This game allows one to either pick their own lottery numbers or have them generated and checks them with the most recent numbers, jackpot, and multiplier. I use concepts such as random, for loops, raw_input, and logic. I would it appreciated if it were reviewed by someone more experienced.

import random
choice = raw_input("Do you want to randomly generate numbers, or pick them? (Enter 'R' for random, 'P' for pick.")
if choice == ('R'):
  one = random.randint(1,69)
  two = random.randint(1,69)
  three = random.randint(1,69)
  four = random.randint(1,69)
  five = random.randint(1,69)
  pball = random.randint(1,26)
elif choice == ('P'):
  one = int(raw_input("Please pick your 1st number, between 1 and 69."))
  two = int(raw_input("Please pick your 2nd number, between 1 and 69."))
  three = int(raw_input("Please pick your 3rd number, between 1 and 69."))
  four = int(raw_input("Please pick your 4th number, between 1 and 69."))
  five = int(raw_input("Please pick your 5th number, between 1 and 69."))
  pball = int(raw_input("Please pick your Powerball number, between 1 and 26."))
  if ((one or two or three or four or five) > 69) or pball > 26 or ((one or two or three or four or five or pball) < 1): #In case the entered numbers are too high or too low.
    print "Please choose a number between 1 and 69."
elif choice != ('R' or 'P'): #In case invalid input is given.
  print "Please enter either 'R' for random or 'P' for picking."
human = [one, two, three, four, five, pball]
print human
#August 15, 2018 Powerball
real = [12,15,28,47,48,16]
jackpot = 40000000
multiplier = 2
def powerball(human,real,jackpot,multiplier):
  x = raw_input("Do you want to buy the multiplier for $1? ('Y' or 'N')")
  if x == 'Y':
    pass
  elif x == 'N':
    multiplier = 1
  p = 0 #Prize
  i = 0 #Index
  m = 0 #Matches
  if human[5] == real[5]: #If you only get the powerball right.
    p = 4
  for i in range(0,5): #If you only get normal numbers, no powerball.
    if human[i] in real:
      m += 1
    i += 1
    if m == 3:
      p = 7
    elif m == 4:
      p = 100
    elif m == 5:
      p = 1000000
  m = 0
  for i in range(0,5): #If you get normal numbers along with the powerball.
    if (human[i] in real) and (human[5] == real[5]):
      m += 1
    i += 1
    if m == 1:
      p = 4
    elif m == 2:
      p = 7
    elif m == 3:
      p = 100
    elif m == 4:
      p = 50000
    elif m == 5:
      p = jackpot
  p *= multiplier
  if p > 0:
    return "Congratulations, you won $%s!" % (p)
  elif p == 0:
    return "Sorry, you didn't win anything, try again next time."
print powerball(human, real, jackpot, multiplier)

Conditions

if ((one or two or three or four or five) > 69)

one or two will return one if it isn't falsy (0 / None / False), you should use separate conditions, like so :

if (one > 69 or two > 69 or three > 69...)

alternatively, you could just check the maximum value of your list

if (max(one, two, three, four, five) > 69)

The same problem occur in this part :

elif choice != ('R' or 'P')

it should be elif choice not in ('R','P')
variable names

instead of writing

m=0#matches

directly use the variable matches, your code will be easier to understand
loops

for i in range(0,5): #If you only get normal numbers, no powerball.
    if human[i] in real:
      m += 1
    i += 1

you don't need to increase i in a for loop, it is done automatically
code structure

in the powerball function, you have the following blocks:

if powerball:
    price = 4

for i in range(0,5):#no powerball
...
for i in range(0,5):#yes powerball
    if powerball and human[i] == real:
        ...

You should change that in a if/else structure with the if powerball while counting the number of corresponding number outside :

matches = 0
price = 0

for i in range(0,5):
    if human[i] in real:
        matches+=1

if human[5] == real[5]:# with powerball
    if matches == 0:
        price = 4
    elif matches == 1:
        price = 4
else:# without powerball
    if matches == 3:
        price = 7
    elif matches == 4:
        price = 100

multiple elif for variable assignation

(I don't know if this one is considered good practice, but it's faster to use and to add case)
instead of writing multiple elif, try to use a dictionary :

prices_for_matches = { 3 : 7,
                       4 : 100,
                       5 : 1000000}
if matches in prices_for_matches:
    price = prices_for_matches[matches]
else:
    price = 0

note i don't know much about powerball, but your solution doesn't care about the order of the balls (human[i] in real instead of human[i] == real[i]) or if the user selected multiple times the same number


Truncating long strings when saving inventory items to database To test incoming data for string values that are too large for the "database" (MS Access), I could do this:

private void SaveToMSAccess(InventoryItem invItem, string dbContext)
{
    invItem = TruncateVerboseStringMembers(invItem);
    . . .
}

private InventoryItem TruncateVerboseStringMembers(InventoryItem invItem)
{
    const int DESC_MAX_LEN = 35;
    const int VENDOR_ID_MAX_LEN = 10;
    const int VENDOR_ITEM_MAX_LEN = 12;
    if (invItem.Description.Trim().Length > DESC_MAX_LEN)
    {
        invItem.Description = invItem.Description.Substring(0, DESC_MAX_LEN);
    }
    if (invItem.vendor_id.Trim().Length > VENDOR_ID_MAX_LEN)
    {
        invItem.vendor_id = invItem.vendor_id.Substring(0, VENDOR_ID_MAX_LEN);
    }
    if (invItem.vendor_item.Trim().Length > VENDOR_ITEM_MAX_LEN)
    {
        invItem.vendor_item = invItem.vendor_item.Substring(0, VENDOR_ITEM_MAX_LEN);
    }
    return invItem;
}

...where TruncateVerboseStringMembers() is always called, even though normally all conditions will fail (strings will not be too long), or I could do it like this:

const int DESC_MAX_LEN = 35;
const int VENDOR_ID_MAX_LEN = 10;
const int VENDOR_ITEM_MAX_LEN = 12;

private void SaveToMSAccess(InventoryItem invItem, string dbContext)
{
    if ((invItem.Description.Trim().Length > DESC_MAX_LEN) ||
        (invItem.vendor_id.Trim().Length > VENDOR_ID_MAX_LEN) ||
        (invItem.vendor_item.Trim().Length > VENDOR_ITEM_MAX_LEN))
    {
        invItem = TruncateVerboseStringMembers(invItem);
    }
    . . .
}

private InventoryItem TruncateVerboseStringMembers(InventoryItem invItem)
{
    if (invItem.Description.Trim().Length > DESC_MAX_LEN)
    {
        . . .

...where TruncateVerboseStringMembers() is only called when it needs to swing into action.

Or something fancier, where, if any strings are too long, I pass an array of bool to TruncateVerboseStringMembers().

Which is preferred?

Making duplicate testing just to avoid a method call doesn't make much sense. Method calls are not that expensive. On the contrary, they can help make the code cleaner.

You can make a method that helps you clean up the strings, just pass in how long each string may be. I think that maked the code as DRY as possible:

private string TruncateString(string value, int maxLen) {
  value = value.Trim();
  if (value.Length > maxLen) {
    value = value.Substring(0, maxLen);
  }
  return value;
}

private InventoryItem TruncateVerboseStringMembers(InventoryItem invItem) {
  invItem.Description = TruncateString(invItem.Description, 35);
  invItem.vendor_id = TruncateString(invItem.vendor_id, 10);
  invItem.vendor_item = TruncateString(invItem.vendor_item, 12);
  return invItem;
}

This will give you the overhead of always calling the method for each string and always assigning the reference back, but those are very cheap operations. Compared to any database call, it's negligible.

If there is nothing in the string to trim, and nothing to truncate, you will actually be putting back the original string reference in the property, so there are no extra strings created in the usual case.


Sensor logger for Raspberry Pi in a stratospheric probe I'm writing a Python Script for a Raspberry Pi to measure different sensors. We are planning to send the Pi with that Script running to the stratosphere, so the power usage for the Pi is limited.

I excuse myself in advance for the code, I had no prior experience with Python.
Are there any ways I can make this code more battery friendly? Would it be beneficial to write 10 rows at once instead of writing one row at a time?

#!/usr/bin/env python3

from sense_hat import SenseHat
import time
import csv
import datetime

sense = SenseHat()
sense.clear()
sense.set_imu_config(True, True, True)
sense.low_light = True

with open('data.csv', mode='w') as file:
    writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
    writer.writerow(['Zeit','Temperatur1', 'Temperatur2', 'Temperatur3',     'Luftdruck', 'Luftfeuchtigkeit', 'Yaw', 'Pitch', 'Roll', 'Compass X', 'Compass     Y', 'Compass Z', 'Gyro X', 'Gyro Y', 'Gyro Z'])

with open('acc.csv', mode='w') as file:
    writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
    writer.writerow(['Zeit','Acc_X','Acc_Y','Acc_Z'])

with open('log.csv', mode='w') as file:
    writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
    writer.writerow(['Zeit','Fehler'])

# Farben definieren
red = (255, 0, 0)
green = (0, 255, 0)
black = (0,0,0)

def writeDataToCsv(temperature, temperature2, temperature3, pressure, humidty,     yaw, pitch, roll, mag_x, mag_y, mag_z, gyro_x, gyro_y, gyro_z):
    with open('data.csv', mode='a') as file:
        writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
        writer.writerow([datetime.datetime.now(),temperature, temperature2,     temperature3, pressure, humidty, yaw, pitch, roll, mag_x, mag_y, mag_z,     gyro_x, gyro_y, gyro_z])

def writeAccelerationToCsv(x,y,z):
    with open('acc.csv', mode='a') as file:
        writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
        writer.writerow([datetime.datetime.now(),x,y,z])
        sense.set_pixel(0, 0, green)
        time.sleep(.05)
        sense.set_pixel(0, 0, black)

def main():
    sense.set_pixel(0, 0, black)
    counter = 0
    try:
        while True:
            #Region Acceleration
            acceleration = sense.get_accelerometer_raw()
            acc_x = acceleration['x']
            acc_y = acceleration['y']
            acc_z = acceleration['z']
            writeAccelerationToCsv(acc_x,acc_y,acc_z)
            time.sleep(.250)
            counter+=1

            #Region Data
            if(counter == 4):
                temperature = sense.get_temperature()
                temperature2 = sense.get_temperature_from_humidity()
                temperature3 = sense.get_temperature_from_pressure()

                pressure = sense.get_pressure()
                humidty = sense.get_humidity()

                orientation = sense.get_orientation()
                yaw = orientation["yaw"]
                pitch = orientation["pitch"]
                roll = orientation["roll"]

                mag = sense.get_compass_raw()
                mag_x = mag["x"]
                mag_y = mag["y"]
                mag_z = mag["z"]

                gyro = sense.get_gyroscope_raw()
                gyro_x = gyro["x"]
                gyro_y = gyro["y"]
                gyro_z = gyro["z"]

                writeDataToCsv(temperature, temperature2, temperature3,     pressure, humidty, yaw, pitch, roll, mag_x, mag_y, mag_z, gyro_x, gyro_y,     gyro_z)

                counter = 0;
    except Exception as e:
        with open('log.csv', mode='a') as file:
            writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
            writer.writerow([datetime.datetime.now(),str(e)])
            sense.set_pixel(1, 0, red)
    finally:
        pass
        main()

if __name__ == '__main__':
    main()

Do not call main recursively. You are setting yourself up for stack overflow. Consider instead

def main():
    while True:
        try:
            your_logic_here
        except Exception as e:
            your_logging_here

Testing for counter == 4 is better done in a loop:

    for _ in range(4):
        handle_acceleration
    handle_the_rest

An unattended controller should handle exceptions more diligently. For sure, you want to act differently for the exceptions raised by sense (if any) vs exceptions raised by writing to the file.
Regarding battery, avoid binary-to-text conversions. Store your data as binary, and convert them to CSV offline, after the Pi safely returns.


Project Euler problem 4 in Ruby A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
  Find the largest palindrome made from the product of two 3-digit numbers.

I started out with this solution. It's iterative, and not very efficient. It multiplies all number combinations, adds the products to an array, finds the palindromes, then chooses the max.

def palindrome?(number)
  number.to_s == number.to_s.reverse
end

def largest_palindrome(range = 1..999)
  array = []
  range.each do |x|
    range.each do |y|
      array.push(x * y)
    end
  end
  array.select { |n| palindrome?(n) }.max
end
puts largest_palindrome

I improved with my second iteration, but it still relies on iteration. I narrowed the range down reasoning that the largest palindrome is likely to be the product of two numbers within 901 and 999. This time I multiplied all the numbers, but only saved the palindromes in the array, then selected max, which saved a step. It's noticeably faster, but still not optimal.

def largest_palindrome(range = 1..99)
  palindromes = []
  range.end.downto(range.begin).each do |x|
    range.end.downto(range.begin).each do |y|
      palindromes << x * y if palindrome?(x * y)
    end
  end
  palindromes.max
end

puts largest_palindrome 901..999

My reasoning about narrowing the range feels like cheating. It's intuitive, and arbitrary.

Algorithm

You can increase the efficiency of the algorithm by making use of two facts (particularly the second one):

Given m and n, m < n, the largest palindrome m*j, m < j <= n, if there are any, is the one for which j is largest.  In other words, with m fixed, we can look for palindromes m*j, beginning with j = n and then successively reduce j until either a palindrome is found or we conclude there are no palindromes m*j for m < j <= n. If a palindrome mk is found, then (for fixed m) there is no need to consider values of j for which m < j < k, as we have found the largest palindrome whose smaller factor equals m and whose larger factor is between m+1 and n.
If a palindrome k*l has been found, where k < l <= n, then in order for i*j > k*l, where i < k, i < j <= n, we see that j > k*l/i (regardless of whether i*j is a palindrome).  In other words, there is no need to check to see if i*j is a palindrome for j <= k*l/i, as it cannot be larger than the currently largest known palindrome.  Moreover:

if i*j, is found to a palindrome, where k*l/i < j <= n, it becomes the currently largest known palindrome; and
if k*l/i > n, we are finished, as no product e*f, e <= i, e < f <= n, can be larger than the currently largest known palindrome.

These two observations are implemented in a straightforward way by the code that follows.

Code

def largest_palindrome(low=1,n)
  best = { product: false }
  (n-1).downto(low) do |start1|
    start2 = best[:product] ? (best[:product]/start1.to_f).ceil : start1+1
    break if start2 > n
    found2 = n.downto(start2).find { |j| palindrome?(start1*j) }
    best = { product: start1*found2, v1: start1, v2: found2 } if found2
  end
  best
end

def palindrome?(n)
  (s = n.to_s) == s.reverse
end

Examples

largest_palindrome(99)
  # {:product=>             9,009, :v1=>       91, :v2=>      99,
  # :smaller_at_term=>         90, :nbr_palins=>1, :soln_time=>"0.00004"}
largest_palindrome(999)
  # {:product=>           906,609, :v1=>      913, :v2=>      993,
  #  :smaller_at_term=>       907, :nbr_palins=>2, :soln_time=>"0.00101"}
largest_palindrome(9,999)
  # {:product=>        99,000,099, :v1=>     9901, :v2=>     9999,
  #  :smaller_at_term=>    9,900,  :nbr_palins=>1, :soln_time=>"0.00178"}
largest_palindrome(99,999)
  # {:product=>     9,966,006,699, :v1=>    99681, :v2=>    99979,
  #  :smaller_at_term=>     99661, :nbr_palins=>1, :soln_time=>"0.02040"}
largest_palindrome(999,999)
  # {:product =>  999,000,000,999, :v1=>  999,001, :v2=>  999,999,
  #  :smaller_at_term=>   999,000, :nbr_palins=>1, :soln_time=>"0.20434"}
largest_palindrome(9,999,999)
  # {:product=>99,956,644,665,999, :v1=>9,997,647, :v2=>9,998,017,
  #  :smaller_at_term=> 9,995,665, :nbr_palins=>1, :soln_time=>"2.05677"}

I have formatted the numbers to make them easier to read and also added three statistics I thought might be of interest:

the value of the smaller of the two factors when the search was terminated;
the number of palindromes found before the search terminated; and
the solution time in seconds (on a newish Mac).

To see where each search terminated, divide best[:product] by n, round up and subtract 1. For example, for n = 9999, this would be:

(99000099/9999.0).ceil - 1 #=> 9900

This shows that when determining the largest palindrome for numbers up to 9,999, it was only necessary to consider pairs with values greater than 9,900. Hence, at most (9999-9900)*(9999-9901) => 99*98 => 9,702 pairs were examined, which is 0.0097% of all 9999*9998 => 99,970,002 pairs of numbers up to 9,999.

For n = 999, two palindromes were found before the search terminated. In each of the other four examples, only one palindrome (i.e., the largest) was found before the search terminated.


Binomial coefficient in Java Find nCr for given n and r.

  Input:

  First line contains no of test cases T, for every test case 2
  integers as inputs (n,r).

  Output:

  Compute and print the value in separate line. Modulus your
  output to 10^9+7. If n

  Constraints:

  1<=T<=50

  1<=n<=1000

  1<=r<=800

  Example:

  Input:

  1

  3 2

  Output:

  3

My approach:

import java.util.Scanner;
import java.lang.Math;
import java.math.BigInteger;

class GFG {

    private static int calcBinCoeff (int num, int r) {

        BigInteger numerator = new BigInteger("1");
        int limit = (int)(Math.pow(10,9) + 7);
        BigInteger modulus = new BigInteger(String.valueOf(limit));

        for (int i = num; i > num - r ; i--) {
            BigInteger ind = new BigInteger(String.valueOf(i));
            numerator = numerator.multiply(ind);
        }

        BigInteger fact = new BigInteger("1");

        for (int i = 2; i <= r; i++) {
            BigInteger elem = new BigInteger(String.valueOf(i));
            fact = fact.multiply(elem);
        }

        BigInteger ans = (numerator.divide(fact)).mod(modulus);

        return ans.intValue();
    }

    public static void main (String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            int numTests = sc.nextInt();

            while (numTests-- > 0) {
                int num = sc.nextInt();
                int r = sc.nextInt();

                System.out.println(calcBinCoeff(num, r));
            }
        }

    }
}

I have the following questions with regards to the above code:

1.Is there a smarter way to approach this question?

How can I improve the space and time complexity of the given question?
Have I gone too overboard by using BigInteger Library for this question?

Reference

Is there a smarter way to approach this question?

We'll see in a moment. Parts of it can be improved for sure.

How can I improve the space and time complexity of the given question?

You can't. The complexity will remain the same. The changes you can make might give small increases in performance or decrease memory usage, but the complexity will remain the same.

Have I gone too overboard by using BigInteger Library for this question?

I thought at first that it was possible to use just long, but I'm afraid not. Because of 1000 nCr 500, and such big numbers, you are stuck with BigInteger.

You can use BigInteger.valueOf instead of using the constructor with a String.

You can save some time by using the symmetric property of nCr if r > n / 2. For example, 100 nCr 80 is the same as 100 nCr 20.

You can use just one for-loop instead of two:

value = 1;
for (int i = 0; i < r; i++) {
    value = value * (n - i) / (i + 1);
}
return value;

I used something similar in a project of mine (where I used double instead and thus didn't have to think about truncating integers - an issue which is fixed above thanks to Martin R).


Fast incremental backup algorithm using RSYNC I'm running a simple Bash script that uses rsync to do an incremental backup of my web server every hour. What I'm looking for is an efficient algorithm to delete the proper backups so that in the end I keep:

Hourly backups for 24 hours.
Daily backups for 1 week.
Weekly backups for 1 month.
Monthly backups from that point on.

I'll figure out when to delete the monthly backups based upon when I run out of space. So we're not worried about that. I'm also familiar with the various wrappers for rsync like rdiff-backup and rsnapshot but those aren't necessary. I prefer to write code myself whenever possible even if it means reinventing the wheel sometimes. At least that way if I get a flat tire I know how to fix it :)

Here's the actual commented code that runs every hour:

#if it's not Sunday and it's not midnight
if [ $(date +%w) -ne 0 ] && [ $(date +%H) -ne 0 ]; then
    #remove the backup from one day ago and one week ago
    rm -rf $TRG1DAYAGO
    rm -rf $TRG1WEEKAGO
fi

#if it's Sunday
if [ $(date +%w) -eq 0 ]; then
    #if it's midnight
    if [ $(date +%H) -eq 0 ]; then
        #if the day of the month is greater than 7
        # we know it's not the first Sunday of the month
        if [ $(date +%d) -gt 7 ]; then
            #delete the previous week's files
            rm -rf $TRG1WEEKAGO
        fi
    #if it's not midnight
    else
        #delete the previous day and week
        rm -rf $TRG1DAYAGO
        rm -rf $TRG1WEEKAGO
    fi
fi

Basically:

If it's not Sunday and it's not 3am:

  - delete the backup from one day ago

  - delete the backup from one week ago

If it is Sunday:

    If it is Midnight:

        If the day of the month is greater than 7:

            -delete the backup from one week ago

    Else (if it's not Midnight)

      - delete the backup from one day ago

      - delete the backup from one week ago

That seems to work but I'm wondering if anyone can come up with a simpler, more efficient algorithm or add any ideas for a better way of accomplishing this.

That seems to work but I'm wondering if anyone can come up with a simpler, more efficient algorithm or add any ideas for a better way of accomplishing this.

I think so. Use a naming scheme with a common prefix, and a variable suffix depending on the period, for example:

Hourly backups for 24 hours: hourly-$(date +%H).gz, results in:

hourly-00.gz
hourly-01.gz
hourly-02.gz
... and so on until hourly-23.gz after which it starts over from hourly-00.gz

Daily backups for 1 week: daily-$(date +%a).gz, results in:

daily-Sun.gz
daily-Mon.gz
daily-Tue.gz
... and so on until daily-Sat.gz, after which it starts over

Weekly backups for 1 month: weekly-$(($(date +%W) % 4)).gz, results in:

weekly-00.gz
weekly-01.gz
weekly-02.gz
weekly-03.gz after which it starts over from weekly-00.gz

You'll never have to delete anything. You will have the same set of files,
and rsync (with appropriate parameters) will copy only the changed ones.

As for the posted code,
the single biggest problem is the duplicate calls to $(date ...) with the same parameters:

Inefficient: multiple unnecessary process executions
Bad practice: duplicated logic
Unnecessary and error prone: the multiple calls to $(date +%w) (for example) probably expect to get the same result. So there should be only one call, saved in a variable. If the day happens to turn between two calls, may have a nasty bug, and in any case it's completely unintended situation.


Cyclic iterator in both directions I am trying to make a cyclic iterator that works backwards and forwards. getNext() gets the next array item, getPrevious() gets the item before the last returned one from getNext(). This seems to work, but there must be a better way. How can this be refactored?

var cyclicIterator = function (arr) {
    var index = 0;
    var length = arr.length;
    var current;
    return {
        getNext: function () {
            current = arr[index];
            index = (index + 1) % length;
            return current;
           },
        getPrevious: function () {
            index = arr.indexOf(current);
            if (index === 0) {
                index = length - 1;
            }
            else {
                index = index - 1;
            }
            current = arr[index]
            return current;
        }
    };
};

Is there any reason why getPrevious resorts to using indexOf? As far as I can tell, it can only cause problems.

For instance:

var array = [1, 2, 3];
var iterator = cyclicIterator(array);

iterator.getPrevious();

Since current is declared but hasn't been assigned a value, this will call  arr.indexOf(undefined) and then proceed to subtract 1 from that. I doubt that's going to work out.

Alternatively, I might do this:

var array = [1, 2, 3];
var iterator = cyclicIterator(array);
iterator.getNext(); // current is now 1
array[0] = 2;       // change the first element in the array
iterator.getPrevious();

Now, getPrevious will call arr.indexOf(1) and get -1. And it will then subtract 1 from that. Again, I doubt it'll work out.

I'd also wonder why there's no getCurrent function. In fact that's what getNext does. It for some reason returns the current index, only incrementing the index afterwards. Meanwhile getPrevious decrements the index before returning anything.

You also store the length of the array when you receive it, which could lead to some weird stuff if the array is later modified.

For instance:

var array = [1, 2, 3];
var iterator = cyclicIterator(array);
iterator.getNext(); // index is now 1
array.splice(3);    // clear the array
iterator.getNext();

That last call will calculate 2 % 3 which is, well, 2. But that index doesn't exist anymore.

You could simply skip caching the length, but that could still get weird. getNext would start skipping places when "looping around", if the array's been truncated after the iterator was created.

var array = [1, 2, 3];
var iterator = cyclicIterator(array);
iterator.getNext(); // index is now 1
iterator.getNext(); // index is now 2
array.pop();        // remove one item from the array
iterator.getNext();

With no caching of the length, the last call will calculate (2 + 1) % 2 which is 1. But that'll skip index 0.

So I'd simply copy the array, to make sure there's always something to work with.

I'd do this instead:

var cyclicIterator = function (array) {
    var index = 0;
    var copy = array.slice(0);

    return {
        getCurrent: function () {
            return copy[index];
        },

        getNext: function () {
            index = ++index % copy.length;
            return this.getCurrent();
        },

        getPrevious: function () {
            if(--index < 0) {
              index += copy.length;
            }
            return this.getCurrent();
        }
    };
};


Asking for GPS and Internet permissions private void loadTabsIfGPSAndInternetAvailable()
    {
        final Utils utils = new Utils(this);
        final LocationClient locationClient = new LocationClient(this);
        if (!utils.isConnected())
        {
            utils.generateNoConnectivityAlert();
        }
        else if (!locationClient.hasGPS())
        {
            utils.generateNoGPSAlert();
        }
        else
        {
            if (androidVersion >= Build.VERSION_CODES.M)
            {
                requestAllPermissions();
            }
            else
            {
                loadCameraAndForecastTabs();
            }
        } // ends else block for if internet and GPS are enabled
    }

This is some code that loads tabs if the GPS and internet connectivity are available.  I'm aware that at the moment this is very messy code, with lots of nested if statements, that is hard to read, and am not sure how to structure it better.  Can people help me please?

Well, you don't need to use nested if statements here, but an if / else if ... chain seems unavoidable.

You can neaten up the code like this.  Note: 12 lines of code instead of 25.

private void loadTabsIfGPSAndInternetAvailable() {
    final Utils utils = new Utils(this);
    if (!utils.isConnected()) {
        utils.generateNoConnectivityAlert();
    } else if (!(new LocationClient(this).hasGPS())) {
        utils.generateNoGPSAlert();
    } else if (androidVersion >= Build.VERSION_CODES.M) {
        requestAllPermissions();
    } else {
        loadCameraAndForecastTabs();
    }
}

However, I suspect that there is something wrong with the logic of your original code ... which would make my refactoring incorrect as well.


Search for the longest sequence of toggled consecutive bits in an integer I have to do a function called findsaw. This function searches for the longest sequence of toggled consecutive bits in an integer and returns the index of the first bit of the sequence, the sequence must start from the least significant bit.

In the case there are multiple answers(sequences with same size) choose the one with lowest start index.

Function signature:

unsigned int findsaw(int value)

Some test cases:

findsaw(0x0) returns 0
findsaw(0xAA) returns 0
findsaw(0xA0F) returns 8
findsaw(0xF0A) returns 0
findsaw(0xFA0) returns 4
findsaw(0xEAEA476BL) returns 23

My code:

#include <stdio.h>
#define YES 1 /* inside a sequence */
#define NO 0 /* outside a sequence */

unsigned int findsaw(int value){
    unsigned int sequence = value;
    unsigned char idx = 0;
    unsigned char sequenceIdx = 0;
    unsigned char currentIdx = 0;
    unsigned char size = 0;
    unsigned char sequenceSize = 0;
    unsigned char bit = value & 1;
    unsigned char nextBit;
    unsigned char insideSequence = NO;

    while (sequence){
        sequence>>= 1;
        nextBit = sequence & 1;
        if(bit ^ nextBit){
            if(insideSequence){
                sequenceSize++;
            }
            else{
                sequenceSize = 2;
                sequenceIdx = currentIdx;
                insideSequence = YES;
            }
        }
        else{
            if(size < sequenceSize){
                size = sequenceSize;
                idx = sequenceIdx;
            }
            insideSequence = NO;
            sequenceSize = 0;
        }
        currentIdx++;
        bit = nextBit;
    }
    if(size < sequenceSize){
        idx = sequenceIdx;
    }
    return idx;
}

What would be the correct output for all 1's like findsaw(0xF), my function returns the index of the last bit, in this case 3?

Before we make any changes, let's add some tests to the end, so we have confidence that we don't break anything that worked:

#include <stdio.h>
static int test(unsigned int value, unsigned int expected)
{
    unsigned int actual = findsaw(value);
    if (actual == expected)
        return 0;
    printf("findsaw(%#x) = %u\n", value, actual);
    return 1;
}

int main()
{
    return test(0x0, 0)
        +  test(0xAA, 0)
        +  test(0x585, 0)
        +  test(0xA0F, 8)
        +  test(0xF0A, 0)
        +  test(0xFA0, 4)
        +  test(0xEAEA476Bu, 23);
}

This all passes (the program returns 0).  I made test take the value as an unsigned int, because 0xEAEA476B is too big for a plain int on my system.

Now let's look at your code.

#include <stdio.h>
#define YES 1 /* inside a sequence */
#define NO 0 /* outside a sequence */

We're not using anything from <stdio.h>, so that's not required.  Also, instead of defining YES and NO in the preprocessor, we could include <stdbool.h>, and then use true and false instead.

unsigned int findsaw(int value) {
    unsigned int sequence = value;

Are you required to accept input as a signed integer?  If not, then declare findsaw() to take an unsigned int.  As it is, the last test case (from the question's code) produced a compilation warning, as 0xEAEA476BL is larger than INT_MAX on my system.

unsigned char idx = 0;
unsigned char sequenceIdx = 0;
unsigned char currentIdx = 0;
unsigned char size = 0;
unsigned char sequenceSize = 0;
unsigned char bit = value & 1;
unsigned char nextBit;

None of these really need to be char.  It's probably better to let them be int (or uint_fast8_t if you're really keen).

These names aren't immediately obvious to me (or to you in six months' time).  It might be worth grouping them so that idx and size, which represent the best match so far, are placed together, with a comment explaining that.  Similarly, sequenceIdx and sequenceSize seem to represent the current in-progress match, and should go together.

Some of the naming was alien to me: I'd have considered what you call the "next" bit to be "current", and what you call just "bit" to be "last_bit".  That might be just me, though.

    if (bit ^ nextBit) {

A comment would be nice here: this is true when we're matching the sawtooth pattern.  Also, the else branch contains actions that are only needed immediately at the end of a sequence, and do nothing for extended runs such as 0x00 or 0xFF, so that can be else if (insideSequence).

We can save a bit of work here:

        /* matched a transition */
        if (insideSequence) { /* just add to the size */
            sequenceSize++;
        } else {
            /* initialize for inside a sequence */
            sequenceSize = 2;
            sequenceIdx = currentIdx;
            insideSequence = true;
        }

If we initialise sequenceSize to 1 instead of 0, then we can simply increment it in both cases (i.e. outside the if).  We can use sequenceSize == 1 to determine whether we're in a sequence, and we no longer need the insideSequence variable (nor <stdbool.h>):

unsigned int findsaw(unsigned int value) {
    unsigned int sequence = value;

    /* best match so far */
    unsigned int best_start = 0; /* this is what we're looking for */
    unsigned int best_size = 0;

    unsigned int sequenceIdx = 0;
    unsigned int currentIdx = 0;
    unsigned int sequenceSize = 1;

    while (sequence) {
        const int last_bit = sequence & 1;
        sequence >>= 1;
        const int current_bit = sequence & 1;
        if (last_bit ^ current_bit) {
            /* matched a transition */
            if (sequenceSize++ == 1) {
                /* the start of a new sequence */
                sequenceIdx = currentIdx;
            }
        } else if (sequenceSize != 1) {
            /* not matched - did we just finish a sequence? */
            if (best_size < sequenceSize) {
                best_size = sequenceSize;
                best_start = sequenceIdx;
            }
            sequenceSize = 1;
        }
        ++currentIdx;
    }
    if (best_size < sequenceSize) {
        best_start = sequenceIdx;
    }
    return best_start;
}

Let's see if we can do anything about the duplication of if (best_size < sequenceSize) when we reach the last bit.  I'll add a couple of extra tests:

    +  test(0x50000005u, 27)
    +  test(0xA0000005u, 0)

The last one fails (returns 28), because we are zero-extending the left of the value, but not the right.  If we simply take out the test, then other test cases fail (0xa0f and 0x50000005).  It seems that the while (sequence) returns too early in those cases.

At this point, I give up fixing this and look at a different approach.  We don't need to check last_bit ^ current_bit every time around the loop - we can compute them all at the same time like this:

unsigned int sequence = value;
unsigned int mask = sequence ^ (sequence >> 1);

This produces a 1 everywhere we have a bit preceded by its complement.  We still have the problem that the high bit might be set, but we can fix this by writing mask = sequence ^ (sequence << 1) to make the low bit the stray one, and we can just shift that out.  Now, all we have to do is find the longest run of 1s:

unsigned int findsaw(unsigned int value)
{
    unsigned int sequence = value;
    unsigned int mask = sequence ^ (sequence << 1);

    /* best match so far */
    unsigned int best_start = 0; /* this is what we're looking for */
    unsigned int best_size = 0;

    /* current run */
    unsigned int current_start = 0;
    unsigned int current_size = 0;

    /* current position */
    for (unsigned int i = 0;  mask >>= 1;  ++i) {
        if (mask & 1) {
            if (!current_size++)
                /* the start of a new run */
                current_start = i;
        } else if (current_size) {
            current_size = 0;
        }

        if (current_size > best_size) {
            best_size = current_size;
            best_start = current_start;
        }
    }

    return best_start;
}

#include <stdio.h>
static int test(unsigned int value, unsigned int expected)
{
    unsigned int actual = findsaw(value);
    if (actual == expected)
        return 0;
    printf("findsaw(%#x) = %u\n", value, actual);
    return 1;
}

int main()
{
    return test(0x0, 0)
        +  test(0xAA, 0)
        +  test(0x585, 0)
        +  test(0xA0F, 8)
        +  test(0xF0A, 0)
        +  test(0xFA0, 4)
        +  test(0xEAEA476Bu, 23)
        +  test(0x50000005u, 27)
        +  test(0xA0000005u, 0);
}

All the tests pass; time to go home.


C++ string Formatter Again Part-2 Previously asked here.
The code is now available on GitHub.
Since the previous review I have added unit tests.
Since it is big it will come in a couple of parts.
Part 1 | Part 2 | Part 3 | Part 4
Part 2
This is a simple helper object. It stores the result of parsing the string in an object. This way we don't need to re-parse the string for information.
FormatInfo.h
#ifndef THORSANVIL_IOUTIL_FORMAT_INFO_H
#define THORSANVIL_IOUTIL_FORMAT_INFO_H

#include <iostream>
#include <typeinfo>

namespace ThorsAnvil::IOUtil
{

// Enum representing the Length, specifier and type information provided by the format string
#pragma vera-pushoff
                                                                                // printf doc http://www.cplusplus.com/reference/cstdio/printf/
enum class Length    {none, hh, h, l, ll, j, z, t, L};                          // Use the same values as in printf documentation so it is easy to lookup
enum class Specifier {d, i, u, o, x, X, f, F, e, E, g, G, a, A, c, s, p, n};    // Use the same values as in printf documentation so it is easy to lookup
enum class Type      {Int, UInt, Float, Char, String, Pointer, Count};          // The type we are expecting
enum class Dynamic   {None, Width, Precision, Both};                            // If width and/or precision are specified by parameter
#pragma vera-pop

using AllowedType = std::pair<std::type_info const*, int>;

struct FormatInfo
{
    // Formatter has the text representation:
    //      %<Flag>*<Width>?[.<Precision>]?<Length>?<Specifier>
    //
    //      Flag:       - + <space> # 0
    //      Width:      {1-9}{0-9}*
    //      Precision:  {0-9}*
    //      Length:     hh h l ll j z t L
    //      Specifier:  d i u o x X f F e E g G a A c s p n

    // Flags
    bool                    leftJustify;    // -    Left-justify within the given field width; Right justification is the default (see width sub-specifier).
    bool                    forceSign;      // +    Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
    bool                    forceSignWidth; // (space)  If no sign is going to be written, a blank space is inserted before the value.
    bool                    prefixType;     // #    Used with o, x or X specifiers the value is preceded with 0, 0x or 0X respectively for values different than zero.
                                            //      Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
    bool                    leftPad;        // 0    Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
    // Width and precision of the formatter.
    std::size_t             width;
    std::size_t             precision;
    Length                  length;
    Specifier               specifier;

    // Pre-calculate a some values based on the format string
    Type                    type;           // Calculated based on length/specifier
    Dynamic                 useDynamicSize; // Are width/precision dynamically specified.
    AllowedType             expectedType;   // Type info we expect the next argument to be based on length/specifier
    std::ios_base::fmtflags format;         // The format flags that will be applied to stream before the next argument

};

}

#endif

Very little code prompts a very small review. Here are a few things that came to my mind:

Includes

One issue is definitely that you are missing #include <utility> for std::pair, as well as #include <cstddef> (or similar) for std::size_t.

Another thing that might turn out to make some people angry at you is the fact that you #include <iostream>. The reason for this is that this header injects some static initializers into the current compilation unit which initialize the special streams it provides, which in turn leads to binary bloat and a possible performance reduction (take a look at the assembly that your header generates).

On almost all occasions, #include <iostream> can be avoided by including one of several other headers, in you case #include <ios>, which provides std::ios_base.

Ugh, std::type_info

Usually, seeing std::type_info around is setting off some alarm bells for me. The cause for this is not that there is anything inherently wrong with std::type_info, but that most things it could be used for are better expressed through polymorphism or compile time template switching.

From the single file you provide, I cannot possibly tell whether that is the case with your code or not. However, passing a pointer to some std::type_info around together with an int does hint at somewhat dubious practices. Please reevaluate whether the use of std::type_info is really appropriate.

Comments

// Enum representing the Length, specifier and type information provided by the format string

seems borderline unnecessary to me. What the enums represent is already made sufficiently clear by their name, only the information bit linking them to the whole format string functionality is not given in the code (however, since the header is named FormatInfo.h, I would say this information is implied).

// printf doc http://www.cplusplus.com/reference/cstdio/printf/
// Use the same values as in printf documentation so it is easy to lookup
// Use the same values as in printf documentation so it is easy to lookup
// The type we are expecting
// If width and/or precision are specified by parameter

That first comment is bad, because linking to external resources is subject to link rotting. Only do so when the information that is provided there is not easily available anywhere else. In the case of printf parameters this is not the case; most POSIX-compliant systems even have a manpage explaining them thoroughly. Furthermore, the use of printf is so ubiquitous that I'd say it is acceptable to assume users are able to find documentation on their own.

The next two comments are exactly the same and should be coerced into a single commit above the two applying enums.

Both of the last comments do not at a whole lot of valuable information to the code, so I'd say you should omit them.

Structure

FormatInfo seems to contain three separate "blocks" of information/settings. Since these blocks each mark a certain category of information, I would have made nested structs for them. My suggestion would look something akin to this:

struct FormatInfo {
    struct Flags {
        bool leftJustify;
        bool forceSignWidth;
        bool prefixType;
        bool leftPad;
    };

    struct Dimension {
        std::size_t width;
        std::size_t precision;
        Length length;
        Specifier specifier;
    };

    struct FormatSettings {
        Type type;
        Dynamic useDynamicSize;
        AllowedType expectedType;
        std::ios_base::fmtflags format;
    };

    Flags flags;
    Dimension dimension;
    FormatSettings formatSettings;
};

which encapsulates the different setting groups better.

Depending on your use case, there is also a point in making the four enums from the top of your file part of FormatInfo if this makes sense from a structural point of view (again, I don't have an overview of your whole project structure).

Apart from the mentioned points, some points of my answer to Part 1 also apply here, for example the point about indentation.


Query, populate, show, hide data I have created code to show/hide data from a DB.  It works, but as I am new to jQuery, I would like to know if this is a good way.

HTML:

    <? echo $sn; ?>
    <? echo $last_change; ?>
    <? echo $comment; ?>
    <? echo $model_name; ?>
    <a class="more" data-name="<? echo $id; ?>" href="">+

jQuery:

$(function () {
    $(".more").live("click", function () {
    var onMe =$(this);
    var detailsConteiner = $(onMe).next('div');
    var forLoader = $(onMe).parent("li");

        if ($(onMe).text() == "+") {

            $(devInfo).children("span").css({"text-indent":"", "text-overflow":""});
            $(forLoader).fadeIn(400).prepend('');
            $(onMe).text("-")
            $(devInfo).css("background", "");
            $(forLoader).css("background", "#d6e5f4");
            $(onMe).siblings("span").css({"text-indent":"1000px", "text-overflow":"clip"});

            $(detailsConteiner).empty();
            $(details).slideUp(1000);

            var value = $(onMe).attr("data-name");
            var dataString = 'deviceId=' + value;

            $.ajax({
                type: "POST",
                url: "helpers/getDetails.php",
                data: dataString,
                cache: false,

                    success: function (html) {

                        $(detailsConteiner).prepend(html).slideDown(500);
                        $(forLoader).children("img").fadeOut(600);

                    }
            });
            return false;
        }
        else {

            $(details).slideUp(700);
            $(onMe).text("+");
            $(forLoader).css("background", "");
            $(onMe).siblings("span").css({"text-indent":"", "text-overflow":""});
            return false;
        }
    });
});

Ajax response:

Id: <? echo $id; ?>

Serial: <? echo $sn; ?>

Model: <? echo $model_name; ?>

Comment:<? echo $comment; ?>

Last Change<? echo date('d.m.Y', strtotime($last_change)); ?>

CSS:

.devInfo  img {
    margin-bottom:.25em;
    margin-left:1.25em;
    vertical-align:middle;
margin-left:25px;
 }

li.expanded {
    background-color: #d6e5f4;
}

li.expanded span {
    text-indent: -1000px;
    text-overflow:clip;
}

JS:

*function showDetails() // is not needed as the function insertDetails is doing job

function hideRestOfLI() {
         $(".details").slideUp(1000);
    }

function expand() {
        hideRestOfLI();
        $(".devInfo").removeClass(ExpandClass);
        $(".more").text(ColapsedChar);
        $devInfo.addClass(ExpandClass);
        $moreLink.text(ExpandedChar);

    }

 completed: hideLoading // complete: hideLoading

There are many changes to the css through jquery that could just be handled by adding a class to devInfo.

I...

Changed some variable names for readability
Created some variable constants for readability
Created single responsibility functions for clean code
Only transformed elements to jQuery once and stored in a variable starting with '$'
Extracted out the style from js and put it in css
Prevented the link's default action from going
Added functionality to add/remove the 'expanded' class

The code is completely untested. So there is probably some syntax issues, but let me know what you think.

CSS

.devInfo a.more img {
    margin-bottom:.25em;
    margin-left:1.25em;
    vertical-align:middle;
}

.devInfo.expanded a.more {
    background-color: #d6e5f4;
}

.devInfo.expanded {
    background: url();
}

.devInfo.expanded .span {
    text-indent: 1000px;
    text-overflow: clip;
}

JS

$(function () {
    var ExpandedChar = "-",
        ColapsedChar = "+",
        ExpandClass = 'expanded';

    var toggleDetails = function(event) {
        event.preventDefault();

        var $moreLink = $(this),
            $details= $moreLink.next('.details'),
            $devInfo = $moreLink.closest('.devInfo');

        var displayLoading = function() {
            $devInfo.prepend(buildLoadImage()).fadeIn(400);
        };

        var hideLoading = function() {
            $devInfo.children("img").fadeOut(600);
        };

        var insertDetails = function(html) {
            $details.prepend(html).slideDown(500);
        };

        var getDetailsFor = function(deviceId) {
            $.ajax({
                 type: "POST",
                 url: "helpers/getDetails.php",
                 data: {deviceId: deviceId},
                 cache: false,
                 beforeSend: displayLoading,
                 success: insertDetails,
                 completed: hideLoading
             });
        }

        if (isColapsed()) {
            expand();
            getDetailsFor($moreLink.attr("data-name"));
        } else {
            colapse();
        }

        function expand() {
            $devInfo.addClass(ExpandClass);
            $moreLink.text(ExpandedChar);
            showDetails();
        }

        function showDetails() {
            $details.slideUp(1000);
        }

        function colapse() {
            $devInfo.removeClass(ExpandClass);
            $moreLink.text(ColapsedChar);
            hideDetails();
        }

        function hideDetails() {
            $details.slideUp(700);
        }

        function isColapsed() {
            return $moreLink.text() == ColapsedChar;
        }

        function buildLoadImage() {
            return $('<img />').attr('src', '/images/css/loader_small.gif');
        }
    }

    $(".more").live("click", toggleDetails);
});


Determine whether bitwise-OR of sub-array is odd Problem:
Given an array A of N integers, you will be asked Q queries. Each query consists of two integers L and R. For each query, find whether bitwise OR of all the array elements between indices L and R is even or odd.
My approach:
Accept the array of N integers. For any query (Qi) scan the array of integers between the given limit. If an odd number is found (x%2==1) then raise a flag and terminate scanning. If flag is found raised tell that the result is odd, else say that it's even.
On thinking further, I find myself at the dead end. I can't optimize the code anymore. Only thing I can think of is instead of doing mod 2 I will check the last digit of each number and see if it is one of [0,2,4,6,8]. Upon trying that, the time limit still expired (in context to competitive programming [1]; Note: the competition has ended a day ago and results declared). Anyways, my question is to find a better method if it exists or optimize the code below.
I assume that the time complexity is O(nQ) where n is the number of elements in the given range.

The code O(nq)
Assume array is 1-indexed.
Input
First line consists of two space-separated integers N and Q.
Next line consists of N space-separated array elements.
Next Q lines consist of two space-separated integers L and R in each line.
#include<stdio.h>
#pragma GCC optimize("O2")

int main()
{
    long int c,d,j,N,Q;
    int fagvar=0;
    scanf("%ld %ld\n",&N,&Q);
    int a[N];
    int i=0;
    while(N--)
    {
        scanf("%ld",&a[i]);
        i++;
    }
    while(Q--)
    {
        scanf("%ld %ld",&c,&d);
        for(j=c-1;j<d;j++)
        {
            if (a[j]%2==1)
            {
                fagvar=1;
                break;
            }
        }
        if (fagvar==1)
        {
            printf("%d\n",0);
            fagvar=0;
        }
        else
        {
            printf("%d\n",1);
        }
    }
    return 0;
}

After 2 answers and a rethinking of algorithm, the final complexity falls at O(n+q). Note: Since this was a competitive problem and I probably won't revisit the same program I haven't added any extra readability. The reader is free to edit my code as required. For the algorithm, visit Toby Speight's comment section.
Visit here for the code. For an amalgamation of spanning over even numbers and Toby's method, visit here.

Code

#pragma GCC optimize("O2")

Normally we just pass that as a compiler flag, so we don't get "unrecognised pragma" warnings from other compilers.

    long int c,d,j,N,Q;

These are poor names - they tell us very little about what they are used for.
The number of array elements and the number of queries can't be negative.  I suggest size_t (from <stdint.h>) would be better than long for these.  Also consider what range is required for the other values (the challenge should state these bounds).  You might want to use the int_fastX_t and int_leastX_t families to ensure the required range.

    scanf("%ld %ld\n",&N,&Q);

Don't throw away the return value from scanf() like that.  It's important to know how many conversions were successfully performed before attempting to use the assigned values.
Algorithm
This is on average, much less computation than the naive brute-force algorithm, since we stop examining the array once we find an odd number.
Something to consider, especially for programming challenges, is that we often talk of average-case complexity using big-O notation, but it can be more helpful to think like an adversary: "What's the worst-case input this algorithm could be given?".  The test cases are likely to include some arrays which are all odd or all even - the former being very expensive for this algorithm.
If we have many queries, we can spend a little time creating a structure to make each query constant-time.  The way I would approach this is probably to have an array of size_t that stores the running count of odd numbers.  Then, given a query Q(m,n), look at odd_count[n]; if it's equal to odd_count[m], we have only even numbers in the range, else we have at least one odd number.  Note that we don't need to actually store the input array, as we'll only use the running total.  Obviously, adjust m and n before lookup if these are inclusive in the challenge (it's a little unclear in your summary, but I assume more rigorously defined in the original).


Multiple serial URL requests in Objective-C / iOS I want to check the existence of various API endpoints by doing serial URL request. If the first one fails, I want to try the second one, if the second fails I want to try the third one, etc.

Here is some code I use to do this:

self.apiEndpoint = kApiAjaxEndpoint;
[self testEndpointWithBlock:^(id response, NSError *error) {
    if (error) {
        self.apiEndpoint = kApiAjaxLegacyEndpoint;
        [self testEndpointWithBlock:^(id response, NSError *error) {
            if (error) {
                self.apiEndpoint = kApiRestEndpoint;
            }
            [self saveApiEndpoint];
        }];
    } else {
        [self saveApiEndpoint];
    }
}];

So for now I'm only testing for 2 API endpoints but the moment I add a new endpoint I would need to add another call to testEndpointWithBlock: with error handling code.

I was wondering if you can think of a more elegant way of doing this?

Create several instances of NSOperation
Set dependencies so that one runs after another.
Add to a private NSOperationQueue.
Cancel all operations in a queue if a match is found.


Minecraft block generator This script is a tool to help minecraft mod development. When you want to add a new block to the game you have to create three json files. This script generates three JSON files in specific locations. It's intended to be run in a certain directory so that the files go into the right location. Also it's for my own personal use.

The reason I didn't use the json module is simply because I didn't feel like. If it would make this script much better then I am all for switching to that although I did enjoy writing my json methods and found it educational which is another reason I'm making this, to learn a bit of python.

It's quite long and I think the functions could be taken out into a new file but then I'll need to make sure I have both files just to run this which I don't like.

I'm not concerned about efficiency or speed, just readability and maintainability, and general best practice.

import os

# Declare Functions
def jsonStart():
    return "{\n"

def jsonEnd(indent):
    return "\n" + jsonIndent(indent) + "}"

def jsonIndent(amount):
    amount = amount * 4
    return " " * amount

def jsonKeyValue(key, value, indent = 0):
    return jsonIndent(indent) + jsonKey(key) + jsonValue(value)

def jsonKey(key, indent = 0):
    return jsonIndent(indent) + "\"" + key + "\"" + ": "

def jsonValue(value):
    return "\"" + value + "\""

def deleteCreatedFiles():
    print("\nSomething went wrong")
    for file in createdFiles:
        print("Deleting: " + file)
        os.remove(file)
    print("\n")

def createFile(filename, data):
    try:
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        with open(filename, "w+")as newFile:
            newFile.write(data)
    except:
        deleteCreatedFiles()
        raise
    else:
        createdFiles.append(os.path.relpath(newFile.name))
        print("Created" + os.path.relpath(newFile.name))

def blockStatesFile():
    data = jsonStart()
    data += jsonKey("variants", 1) + jsonStart()
    data += jsonKey("normal", 2) + "{ " + jsonKeyValue("model", modid + ":" + blockName) + "}"
    data += jsonEnd(1)
    data += jsonEnd(0)
    return data

def modelsItemFile():
    data = jsonStart()
    data += jsonKeyValue("parent", modid + ":block/" + blockName, 1) + ",\n"
    data += jsonKey("textures", 1) + jsonStart()
    data += jsonKeyValue("layer0", modid + ":items/" + blockName, 2)
    data += jsonEnd(1)
    data += jsonEnd(0)
    return data

def modelsBlockFile():
    data = jsonStart()
    data += jsonKeyValue("parent", "block/cube_all", 1) + ",\n"
    data += jsonKey("textures", 1) + jsonStart()
    data += jsonKeyValue("all", modid + ":blocks/" + blockName, 2)
    data += jsonEnd(1)
    data += jsonEnd(0)
    return data

# Run Script
createdFiles = []
blockName = input("block name: ")
modid = input("modid: ")
createFile("blockstates/" + blockName + ".json", blockStatesFile())
createFile("models/item/" + blockName + ".json", modelsItemFile())
createFile("models/block/" + blockName + ".json", modelsBlockFile())

I won't repeat @victor's answer, but Python is a language that comes with batteries included; meaning that a lot of behaviour has already been bundled into modules, and is maintained for correctness and performance. You should really avoid to reinvent the wheel if it is not for learning purposes.

Python also comes with an official style guide: PEP8, which is advised to follow if you want your code to look like Python code to others.

Your code also rely heavily on variables defined globally. This kind of code is error prone and less reusable. Instead, define arguments for your functions and pass information as parameters.

Lastly, you should avoid keeping code at the top-level of the file, protect it with an if __name__ == '__main__' guard:

import os
import json

def delete_files(files):
    for filename in files:
        os.remove(filename)

def create_file(filename, data, created_files):
    try:
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        with open(filename, "w+") as new_file:
            json.dump(data, new_file, indent=4)
    except:
        print("\nSomething went wrong")
        print("Deleting:", *created_files)
        print("\n")
        delete_files(created_files)
        raise
    else:
        filepath = os.path.relpath(new_file.name)
        created_files.append(filepath)
        print("Created", filepath)

def block_states(modid, block_name):
    return {
        'variants': {
            'normal': {
                'model': f'{modid}:{block_name}',
            },
        },
    }

def models_item(modid, block_name):
    return {
        'parent': f'{modid}:block/{block_name}',
        'textures': {
            'layer0': f'{modid}:items/{block_name}',
        },
    }

def models_block(modid, block_name):
    return {
        'parent': 'block/cube_all',
        'textures': {
            'all': f'{modid}:blocks/{block_name}',
        },
    }

def main(modid, block_name):
    created_files = []
    create_file(
            f'blockstates/{block_name}.json',
            block_states(modid, block_name),
            created_files)
    create_file(
            f'models/item/{block_name}.json',
            models_item(modid, block_name),
            created_files)
    create_file(
            f'models/block/{block_name}.json',
            models_block(modid, block_name),
            created_files)

if __name__ == '__main__':
    block_name = input("block name: ")
    modid = input("modid: ")
    main(modid, block_name)


Executing periodic tasks I am writing a code in Golang to execute a periodic function (every 2 second). According to documentation and an example I have written two programs. Can anybody tell which one is better? Also, is there another better solution?

Code 1:

package main

import (
    "fmt"
    "time"
)

func periodicFunc(tick time.Time){
    fmt.Println("Tick at: ", tick)
}

func main(){
    fmt.Println("Starting a new ticker....")

    ticker := time.NewTicker(2 * time.Second)
    go func(){
        for t := range ticker.C {
            //Call the periodic function here.
            periodicFunc(t)
        }
    }()

    quit := make(chan bool, 1)
    // main will continue to wait untill there is an entry in quit
    <-quit
}

Code 2:

package main

import (
    "fmt"
    "time"
)

func periodicFunc(tick time.Time){
    fmt.Println("Tick at: ", tick)
}
func main(){
    ticker := time.NewTicker(1 * time.Second)

    go func() {
        for {
           select {
            case <- ticker.C:
                //Call the periodic function here.
                periodicFunc(<- ticker.C)
            }
        }
     }()

    quit := make(chan bool, 1)
    // main will continue to wait untill there is an entry in quit
    <-quit
}

A vs. B type questions are seldom good questions for a code review. Often the answer is "C".

That's true this time too.

You don't need a go routine for the "ticker".
Your second implementation only waits for 1 second, instead of 2.
your "quit" channels don't need to be buffered

Why don't you just do:

func main() {
    for t := range time.NewTicker(2 * time.Second).C {
        periodicFunction(t)
    }
}


Python dictionary usage I create python dictionary based on the parsed data:

user_details['city'] = None
if api_result.get('response')[1] and api_result.get('response')[1][0]:
    api_result_response = api_result.get('response')[1][0] # city details
    if api_result_response:
        user_details['city'] = int(api_result_response.get('cid'))
        city_name = api_result_response.get('name')
if user_details['city'] and city_name:
    # do something

So, I do a lot of verifications if passed data exists, if user_details['city'] assigned etc. Is there any way to simplify that?

Another key feature to dictionaries is the dict.get(key, default) function which allows you to get a default value if the key doesn't exist. This allows you to make the code less cluttered with if statements and also try/except.

The solution is often a balance between if and try statements and default values. If you are checking correctness of values, keep the try/catch statements as small as possible.

    response = api_result.get('response', None)
    if response:
        city_name = response.get('name', '')
        try:
            user_details['city'] = int( reponse.get('cid', 0) )
        except ValueError, e:
            pass # report that the 'cid' value was bogus


Print the number of movies that was watched by more than 3 people I want to create a program that can print the number of movies that was watched by more than 3 people (data stored in a nested list as below ).

list_movies = [('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald']),
               ('Terminator',['Anne','Johnny','Peter','Ronald','Neville'])]

count2 = 0
for (movie,name) in list_movies:
    count = 0
    for (name) in list_movies:
        if name != '':
            count += 1
    if count > 3:
        count2 += 1

print(count)
print(count2)

Make it a function

This should really be a function for test ability, reuse ability

It would need to be a function which accepts 2 parameters (The list we want to query, the amount of people have had to watch it)

And it will return the amount of times this happened

Add doc strings to said function, so after a while when you come back to this code, you still understand what you have written

For example:

def list_movies(movie_list, n):
    """
    a method what returns the count of movies watched by more then n people

    args:
        movie_list (list): The list of movies in [(movie, [names]), ..]
        n (int): The amount of times the movies has need to be watched

    returns:
       The count of movies that has been watched by more then n people
    """

Make proper tests

if you had properly tested this code, @Mathias's comment would probably not be necessary

There are a few good modules to test functionality doctest or unittests

Let's use doctest and add some tests to the docstring:

>>> count_movies_watched([('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald'])], 3)
1

>>> count_movies_watched([('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald'])], 4)
0

Without even writing a single line of code, it's already more clear, what this function will do and what a correct answer will be.

Improving Code

You can use list comprehension and the built in sum to get a count of movies
Use _ for variables you don;t use later on

Netting me:

sum([1 if len(names) > n else 0 for _, names in movie_list])

But this can also be improved, as @Mathias correctly states

sum will accept any iterable there is no need for the list comprehension
sum can add bools as well so no need for the awkward ternary

Netting me:

sum(len(names) > n for _, names in movie_list)

Putting it all together

import doctest

def count_movies_watched(movie_list, n):
    """
    a method what returns the count of movies watched by more then n people

    args:
        movie_list (list): The list of movies in [(movie, [names]), ..]
        n (int): The amount of times the movies has need to be watched

    returns:
        The count of movies that has been watched by more then n people

    >>> count_movies_watched([('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald'])], 3)
    1

    >>> count_movies_watched([('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald'])], 4)
    0
    """
    return sum(len(names) > n for _, names in movie_list)

if __name__ == '__main__':
    doctest.testmod()


Fastest method of getting the bounding box containing all value ranges I want to find the fastest method of getting the range object which contains all values in a worksheet, while only containing 1 area. Traditionally one might think this is what UsedRange does, however UsedRange often selects cells outside of the value range.

I believe there is no existing VBA range which will suffice to this criteria alone then so I set out to build my own. I tested 2 versions. The first exploits the SpecialCells() function:

Function ValueBoundingBox(sht As Worksheet) As Range
  'Get used range
  Dim ur As Range
  Set ur = sht.UsedRange

  'If used range is 1x1 then result is 1x1
  If ur.Rows.Count = 1 And ur.Columns.Count = 1 Then
    Set ValueBoundingBox = ur
    Exit Function
  End If

  'Find all non-empty cells
  Dim x As Range
  Set x = Application.Union( _
    ur.SpecialCells(xlCellTypeConstants), _
    ur.SpecialCells(xlCellTypeFormulas) _
  )

  'Loop over all areas
  Dim area As Range, colMin, colMax, rowMin, rowMax, colArea, colAreaMax, rowArea, rowAreaMax As Long

  'Set Initial (Large) values for colMin and rowMin
  rowMin = 1048576
  colMin = 16384

  'Loop over all areas selected by special cells.
  For Each area In x.Areas
    With area
      'Calculate min and max rows/cols of area
      colArea = .Column
      colAreaMax = .Column + .Columns.Count
      rowArea = .row
      rowAreaMax = .row + .Rows.Count

      'Calculate min/max of range based on these values
      If rowAreaMax > rowMax Then rowMax = rowAreaMax
      If rowArea < rowMin Then rowMin = rowArea
      If colAreaMax > colMax Then colMax = colAreaMax
      If colArea < colMin Then colMin = colArea
    End With
  Next

  'Return bounding box
  Set ValueBoundingBox = Range(sht.Cells(rowMin, colMin), sht.Cells(rowMax, colMax))
End Function

The next uses the array of values extracted from a range to determine the minimum and maximum rows:

Function ValueBoundingBox2(sht As Worksheet) As Range
  'Get used range
  Dim ur As Range
  Set ur = sht.UsedRange

  'If used range is 1x1 then result is 1x1
  If ur.Rows.Count = 1 And ur.Columns.Count = 1 Then
    Set ValueBoundingBox2 = ur
    Exit Function
  End If

  'Find via array
  'Get array of all values:
  Dim v As Variant
  v = ur.Value

  'Define required values
  Dim colMin, colMax, rowMin, rowMax, row, col As Long

  'Find min row:
  For row = LBound(v, 1) To UBound(v, 1)
    For col = LBound(v, 2) To UBound(v, 2)
      If Not IsEmpty(v(row, col)) Then
        rowMin = row
        GoTo NextNum
      End If
    Next
  Next
NextNum:
  'Find max row
  For row = UBound(v, 1) To LBound(v, 1) Step -1
    For col = LBound(v, 2) To UBound(v, 2)
      If Not IsEmpty(v(row, col)) Then
        rowMax = row
        GoTo NextNum2
      End If
    Next
  Next
NextNum2:
  'Find min col:
  For col = LBound(v, 2) To UBound(v, 2)
    For row = LBound(v, 1) To UBound(v, 1)
      If Not IsEmpty(v(row, col)) Then
        colMin = col
        GoTo NextNum3
      End If
    Next

  Next
NextNum3:
  'Find max col
  For col = UBound(v, 2) To LBound(v, 2) Step -1
    For row = LBound(v, 1) To UBound(v, 1)
      If Not IsEmpty(v(row, col)) Then
        colMax = col
        GoTo NextNum4
      End If
    Next
  Next
NextNum4:
  Set ValueBoundingBox2 = Range(sht.Cells(rowMin, colMin), sht.Cells(rowMax, colMax))
End Function

Testing the above functions for performance results in the following results:

| Proc name         | Time taken |
|-------------------|------------|
| ValueBoundingBox  | 52s        |
| ValueBoundingBox2 | 1s         |

Clearly the 2nd version I made is far superior than the version which exploits SpecialCells() however I was wondering whether anyone else had any other ideas to speed up the algorithm further?

This should work. It's pretty simple method. I cannot test with your sheet as mine is not nearly that large, but you can try it.

IMPORTANT NOTE: This MUST be called as a Sub if it is a function that is called from a cell then, it will not work. (because excel uses the active range to perform the start of the SpecialCells I believe).

I have tested this code with your picture of cells and it works well.

It also works with other versions of cell combinations and locations that I have tested.

The reason to use the following code is because it is simple and can save valuable programming time.  The SpecialCells Method is reliable if used correctly just like any other programming language and function. It is worth a try and also worth timing with your larger data.

In addition, the OP also uses SpecialCells in his code, just not the same way that I have.

I hope this helps.

    Option Explicit

    Sub RunIT()
        'Input range must be the first cell of where the data starts
        GetAllCells Range("A1")
    End Sub

    Public Sub GetAllCells(rngInStartingRange As Range)
        Dim strTemp As String

        strTemp = Range(rngInStartingRange, rngInStartingRange.SpecialCells(xlLastCell, xlTextValues)).Address
    End Sub


Power of two integers Challenge:

  Given a positive integer which fits in a \$32\$ bit signed integer,
  find if it can be expressed as \$A^P\$ where \$P > 1\$ and \$A > 0\$.
  A and P both should be integers.

  Example

  Input : 4
  Output : True
  as \$2^2 = 4\$.

My approach:

public class Solution {
    public int isPower(int A) {
        int exp, base;

        if( A == 1)
            return 1;

        if( A%2 == 0)
            {
                for( int i = 2; i < A; i+= 2 )
                  {
                        double variable = Math.log(A) / Math.log(i);
                        double formatted = Double.parseDouble(String.format( "%.6f", variable));

                        if((formatted== Math.floor(formatted)) && !Double.isInfinite(formatted))
                            return 1;
                  }
                return 0;
            }

        else
            {
                for( int i = 3; i < A/2; i+= 2 )
                  {
                       double variable = Math.log(A) / Math.log(i);
                       double formatted = Double.parseDouble(String.format( "%.6f", variable));

                        if((formatted== Math.floor(formatted)) && !Double.isInfinite(formatted))
                           return 1;
                  }
                return 0;
            }

    }
}

I have the following questions with regards to the above code:

Is there any better method to solve this question?
How can I further optimise the time and space complexity of the solution?

Accuracy

Floating-point approximations are not an acceptable substitute for integer arithmetic!  Otherwise, you end up with mistakes, like Homer's bogus counterexample of Fermat's Last Theorem.

How does that apply to your code?  Consider isPower(2147483647).  Your code yields 1, because it thinks that 463412 ≈ 2147483647.  In fact, 463412 = 2147488281, and the correct answer is "false", since 2147483647 is prime.

Filtering a number through a double → String → double round-trip conversion is especially egregious.

Naming

Try to choose variable names that are consistent with the nomenclature in the challenge.  Your variable is really P; your i corresponds to A; your A should be named something else altogether — perhaps n.

Suggested solution

Count the number of times each prime factor of n occurs.  You need to be able to segregate those factors into equal groups, with no lone factors left over.

import java.util.PrimitiveIterator;
import java.util.stream.IntStream;

public class Solution {
    /**
     * Calculates the GCD of two numbers using the Euclidean Algorithm.
     */
    private static int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    public boolean isPower(int n) {
        PrimitiveIterator.OfInt factors =
            IntStream.concat(IntStream.of(2), IntStream.iterate(3, i -> i + 2))
                     .iterator();

        // Count the number of times each prime factor occurs
        IntStream.Builder exponents = IntStream.builder();
        int f, e;
        do {
            f = factors.nextInt();
            for (e = 0; n % f == 0; e++) {
                n /= f;
            }
            if (e > 0) {
                exponents.add(e);
            }
        } while (f < n);

        // Try to segregate the factors into equal groups with no loners.
        // If there is no GCD, then n was 1, so a=1, p=2 would work.
        int p = exponents.build().reduce(Solution::gcd).orElse(2);
        return p > 1;
    }
}


Grids, Cells, and Inheritance I want to build a grid and I have 2 concepts: Grid which is consist of Cell.

Grid class is:

var Grid = function (rows, columns, cellInit) {
    var canvas = create_canvas();
    this.context = canvas.getContext('2d');

    this.matrix = new Array(rows);
    for (var x = 0; x < rows; x+=1) {
        this.matrix[x] = new Array(columns);
        for (var y = 0; y < columns; y+=1) {
            this.matrix[x][y] = new Cell(x, y, cellInit(), this.context);
        }
    }
};

Cell class is:

var Cell = function (x, y, value, context) {
    this.x = x;
    this.y = y;
    this.rectX = s.cell_width * this.x + s.pad;
    this.rectY = s.cell_height * this.y + s.pad;
    this.value = value;
    this.context = context;
};

Also I have fill method for Cell:

Cell.prototype.fill = function(type) {
    this.context.fillStyle = s.colors[type];
    this.context.fillRect(this.rectX, this.rectY, s.rect_width, s.rect_height);
    return this;
}

And actually I have 2 questions about this code:

Looks like that Grid and Cell should have parent-child relationship. Is it normal that I'm creating child objects at parent class?
I need somehow to give access to context var from Cell class without passing it via constructor. I had tried to play with prototypes but can't figure out how to do that.

Looks like that Grid and Cell should have parent-child relationship. Is it normal that I'm creating child objects at parent class?

There is no reason for a Grid and Cell to have any inheritance relationship. A Cell is not a kind of Grid, nor is a Grid a kind of Cell.

  I need somehow to give access to context var from Cell class without passing it via constructor.

Why? That's exactly how you should give a Cell access to the context. The constructor is the right way to do this. It's completely normal for a container class to pass needed context into its children.

  I had tried to play with prototypes but can't figure out how to do that.

It's a bad design to put data on the prototype. You would effectively make it impossible to have two independent Grids, if every single instance of Cell can only share access to one Grid's context via Cell's prototype. It's far better for each Grid to pass its context into all its Cells.


Fetching movie data using jQuery Requirements

Display movie datas inside all tags that have the class movie_list
Make an ajax call for fetching movie datas
Fill loading text before fetch data
If any error occurs during loading, the content should be empty

What I did

Cached all elements which have the class movie_list
Made functions which have only one responsibility
Functions take movieList elements for making easy to unit test

What I want to know

More readable/reusable code
Any performance improvement point
Any good design pattern on here

function loadMovies() {
   const url = 'http://moviedatas.com/movies';
   const movieList = $('.movie_list');

   setOnLoading(movieList);

   $.ajax({
       method: 'GET',
       url: url,
       data: {
           count: 10
       },
       success: function(response) {
           movieList.each(function() {
               const wrapper = $(this);

               render(wrapper, items);
           });
       },
       error: function(error) {
           onError(movieList);
       }
   })
}

function setOnLoading(movieList) {
   movieList.each(function() {
       $(this).html('Loading...');
   });
}

function render(wrapper, items) {
   const template = `

{title}

{description}

`;

   let movies = '';
   for (let i = 0; i < items.length; i++) {
       movies += template
           .replace('{title}', items[i].title)
           .replace('{description}', items[i].description);
   }

   wrapper.html(movies);
}

function onError(movieList) {
   movieList.each(function() {
       $(this).html('');
   });
}

As pointed out by Blindman67: in render(wrapper, items);, items is not defined.

const url = 'http://moviedatas.com/movies';

Const variable used only one time, you can remove it and write url: http://moviedatas.com/movies

Same for

const wrapper = $(this);

Use ES6 arrow function shortcut syntax () =>

    success: function(response) {
        movieList.each(function() {
            const wrapper = $(this);

            render(wrapper, items);
        });
    },

7 lines in one, shorter is cleaner.

success: (response) => movieList.each(() => render($(this), response.items)),

error: function(error) {
    onError(movieList);
}

If you don't use error XHR response, just write

error: () => onError(movieList)

Write jsDoc docstring above functions to help developers and IDE understanding what is happening.
If functions are becoming inline, you may write them directly in caller function.

Full review (without docstring)

function loadMovies() {
   const movieList = $('.movie_list');

   // setOnLoading
   movieList.each(() => $(this).html('Loading...'));

   $.ajax({
       method: 'GET',
       url    : 'http://moviedatas.com/movies',
       data   : { count: 10 },
       success: (response) => movieList.each(() => render($(this), response.items))
       error  : () => movieList.each(() => $(this).html(''));
   });
}

function render(wrapper, items) {
   const template = `

{title}

{description}

`;

   let movies = '';

   for (let i = 0; i < items.length; i++) {
       movies += template
           .replace('{title}', items[i].title)
           .replace('{description}', items[i].description);
   }

   wrapper.html(movies);
}

Also, I don't understand the logic of getting a movie list data and then iterating over a movie list HTML to put movies in. It becomes a list of list of movies...


Is this a safe Login? I've been doing a lot of searching on PHP, logins, forms, cookies, sessions, etc.  And so, I've tried to gather all the info that I got from all over the place.  But, I didn't find a place with all the info, and tried to do the best secure login I could do.

This is what I have.  If this ends up being good, others can use this.  Otherwise, just ignore it.  But I'd like to have opinions.

First, every page makes sure you use HTTPS:

if($_SERVER["HTTPS"] != "on")
{
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    exit();
}

Send username and pass using POST over the https should be safe enough?

Using XMLHttpRequest to check password on Check.php:

function validate() {

var un = document.form1.myusername.value;
var pw = document.form1.mypassword.value;

  httpObject = getHTTPObject();

  if (httpObject != null)
  {
    var params = "username="+un+"&password="+pw;

    httpObject.open("POST","Check.php", true);
    httpObject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    httpObject.setRequestHeader("Content-length",params.length);
    httpObject.setRequestHeader("Connection","close");
    httpObject.onreadystatechange = setValid;
    httpObject.send(params);
  }

}

On Check.php, upon confirming password (which was saved on server encrypted), I set up cookie and session creating unique IDs and session secrets:

if($u==$username && $p==$password)
    {
        $valid=1;

        //Setting up session and cookie
        //if cookie stored secret does not meet session secret, session has been hijacked, the same for id
        //session is stored on server while cookie is stored on client

        session_start();
        $sessionTime = time();
        $unique_id = uniqid(sha1($_SERVER['HTTP_USER_AGENT'] . $username), true); //create a unique ID
        $sessionSecret = sha1($sessionTime . $unique_id);   // Create a unique secret based on time and ID

        $_SESSION[$unique_id]['time']    = $sessionTime;
        $_SESSION[$unique_id]['user']    = $us;
        $_SESSION[$unique_id]['secret']    = $sessionSecret;

        // if user changes cookie Secret, it wont match any secret of any other session stored in server
        setcookie("LoginCookie_s", $sessionSecret);
        setcookie("LoginCookie_i", $unique_id);

        // inform user that login was successfull
        echo $valid;
        return;
    }

Back in login: if the return value is 1, I can proceed to main page.
On the main page and every other pages I validate cookie and session:

<?php
 // Validate session and cookie
//if cookie stored secret does not meet session secret, session has been hijacked, the same for id
//session is stored on server while cookie is stored on client

//is cookie set?
if(!isset($_COOKIE["LoginCookie_s"]) || !isset($_COOKIE["LoginCookie_i"]))
{
    //this guy did not pass by login!
    header("location:Login.php");
    exit();
}

session_start();

// was session started on login?
if(!isset( $_SESSION[$_COOKIE["LoginCookie_i"]] ))
{
    //this guy did not pass by login!
    header("location:Login.php");
    exit();
}

// even if a user forged an id matching another user's id he would need to change cookie secret
// if user changes cookie id or secret, it wont match the session secret of that other user id
if( $_COOKIE["LoginCookie_s"] != $_SESSION[$_COOKIE["LoginCookie_i"]]['secret'] )
{
    //cookie and\or session has been hijacked
    header("location:Login.php");
    exit();
}

//all is fine, proceed loading the rest of the page...
 ?>

Am I missing something?

Some comments:

if($_SERVER["HTTPS"] != "on")

See: https://stackoverflow.com/a/2886224/59087

Avoid calling exit() from more than one location.

The following code is repeated many times:

//this guy did not pass by login!
header("location:Login.php");
exit();

You could write some functions to avoid the duplication:

function redirectLogin() {
  redirect( "Login.php" );
}

function redirect( $page ) {
  header( "Location: $page" );
  exit();
}

This removes the duplication and ensures that you have only one place in the code to change if you wanted to rename Login.php, for example, to login.php, which is a bit more user-friendly (on Unix systems).