Option buttons in plugin Dialog I used the jQuery UI plugin Dialog to ask a user for "name" and to show it in a subsequent dialog.

Is there the better way to add a function to the option "buttons" to get the data and to go to a new dialog?

    $("#message").dialog({autoOpen: false});
    $("#form").dialog({
        autoOpen: false,
        modal: true,
        title: "What is your name?",
        buttons:{
            "Submit": function(){
                $( this ).dialog( "close" );
                $("#message").dialog("open");
                var str = $("input").val();
                $("span").text(str);
            }
        }
    });
    $("#btn").click(function(){
        $("#form").dialog("open");
    });

    <button id="btn">Click me</button>
    <form id="form">
        <input type="text" name="">
    </form>

Hello, !

Your Question

Is there the better way to add a function to the option "buttons" to get the data and to go to a new dialog?

I don't believe there is a "better" way, though instead of using an object for the buttons option, an array could be utilized, which would allow more customization of the buttons. For example, the submit button could have a custom icon added to it and more custom event handlers, like mouseenter. See the code snippet at the end of this post for an example.
Feedback
Elements without ids
Your example contains only one form input (i.e. <input type="text" name="">), though it is typically rare to only have one form input. As soon as other text/radio/checkbox inputs are added, the way that is referenced in JavaScript will need to change. I would advise you to always add an id attribute to the elements and use those when referencing them in the JavaScript. So that text input could have an id attribute like id="username". Then the JavaScript can reference it using that attribute: $('#username').val().
The same is true for the  element that gets set with the text entered by  the user. It would be wise to also give that element an id attribute and use it in the JavaScript code. This actually would prevent the title of the message dialog from getting updated with the name (see screenshot below).

That happens because $('span') matches multiple elements, including the header of the message dialog and the element that follows "Hello, ", and then .text() updates all of those matching elements.
jQuery DOM ready callback
It is best to wrap the jQuery code in a function called when the DOM is ready. Traditionally that was done with $.ready() but in the latest versions that is deprecated, in favor of the $(function() {...}); syntax. That way, all variables will have limited scope instead of being global variables (i.e. on window).
jQuery references
It is wise to store DOM look-ups (e.g. $('#message')) in a variable (or actually, a constant would be semantically better, though browser support can be an issue there...), since  those can be expensive.
So for example:

$("input").val()

could be replaced with
usernameInput.val();

if a line like the following is added at the beginning of the script:
const usernameInput = $('#username');

For more tips like these, I suggest reading this article. I know it is 3 years old and bashes jQuery in the beginning but there are some really useful tips there.

$(function() { //DOM ready callback
    //store references in DOM
    const usernameInput = $('#username');
    const usernameDisplay = $('#username_display');
    //store a reference to the message dialog
    const messageDialog = $("#message").dialog({autoOpen: false});
    const formDialog = $("#form").dialog({
        autoOpen: false,
        modal: true,
        title: "What is your name?",
        buttons: [{
            text: "submit",
            icon: "ui-icon-contact",
            mouseenter: function() { //when user starts to hover over button
                $(this).effect('shake', 'swing', 100);
            },
            click: function() {
                $( this ).dialog( "close" );
                messageDialog.dialog("open");
                var str = usernameInput.val();
                usernameDisplay.text(str);
            }
        }]
    });
    $("#btn").click(function(){
        formDialog.dialog("open");
    });
})

<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

<button id="btn">Click me</button>
    <form id="form">
        <input type="text" name="" id="username">
    </form>

Hello, !


Summing durations associated with each MAC address in a MongoDB result I have a script which get data from MongoDB in the form of array and show the result. The array has a number of records in the thousands. A sample array is as follows:

array(2) {   ["mac"]=> string(17) "2c:33:7a:10:f8:39" int(1478199995) ["duration"]=> int(5) }

array(2) {   ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478203338) ["duration"]=> int(3) }

array(2) {   ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478201111) ["duration"]=> int(7) }

array(2) {   ["mac"]=> string(17) "2c:33:7a:10:f8:39" int(1478206709) ["duration"]=> int(7) }

array(2) {   ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478202821) ["duration"]=> int(6) }

array(2) {   ["mac"]=> string(17) "2c:33:7a:10:f8:39" int(1478202366) ["duration"]=> int(4) }

array(2) {   ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478205023) ["duration"]=> int(2) }

I am showing record with respect mac address like in above array MAC address "2c:33:7a:10:f8:39" has three records and "38:0b:40:ad:03:53" has four, so I will add duration of each record and show on browser like this

2c:33:7a:10:f8:39          16sec
38:0b:40:ad:03:53          18sec

I am doing this by following logic which I think is too slow for 5000 to 6000 records.

I first get the MAC address in an array and remove duplication and then run a for loop on that array and add all duration for specific MAC my code is as below.

<?php
 foreach ($cursor as $document) {
 array_push($arr,$document["mac"]);
 }
 $arr=array_unique($arr);
 $duration=0;

 for($i=0;$i<count($arr);$i++){

foreach ($cursor as $document) {

if($document["mac"]==$arr[$i])
{

$duration+=$document['assoc_time'];

}

echo $arr[$i]."      ".$duration;
}

?>

How I can make this process fast and how to perform this task in only one foreach loop.

You can do this in only one foreach, making it faster and intelligible for future modification or reuse. The approach  I propose is as follows:

//(some sort of pythonish pseudocode)
// let cursor be the array with the mac addresses and duration
result = [] // empty array
for each element in cursor as document:
  document['mac'] is not a key of result then:
    result[ document['mac'] ] = document['duration']
  otherwise
    result[ document['mac'] ] += document['duration']

This way you can quickly check your data, it is very handy. The only difference is that you'll get an array like this:

[
   'mac1' => 'total duration in integer type',
   'mac2' => 'total duration in integer type for mac2'
   ... etc ..
]

In case you really need the current result array structure, you can do this after the first loop:

//(some sort of pseudocode)
arr = [] //initialize the array
for each element in result as mac => duration:
  arr[] = [ 'mac' => mac, 'assoc_time' => duration ]

The difference between nesting two (possibly) big loops and just checking if a key exists in an array is significant. Now let's write a few lines of PHP code:

<?php
$result = array(); // maybe just $result = []; in case you have a proper PHP version.
foreach ($cursor as $document):
  if ( isset( $result[ $document['mac'] ] ) ):
    $result[ $document['mac'] ] += $document['duration']
  else:
    $result[ $document['mac'] ] = $document['duration']
  endif;
endforeach;

You can just replace the endforeach, endif with the traditional brackets.


Expandable text boxes for legends of fieldsets What is the best way to refactor the following script?

The above script will be applied to the following HTML and ASP.NET code:

            <fieldset>
                <legend>
                    +
                    KengLink Function
                </legend>

                    <asp:CheckBoxList ID="UserRoles" runat="server" />

            </fieldset>
            <fieldset>
                <legend>
                    +
                MI Sheet
                </legend>

                    <asp:CheckBoxList ID="UserRolesMISheet" runat="server" />

            </fieldset>

Don't use ids at all. (You almost never should be using them. Ids get to be really problematic once you have composite views and/or multiple people on a project)

Place a few appropriate classes in your html. And use the jquery composite and relative references to do it all at once.

$('.expander').click(function() {
  $(this).closest('fieldset').find('.expandable').toggle('show');
  var l = $(this).find('label');
  l.text(l.text() === '+' ? '-' : '+');
});

where your clicker span gets a class of expander and your rolesList gets the class of expandable. You could just use rolesList directly, but I find  expandable to be somewhat more descriptive.


Implementing a simple queue in C I am learning C and I have some trouble with pointers. I decided to create a queue to practice a bit. The program works as intended, however I want to know some good practices and suggestions.

Here is queue.c:

#include <stdlib.h>
#include "bank_sim.h"
#include "queue.h"

void initiliaze(Queue *queue) {
        queue->head = NULL;
        queue->tail = NULL;
}

void enqueue(Queue *queue, Customer *customer) {
        if (queue->head == NULL) {
                queue->head = customer;
                queue->tail = customer;
                queue->customer_cnt++;
        } else {
                queue->tail->next = customer;
                queue->tail = customer;
                queue->customer_cnt++;
        }
}

Customer *dequeue(Queue *queue) {
        if (queue->head == NULL) {
                return NULL;
        } else {
                Customer *head_customer = queue->head;
                queue->head = queue->head->next;
                head_customer->next = NULL;
                queue->customer_cnt--;
                return head_customer;
        }
}

queue.h:

#ifndef QUEUE_H
#define QUEUE_H
#include "bank_sim.h"

typedef struct {
        Customer *head;
        Customer *tail;
        int customer_cnt;
} Queue;

void initiliaze(Queue *queue);
void enqueue(Queue *queue, Customer *customer);
Customer *dequeue(Queue *queue);

# endif

Finally bank_sim.h:

#ifndef BANK_SIM_H
#define BANK_SIM_H

typedef struct Customer Customer;

struct Customer {
        int id;
        int service_time;
        struct Customer *next;
};

typedef struct {
        Customer *customer;
        int occupied;
} Bank_Teller;

#endif

Comments regarding anything is welcome including whether my structure for Customer and Queue can be improved.

One major thing:
Queue consists of node which consist of data. Here, your data is Customer.
Data should not be coupled with the Queue i.e. think this way.

   typedef struct Node{
         Node* next; // navigation pointer.
         Customer customer; // data
   }Node;

Considering the current implementation, here are a few points to go with:

Initialize misses to initialize customer_cnt = 0;.
Where are you allocating the Queue instance. Instead, have getQueueNode which allocates memory for the node and initialise that as well. Allocation at one place helps for e.g: easy debugging when malloc returns null due to insufficient memory.
Extract common code outside the if-else block in enqueue().
Put related code at once i.e. in dequeue operations for head_customer could be consecutive.


TLE on SPOJ for Prime Generator (PRIME1) The objective is to find all primes between two given numbers. It is specified that the two numbers are \$\le\$ 1 billion and the difference between the two numbers is ~100,000. We are to repeat the whole process for a \$t\$number of times, where \$t\$ is given \$\le\$ 10.

Detail of the problem: PRIME1

The following code results in Time Limit Exceeded, so please suggest optimizations.

import java.lang.*;
import java.util.*;
import java.io.*;

class PRIME1 {
    static boolean[] primesUpto(){
        boolean[] isPrime =new boolean[31623];
        for(int i=2; i<isPrime.length; i++){
            isPrime[i]=true;
        }
        for(int i=2;i<isPrime.length;i++){
            for(int j=i;j*i<isPrime.length;j++){
                isPrime[j*i]=false;
            }
        }
        return isPrime;
    }
    static boolean[] isPrime=primesUpto();
    static void listPrimes(long m, long n){
        for(long i=m; i<n+1; i++){
            for(int j=2; j<isPrime.length;j++){
                if(isPrime[j] && i%j==0) break;
                if(j==31622) System.out.println(i);
            }
        }
    }
    public static void main(String args[])throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        byte t= Byte.parseByte(br.readLine());
        String[] in = new String[t];
        for(int i=0; i<t; i++){
            in[i]=br.readLine();
        }
        for(int i=0; i<t;i++){
            StringTokenizer st = new StringTokenizer(in[i]);
            listPrimes(Long.parseLong(st.nextToken()), Long.parseLong(st.nextToken()));
            System.out.println();
        }
    }
}

Avoid magic numbers

        boolean[] isPrime =new boolean[31623];

This should have a constant defined.  Perhaps

    final long MAXIMUM_CANDIDATE = 1000000000;
    final int MAXIMUM_SMALLEST_FACTOR = (int)Math.sqrt(MAXIMUM_CANDIDATE);

I suppose that the really correct name would be MAXIMUM_SMALLEST_FACTOR_OF_ANY_NONPRIME_NUMBER_LESS_THAN_MAXIMUM_CANDIDATE, but hopefully this is clear enough.

And you may want to pass it into the method, e.g.

    static boolean[] composites = primesUpto(MAXIMUM_SMALLEST_FACTOR);

and

    static boolean[] primesUpto(int maximumSmallestFactor) {
        boolean[] composites = new boolean[maximumSmallestFactor + 1];

This makes the method more general.

I also changed the name from the verb isPrime to a noun name, as is consistent with object-oriented naming conventions.  I also changed the direction.  This allows us to eliminate the step of setting everything to true.  Now the natural default of false will be correct.  We only need to set the true values.

Don't do unnecessary math

            for(int j=i;j*i<isPrime.length;j++){
                isPrime[j*i]=false;
            }

This does more work than is necessary.  Consider

            for (int j = i*i; j < composites.length; j += i) {
                composites[j] = true;
            }

This saves a multiplication every iteration (two if the compiler is dumb enough) but only replaces an increment by one with an increment by i.  Two operations that will normally take the same time.

You can save even more time by adding another check.

            if (!composites[i]) {
                for (int j = i*i; j < composites.length; j += i) {
                    composites[j] = true;
                }
            }

Now we only sieve out multiples of primes.  So one comparison per outer loop iteration saves running the inner loop more than half the time.

        for(long i=m; i<n+1; i++){

Similarly, this could be written

        for (long i = m; i <= n; i++) {

Don't do in a loop what you can do outside

            for(int j=2; j<isPrime.length;j++){
                if(isPrime[j] && i%j==0) break;
                if(j==31622) System.out.println(i);
            }

You check on every iteration if it is the last iteration.  Consider

            int j = 2;
            for (; j < composites.length; j++) {
                if (!composites[j] && i%j == 0) {
                    break;
                }
            }

            if (j == composites.length) {
                System.out.println(i);
            }

This does the same thing in effect, but it only checks once to see if the loop reached the end.

It also gets rid of the magic number.

And I added more {} and whitespace, because I find it easier to follow.

An alternative

If these changes aren't enough, you might consider changing the algorithm.  You iterate over the entire array to find just the primes.  Why not store just the primes in the first place?  Still use the sieve to mask out the non-primes, but when you find a prime, save it.

            if (!composites[i]) {
                primes.add(i);
                for (int j = i*i; j < composites.length; j += i) {
                    composites[j] = true;
                }
            }

Also, rather than trial division, consider using a sieve again on the range from m to n.

If you want to see an example of how this could work, try here.  I already wrote out a solution for this.  The other answer to the same question has additional explanation of the algorithm and links to a C++ solution.


Rust implementation of next-permutation I am translating this next permutation algorithm in C++:

template<class BidirIt>
bool next_permutation(BidirIt first, BidirIt last)
{
    if (first == last) return false;
    BidirIt i = last;
    if (first == --i) return false;

    while (true) {
        BidirIt i1, i2;

        i1 = i;
        if (*--i < *i1) {
            i2 = last;
            while (!(*i < *--i2))
                ;
            std::iter_swap(i, i2);
            std::reverse(i1, last);
            return true;
        }
        if (i == first) {
            std::reverse(first, last);
            return false;
        }
    }
}

Into this Rust code:
struct Solution;
impl Solution {
    pub fn next_permutation(nums: &mut Vec<i32>) -> bool{
        if nums.len() < 2 {
            return false;
        }
        let first = 0;
        let last = nums.len();
        let mut i = last - 1;
        loop {
            let i1 = i;
            i -= 1;

            if nums[i] < nums[i1] {
                let mut i2 = last;

                loop {
                    i2 -= 1;
                    if nums[i] < nums[i2] {
                        break;
                    }
                }
                let tmp = nums[i];
                nums[i] = nums[i2];
                nums[i2] = tmp;
                nums[i1..last].reverse();
                return true;
            }
            if i == first {
                nums[first..last].reverse();
                return false;
            }
        }
    }
}

Though it works, I think it's not very good-looking. I am a beginner in Rust; any improvement will be welcome!

In no particular order:

Create test cases so you can have some confidence while refactoring.

Don't create empty structs (Solution) just to give them functions. next_permutation is perfectly fine as a free function. If you have to create a bad API to satisfy LeetCode or whatever, write the good API first, and then wrap it. If the API required is so bad you can't wrap a good API with it, it's probably a waste of time.

Use rustfmt.

Accept &mut [T] instead of &mut Vec<T> when you don't need to change the size.

let first = 0;
let last = nums.len();

Don't give unnecessary symbolic names to things that aren't used symbolically. 0 is far more obviously the index of the first element in a slice than first. Furthermore, you don't even need to provide the bounds of the slice when indexing with [..]; they're implied. So you need these even less than you perhaps thought.

i, i1, i2 are meaningless. How about some descriptive names?

I prefer to put each loop in a block with its state variables to limit the scope of the mutability.

let i1 = i;

Similar to the note on first and last above, don't make variables that can be trivially calculated from other variables. The relationship between i and i + 1 is way more obvious than i and i1.

if nums[i] < nums[i + 1] { ... }

Why is this body nested in the outer loop? The algorithm breaks fairly easily into four steps:

Get the index of the rightmost ascending pair of values
Get the index of the rightmost value greater than the first element of that pair
Swap the values at these two indices
Reverse the slice starting just after the first index.

You have 2, 3, and 4 nested inside 1, which makes the algorithm look more complicated than it actually is.

let tmp = nums[i];
nums[i] = nums[i2];
nums[i2] = tmp;

Use nums.swap(i, i2) instead.

As mentioned in the reddit comments, there's an iterator method rposition that finds the last item matching some predicate (if the iterator is one that can be iterated from both ends). You can use this to linearize the first (outer) loop, which may be easier to reason about. Don't go overboard, though: iterators are great for certain tasks and not so great for others. If you feel like the logic and flow of the code is better with a loop, just write the loop.

As for the inner loop, since the trailing subslice is by definition monotonically decreasing, you can search for the swap point using binary search. It's not likely to make a big performance difference, though, and the logic might be a little harder to follow, so you might want to use rposition here as well.

Applied
pub fn next_permutation(nums: &mut [i32]) -> bool {
    use std::cmp::Ordering;
    // or use feature(array_windows) on nightly
    let last_ascending = match nums.windows(2).rposition(|w| w[0] < w[1]) {
        Some(i) => i,
        None => {
            nums.reverse();
            return false;
        }
    };

    let swap_with = nums[last_ascending + 1..]
        .binary_search_by(|n| i32::cmp(&nums[last_ascending], n).then(Ordering::Less))
        .unwrap_err(); // cannot fail because the binary search will never succeed
    nums.swap(last_ascending, last_ascending + swap_with);
    nums[last_ascending + 1..].reverse();
    true
}


Function to toggle between two values of an enum I have this code, but it looks a bit verbose:

enum MonitoringMode
{
    Seek,
    Destroy
}

void ToggleMonitoringMode()
{
    if (_monitoringMode == MonitoringMode.Seek)
        _monitoringMode = MonitoringMode.Destroy;
    else
    if (_monitoringMode == MonitoringMode.Destroy)
        _monitoringMode = MonitoringMode.Seek;
}

There are some well known idioms to toggle between two values, like:

bitwiseBoolean ^= bitwiseBoolean; // bit toggle
boolean = !boolean;               // boolean toggle
oneOrZero = 1 - oneOrZero;        // numeric toggle

Is there a similar, less verbose way to get the same result? I am not sure using the int value of enums would be safe or even "elegant" in C#.

Would there ever be a need to add more values to the MonitoringMode enum?

enum MonitoringMode
{
    Seek,
    Destroy,
    Something,
    SomethingElse
}

In that case, you're not "toggling" - you're mapping. And there's a data structure for that:

private static readonly IDictionary ModeMap = new Dictionary<MonitoringMode,MonitoringMode>
{
    { MonitoringMode.Seek, MonitoringMode.Destroy },
    { MonitoringMode.Destroy, MonitoringMode.Seek },
    // ...
};

Then you could switch from one value to the next simply by using that map:

void ToggleMonitoringMode()
{
    _monitoringMode = ModeMap[_monitoringMode];
}

If there's not going to be a need to ever add more values, then I'd question the use of an enum type here, because you're really toggling between true and false states of some _isSeeking Boolean, which you already know how to toggle.


Most concise Python radix function using functional constructions? The problem with computing a radix using a non-imperative style of programming is you need to calculate a list of successive quotients, each new entry being the quotient of the last entry divided by the radix. The problem with this is (short of using despicable hacks like log) there is no way to know how many divisions an integer will take to reduce to 0.

I'm fine with doing this with a generator :

def rep_div(n,r):
        while n != 0:
                yield n
                n /= r

But I don't like this for some reason. I feel there must be a clever way of using a lambda, or some functional construction, without building a list like is done here :

def rep_div2(n,r):
        return reduce(lambda v,i: v+[v[-1]/r],question_mark,[n])

Once the repeated divisions can be generated radix is easy :

def radix2(n,r):
        return map(lambda ni: ni % r,(x for x in rep_div(n,r)))

So my question is : is it possible to rewrite rep_div as a more concise functional construction, on one line?

From my perspective, I'd say use the generator. It's concise and easily readable to most people familiar with Python. I'm not sure if you can do this in a functional sense easily without recreating some of the toolkit of functional programming languages. For example, if I wanted to do this in Haskell (which I am by no means an expert in, so this may be a horrible way for all I know), I'd do something like:

radix :: Int -> Int -> [Int]
radix x n = takeWhile (> 0) $ iterate (\z -> z `div` n) x

You can certainly recreate takeWhile and iterate, however, this only works due to lazy evaluation. The other option is, as you've said, using log and basically recreating scanl:

def scanl(f, base, l):
    yield base
    for x in l:
        base = f(base, x)
        yield base

def radix(n, r):
    return scanl(operator.__floordiv__, n, (r for x in range((int)(log(n, r)))))

So my answer is going to be "No" (predicated on the fact that someone smarter than me will probably find a way). However, unless you are playing Code Golf, I'd again suggest sticking with the generator version.


Digit Power Sum with BigInteger This is my 1st F# program so I'm open to any and all criticism on my syntax and the way I approached the problem.

Challenge

Project Euler 16: Power Digit Sum

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?

open System
open System.Numerics

let digitPower (n:bigint) p = pown n p
let digitToPowerSum (n:bigint) p =
    (digitPower n p) |>
    string |>
    (fun s -> s.ToCharArray()) |>
    Array.map (fun x -> Int32.Parse (x.ToString())) |>
    Array.sum

[<EntryPoint>]
let main argv =
    let n = new bigint(2)
    let p = 1000
    let value = digitPower n p
    let sum = digitToPowerSum n p

    Console.WriteLine(String.Format("{0}^{1} = {2:n}", n, p, value))
    Console.WriteLine()
    Console.WriteLine(String.Format("Its digit sum is {0}", sum))
    Console.ReadKey() |> ignore
    0

I'm primarily concerned with

It's quite common to convert a number to a string to get the digits, and most of the times, it ought to work, but it's a hack, instead of modelling what should happen.

Here's another way to do it, which deliberately separates integers into its digits.

let rec digits i =
    let tens = i / 10I
    if tens = 0I
    then [i]
    else
        let ones = i % 10I
        (digits tens) @ [ones]

The rest is easy:

let euler16 x y = pown x y |> digits |> List.sum

Some examples from F# Interactive:

> euler16 2I 15;;
val it : System.Numerics.BigInteger = 26 {IsEven = true;
                                          IsOne = false;
                                          IsPowerOfTwo = false;
                                          IsZero = false;
                                          Sign = 1;}
> euler16 2I 1000;;
val it : System.Numerics.BigInteger = 1366 {IsEven = true;
                                            IsOne = false;
                                            IsPowerOfTwo = false;
                                            IsZero = false;
                                            Sign = 1;}


Moving objects on a grid in C++ I have a code that works but is very badly written. The main is very verbose, it is just to test the class.
I want to make objects move on a chessboard (a coordinate grid). I've defined these object as Vehicles. They have a position (x,y) on the plane and a direction. Being forced to move only North-South-East-West possible directions could be

North: (0, 1)
South: (0, -1)
East: (1, 0)
West: (-1, 0)

Vehicles can proceed only step by step (x+1, y), (x, y+1), where x, y are integers. Two vehicles cannot stand in the same position. A vehicle maintains its direction while it is possible, that is while it encounters an occupied position.

So I have to create a void move function which has as arguments the positions of the nearby vehicles (North South East West). Such a function should:

Check if the vehicle can maintain its direction and, if it can, refresh the vehicle position with the new position;
If the cell is occupied, go for another direction, check if the cell in that direction is free...
If every cell surrounding the vehicle is occupied, stay still.

I wrote a code that accomplish point 1 but I have difficulties with point 2. In particular, I can't think about a smart way to change the Vehicle's direction. Here's my code so far, it works but surely this is not the best way to do what I want to do:

 #include <iostream>
#include <cmath>

using namespace std;

class Vehicle {
private:
    int x, y;
    int vx, vy;
public:
    int getx() { return x;}
    int gety() { return y;}
    int getvx() { return vx;}
    int getvy() { return vy;}
void sety(int a) { y = a;}
void setx(int a) { x = a;}
void setvx(int a) {
    if (a != 0) {
        vx = a / abs(a);
    }else { vx = a;}
}
void setvy(int a) {
    if (a != 0) {
        vy = a / abs(a);
    }else { vy = a;}
}

void move(Vehicle * v) {
    int big = 0;
    int per[8];
    per[0]=0;   // North
    per[1]=1;
    per[2]=0;   // South
    per[3]=-1;
    per[4]=1;   // West
    per[5]=0;
    per[6]=-1;  // East
    per[7]=0;

    while(big<8) {
        int cont=0;
        for(int i=0; i<4; i++) {
            if (x+vx != v[i].getx() or y+vy != v[i].gety()) {
                cont ++;
            }
        }
        if(cont==4) {
            x = x + vx;
            y = y + vy;
            break;
        } else {
            vx = per[big];
            vy = per[big+1];
            big = big + 2;
        }
    }
}

void print() {
    cout << "x: " << x << endl;
    cout << "y: " << y << endl;
    cout << "vx: " << vx << endl;
    cout << "vy: " << vy << endl;
    cout << endl;
}

};

int main() {
Vehicle x;
x.setx(0);
x.sety(0);
x.setvx(0);
x.setvy(1);
x.print();

Vehicle v[4];

v[0].setx(0);
v[0].sety(1);
v[1].setx(-1);
v[1].sety(0);
v[2].setx(0);
v[2].sety(-1);
v[3].setx(1);
v[3].sety(0);

for(int i = 0; i<4; i++) {
    v[i].setvx(0);
    v[i].setvy(1);
    v[i].print();
}

x.move(v);
x.print();

v[2].setx(0);
v[2].sety(-2);
v[2].print();

x.move(v);
x.print();

}

The first thing to do to clean up the code would be to make a

struct pos {
   int x;
   int y;
};

This will simplify the remaining of the code, making it easier to reason about the logic.

For example, right now it is possible to set the vehicle' velocity (direction) to {1,1}, which your problem statement doesn't allow.

You should then also define an equality comparison for your location.

Your move function seems to have hard-coded the number of vehicles in play. Instead you should pass it a std::vector<Vehicle> by reference, and use size().

Once you fix these things, the logic of the move function is quite OK. It is quadratic in complexity, but that is OK for few cars. If you ever intend to increase the number of cars by orders of magnitude, there are two ways of improving the code:

Limit the world, and keep a grid where you mark if it is occupied or not.
Store the cars in a std::unordered_map, with their position as key. Then you can look up a position in constant time.

Edit: as suggested in the comment below, using namespace std should not be used. There are several really good reasons for not using it, and the only reason to use it is "I'm lazy". Look around other answers on Code Review for reasoning. This point comes up in about half of the C++ questions.


Aggregate cost for a directed graph in Prolog I've come up with a simple graph traversal algorithm to calculate the aggregated cost of a directed graph or its subgraphs. Given a directed graph, the code visits all reachable nodes and sums up the cost related to the node paying attention to already visited nodes. The return value is the total cost of (sub)graph.

For example, for the graph embedded in the code below all the following is true:

graphCost(a, 63).
graphCost(b, 26).
graphCost(c, 60).
graphCost(f, 32).

As you can see, I wasn't able to avoid duplicated paths without using global variables. I'm new to Prolog, so would like to have someone more experienced to look at it and check whether or not it's reasonable. Perhaps there's a ready to use function to do the same? Is there a more effective way to do it?

edge(a,b).
edge(a,c).
edge(b,d).
edge(c,d).
edge(d,e).
edge(b,b).
edge(c,f).

cost(a, 1).
cost(b, 2).
cost(c, 4).
cost(d, 8).
cost(e, 16).
cost(f, 32).

visitAndMove2(A) :-
  \+edge(A, _),
  nb_getval('Visited', Visited),
  ( \+member(A, Visited) ->
    nb_setval('Visited', [A | Visited]),
    cost(A, C),
    nb_getval('Cost', Cost),
    TC is Cost + C,
    nb_setval('Cost', TC),
    write(' --> '), write(A), write(': '), writeln([A | Visited])
  ;
    write(A), writeln(' --|')).

visitAndMove2(A) :-
  edge(A, Child),
  A \== Child,
  nb_getval('Visited', Visited),
  \+member(Child, Visited),
  nb_setval('Visited', [Child | Visited]),
  cost(Child, C),
  nb_getval('Cost', Cost),
  TC is Cost + C,
  nb_setval('Cost', TC),
  write(A), write(' --> '), write(Child), write(': '), writeln([Child | Visited]),
  visitAndMove2(Child).

graphCost(A, Cost) :-
  nb_setval('Visited', [A]),
  cost(A, C),
  nb_setval('Cost', C),
  visitAndMove2(A),
  nb_getval('Cost', Cost).

Using global variables is a sure sign that you are not working within the declarative paradigm. A declarative way to solve this is to keep track of the already visited variables via an argument of your predicate.

Also, please_use_a_readable_naming_convention insteadOfMakingEverythingHardToReadAsInJava.

For example, suppose you have a relation visited_and_move(Vs0, Vs, Vertex0, Vertex), where:

Vs0 is the list of vertices that are already visited
Vs is the next list of such vertices
Vertex0 is the previous vertex
Vertex is the next vertex.

This is only an example; you may not need all arguments. However, the general approach should be clear: Think in terms of relations between entities, such as the relation between a previous list and the next one.

Such pure predicates can be used in all directions, and tested in isolation without needing to store an implicit global state.


Add watermark to images Recently, I started reading image processing via opencv library in python.

I create a minio object storage and upload some photos into it. After that, I wrote a program which reads every image in each bucket in minio and watermark it with a simple logo. I read each image with imread and finally (after inserting a watermark), save it with imwrite (on the same image).

But when testing my code, I saw that for each image it took about 0.4 seconds. Since I want to do this simple operation for a lot of images, this time is not acceptable.

Here is a part of my simple code:

import cv2
import numpy as np

logo_img = cv2.imread('logo.png', cv2.IMREAD_UNCHANGED)

scl = 50
w = int(logo_img.shape[1] * scl / 100)
h = int(logo_img.shape[0] * scl / 100)
dim = (w, h)
logo = cv2.resize(logo_img, dim, interpolation=cv2.INTER_AREA)
logo_height, logo_width = logo.shape[:2]

def watermark_image(image_name):
    image = cv2.imread(image_name)
    image_height, image_width = image.shape[:2]
    image = np.dstack([image, np.ones((image_height, image_width), dtype="uint8") * 255])
    # Blend
    ovr = np.zeros((image_height, image_width, 4), dtype="uint8")

    x_pos = int(random() * (image_height - 10 - logo_width))
    y_pos = int(random() * (image_width - 10 - logo_height))

    ovr[x_pos:x_pos + logo_height, y_pos:y_pos + logo_width] = logo
    image = cv2.addWeighted(ovr, 0.6, image, 1.0, 0, image)
    cv2.imwrite(image_name, image)

import time
start = time.time()
for bucket in buckets:
    objects = minioClient.list_objects(bucket.name, prefix=None, recursive=True)
    for current_object in objects:
        watermark_image('./test/' + current_object.object_name)

end = time.time()

print(end - start)

How can I improve my code and optimize it in order to need less runtime?

Suppose that I have a object storage which contains a lot of image. Actually I want to prepare an API, for people to request a watermark for every image and then I want to show them requested image after watermarking it online.

I'll focus more on the

  How can I improve my code

part of your question.

Imports at the top

Move your import time to the top of the file, which is standard in Python.

Code in functions

Your logo dimension calculation should be in a function instead of global scope. The code at the bottom should be in a top-level main function.

Integer division

w = int(logo_img.shape[1] * scl / 100)

can be

w = logo_img.shape[1] * scl // 100

Use pathlib

...so that this:

'./test/' + current_object.object_name

can be

Path('test') / current_object.object_name


Finding the smallest cube for which exactly five permutations of its digits are cube (Project Euler #62)

  The digits of the cube, 41063625 (3453), can be permuted to produce
  two other cubes:

  56623104 (3843) and 66430125 (4053). In fact, 41063625 is the
  smallest cube which has exactly three permutations of its digits which
  are also cube.

  Find the smallest cube for which exactly five permutations of its
  digits are cube.

Here is my code which properly works and prints the number of permutations which are cube for a particular i. I have found numbers which have 1,2,3 permutations as perfect cubes. Here is the output which checked from i=0 to i=999 in around 120~130 seconds and found no such number. I need to increase the efficiency of the code otherwise searching will take a very long time. With increase in i the number of digits in cube of i increases and total permutations increase rapidly, hence a rapid decrease in speed.

It also prints 345,3 (correct) and none of 384 or 405 (good).

boolean[] checked = new boolean[999];
    Arrays.fill(checked, false);
    for (int i = 1; i < 999; i++) {
        if (!checked[i]) {
            int cube_perms = 0;
            long i_3 = i * i * i;
            int len = String.valueOf(i_3).length();
            ArrayList<int[]> perms = getPermutations(longToArray(i_3));
            for (int[] x : perms) {
                int num = arrayToInt(x);
                if (String.valueOf(num).length() < len) {
                    continue;
                }
                int cubrt = (int) Math.round(Math.pow(num, 1.0 / 3.0));
                if (Math.pow(cubrt, 3) == (num)) {
                    checked[cubrt] = true;
                    ++cube_perms;
                }
            }
            if (cube_perms == 5) {
                return i;
            }

            System.out.println(i + "," + cube_perms);
        }
    }
    return 0;

getPermutations()

public static ArrayList<int[]> getPermutations(int[] arr) {
    ArrayList<int[]> al = new ArrayList<int[]>();
    Arrays.sort(arr);
    do {
        al.add(arr.clone());
    } while (getNextPermDistinct(arr));
    return al;
}

getNextPermDistinct()

public static boolean getNextPermDistinct(int[] array) {
    // Find longest non-increasing suffix
    int i = array.length - 1;
    while (i > 0 && array[i - 1] >= array[i])
        i--;
    // Now i is the head index of the suffix

    // Are we at the last permutation already?
    if (i <= 0)
        return false;

    // Let array[i - 1] be the pivot
    // Find rightmost element that exceeds the pivot
    int j = array.length - 1;
    while (array[j] <= array[i - 1])
        j--;
    // Now the value array[j] will become the new pivot
    // Assertion: j >= i

    // Swap the pivot with j
    int temp = array[i - 1];
    array[i - 1] = array[j];
    array[j] = temp;

    // Reverse the suffix
    j = array.length - 1;
    while (i < j) {
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
        i++;
        j--;
    }

    // Successfully computed the next permutation
    return true;
}

longToArray()

public static int[] longToArray(long i) {
    int len = String.valueOf(i).length();
    int[] arr = new int[len];
    for (int j = 0; j < len; j++) {
        arr[j] = (int)i % 10;
        i /= 10;
    }
    return arr;
}

arrayToInt()

public static int arrayToInt(int[] a) {
    int num = 0;
    for (int i = a.length - 1; i >= 0; i--) {
        num += a[i] * Math.pow(10, a.length - i - 1);
    }
    return num;
}

Change this code:

boolean[] checked = new boolean[999];
Arrays.fill(checked, false);
for (int i = 1; i < 999; i++) {
    if (!checked[i]) {

To this:

boolean[] checked = new boolean[999];
for (int i = 1; i < checked.length; i++) {
    if (!checked[i]) {

The benefits:

boolean[] has all false values by default, no need to fill
Instead of iterating until some number, iterate until the something with a name that is required for the loop to work correctly, in this case checked.length

Other minor things:

The convention for naming variables is camelCase instead of snake_case
Refer to types by interfaces. Instead of ArrayList<int[]> perms =, use List<int[]> perms =
The getPermutations method returns List<int[]>, but you never actually use the int[] values, you immediately convert them to an int using arrayToInt. It seems it would be better if the method returned List<Integer> where the value are already converted into a form that you actually need.


Word Separator and Pig Latin Program Final Edit This is an updated version of my previous Java program that asks the user for a sentence and then separates the words and then converts the sentence into Pig Latin. My previous program was working, but there was some tweeking that needed to be done which I did after getting positive feedback. Apparently, my loop in the separateWords function was checking for capital letters twice or so. I have included the instructions for the assignment for reference and the code for peer edit. Thank you.

The program will accept a string as input in which all of the words are run together, but the first character of each word is uppercase. Convert the string to a string in which the words are separated by spaces and only the first word starts with an uppercase letter. For example, the string "StopAndSmellTheRose" would be converted to "Stop and smell the roses"

Then the program will convert each word in the result string of task 1 into "Pig Latin". In one version of Pig Latin, you convert a word by removing the first letter, placing that letter at the end of the word, and then appending "ay" to the word.

For example, for the result string "Stop and smell the roses" in task 1, the Pig Latin string should be "topSay ndaay mellsay hetay osesray"

Requirements:

Your program should have 3 methods: a main method, a method for task 1, and a method for task2

the method for task 1 should return the result string of task1
the method for task 2 should display the Pig Latin string

public class Assignment9 {
public static void main(String[] args) {
    // Variables
    String sentence, revisedSentence;

    // Create a Scanner object for keyboard input
    Scanner keyboard = new Scanner(System.in);

    // Get the input string
    System.out.print("Enter sentence: ");
    sentence = keyboard.nextLine();

    //Close keyboard
    keyboard.close();

    // Call function to perform Task 1
    revisedSentence = separateWords(sentence);

    System.out.print("Revised Sentence: " +revisedSentence);

    // Call function to perform Task 2
    toPigLatin(revisedSentence);
}

private static String separateWords(String sentence)
{
    // Variables
    StringBuilder str = new StringBuilder(sentence);
    int i = 1;

     // While loop repeats until the end of the sentence
    while (i < str.length())
    {
        // Checks for upper case characters
        if(Character.isUpperCase(str.charAt(i)))
        {
            str.insert(i, ' ');
            i++;
            char ch = Character.toLowerCase(str.charAt(i));
            str.setCharAt(i, ch);
        }
        i++;
    }
    return str.toString();
}

private static void toPigLatin(String revisedSentence)
{
    // Variables
    String latin = " ";

    // Split sentence by spaces
    String[] tokens = revisedSentence.split(" ");

    // Convert English sentence into Pig Latin
    for (int i = 0; i < tokens.length; i++)
    {
        // Get string from array
        String str = tokens[i];

        // Get first letter from string
        String str1 = str.substring(0, 1);

        // Get substring from string
        String str2 = str.substring(1, str.length());

        // Concatenate the two strings in a required format
        str2 = str2.concat(str1);

        // Concatenate the result and "AY"
        str2 = str2.concat("ay");

        // Make a sentence with all the words
        latin = latin.concat(str2 + " ");
    }

    // Display pig latin verison
    System.out.println("\nPig Latin Version:" +latin );
    }
}

Your commenting is absolutely abusive. This one is particularly beautiful... in its own way:
//Close keyboard
keyboard.close();

None of these comments are useful, because:

They state the obvious. Let the code speak for itself!
They tell the reader what the code is doing, but not why it's doing it.
They are a distraction. Reader/maintainer reads the comment, and then the code, and then subconsciously validates whether the comment reflects what the code underneath is saying.

See this beautiful answer specifically about comments - two things to remember:

Comments are supposed to make plain what the code does not tell us already.

Good code seldom needs comments

The naming is also inconsistent:
StringBuilder str = new StringBuilder(sentence);

String str = tokens[i];

A better name for the former could be builder, and a meaningful name for the latter could be token.
Comments should not replace meaningful names:
// Get first letter from string
String str1 = str.substring(0, 1);

If str1 were firstLetter...


Calculating the statistical Mode(s) of a (possibly multi-modal) set of elements I am trying to come up with the most performant way of calculating the statistical Modes of a std::vector, obeying two conditions:

1) my function should not duplicate memory usage (which would required for most usually mentioned faster methods of calculating mode);

2) my function should be able to handle multi-modality. It means, it should be able to return more than one mode when apropriate (i.e. in case the elements in the passed vactor have more than one mode).

Here is my function so far. It works, but I have the feeling that it could be further improved and reviewed, so I brought it here:

#include <vector>
#include <math.h>

std::vector<int> Mode(std::vector<int> &myvector)
{
int vectorsize = myvector.size();
int max = 0;
std::vector<int> maxs;
int counter = 1;
std::sort(myvector.begin(), myvector.end());

for (int i = 0; i < vectorsize - 1; i++)
{
    int currentnum = myvector[i];

    if (currentnum == myvector[i + 1])
    {
        counter++;

        if (counter > max)
        {
            if (counter > vectorsize - i) break; //early exit when the mode found so far appears more than the number of elements still to be evaluated
            max = counter;
            if (maxs.size() > 0) maxs.clear();
            maxs.push_back(currentnum);
        }
        else if (counter == max)
        {
            bool alreadyin = false;
            for (int j = 0; j < maxs.size(); j++)
            {
                if (maxs[j] == currentnum)
                {
                    alreadyin = true;
                    break;
                }
            }
            if (alreadyin == false)
                maxs.push_back(currentnum);
        }

    }
    else counter = 1; //reset the counter
}

return (maxs.size() > 0) ? maxs : myvector; //if all elements appear only once, return the whole initial vector; otherwise return the the modes that were found
}

Corrections, improvements an even suggestions of algorithm changes are very welcome.

So without really understanding what you mean with mode I would suggest the following purely based on your code:

Add includes. The code as is doesn't compile, which makes it harder for reviewers.
Premature Optimization. You are doing a lot of it. There is no reason to assign vectorsize to myvector.size(). The compiler will take care of that. Also currentnum is unnecessary.
Be consistent with your style. Putting else clauses at the same line with the code makes the code incredibly hard to read. Also parentheses really help in tracing the control flow. Generally nested control flow should utilize parentheses.
Naming. Consider camelCase or scores, but do not just add lowercaseletters as in alreadyin
alreadyin == false should be !alreadyin

So know that I know what you mean we can optimize the code.

The first thing would be naming. The vector containing the modes should be named modes rather than maxs. Similarly I would rather name max as currentMode or better modeStrength.

The second point would be the update of the vector. Currently you always clear it. However, if it only has one mode you can just change that value.

if (modes.size() == 1)
    modes[0] = myVector[i];
else if (modes.size() > 1)  {
    modes.clear();
    modes.push_back(myVector[i]);
} else {
    modes.push_back(myVector[i]);
}

The third idea would be to increment your loop based on the found matches so you do not reiterate already processed data

unsigned counter;
unsigned modeStrength = 0;
for (unsigned i=0; i < myVector.size() - 1; i += counter) {
    counter = 1;
    while ((counter + i != myVector.size()) &&
           (myVector[i] == myVector[i+counter])) {
        counter++;
    }
    if (counter == modeStrength) {
        modes.push_back(myVector[i]);
    } else if (counter > modeStrength) {
        modeStrength = counter;
        if (modes.size() == 1) {
            modes[0] = myVector[i];
        } else {
            modes.clear();
            modes.push_back(myVector[i]);
        }
    }
}

That would also turn the check for existence unnecessary.


Grey to Colored Image I want to improve the code, in which you can enter a grey bitmap and it will return you a colored one.

function ChangeBaseGrey(bitmap, color)
{
var canvas = document.getElementById("imagesColored");
var ctx = canvas.getContext("2d");
var dataBitmap = bitmap.data;

var r0 = (color >> 16) & 0xff,
    g0 = (color >> 8) & 0xff,
    b0 = color & 0xff;

for(var c = 0; c < dataBitmap.length; c += 4)
{
    var r1 = dataBitmap[c],
        g1 = dataBitmap[c + 1],
        b1 = dataBitmap[c + 2];

    if(dataBitmap[c + 3] > 0 && (r1 == g1 && r1 == b1 && g1 == b1))
    {
        var co = color;
        dataBitmap[c] = colorRGBBound(r0 * (r1 / 255));
        dataBitmap[c + 1] = colorRGBBound(g0 * (g1 / 255));
        dataBitmap[c + 2] = colorRGBBound(b0 * (b1 / 255));
    }
}

ctx.putImageData(bitmap, 0, 0);

var finalImage = new Image();
finalImage.src = canvas.toDataURL("image/png");

return finalImage; // Colored Image Output
}

From a once over:

Your indenting is off, this might be a copy paste problem into the question, consider using jsbeautify
You never use var co = color;, throw it away
(r1 == g1 && r1 == b1 && g1 == b1) consider that if r1 = g1 and r1 = b1, then g1 must be equal to b1 so you can use the simpler (r1 == g1 && r1 == b1)
I am not sure why you update the bitmap AND create a new image, I would do only 1 of these for extra speeds
r0,g0,b0 and r1,g1,b1 are not the most intuitive variable names..
Consider caching the values of colorRGBBound(r0 * (r1 / 255)); , there are only 255 possibilities for the value of r1 and you can use the same cache for r1,g1 and b1


Number guessing game in C This is just a little number guessing game. I know it's simple but I am a newbie in C and I think such a little example can be enough for finding simple design flaws that can than be eliminated.

If you know how parts of the code can be written more beautiful and more safe, please let me know!

/*
 * In this program the user has to guess a number between 1 and 99.
 * He has six tries.
 */

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

int generate_random_number(int lower_range, int upper_range)
{
    srand(time(0));
    return (rand() % (upper_range - lower_range + 1)) + lower_range;
}

// this function stops the program until useless input is entered
void pause()
{
    int useless;
    scanf("%i", &useless);
}

int main()
{
    // generate random number
    const int lower_range = 1;
    const int upper_range = 99;
    const int random_number = generate_random_number(lower_range, upper_range);

    // start of game
    printf("You have to guess a number between 1 and 99.\n");
    printf("You have six tries.\n");
    const int tries = 6;
    for (int i = 0; i < tries; i++)
    {
        printf("> ");
        int guess;
        scanf("%i", &guess);

        if (guess > random_number)
        {
            printf("The secret number is smaller.\n");
        }
        else if (guess < random_number)
        {
            printf("The secret number is higher\n");
        }
        else if (guess == random_number)
        {
            printf("You found the secret number!\n");
            pause();
            return 0;
        }
    }

    printf("You haven't found the secret number.\n");
    printf("The secret number was %i.\n", random_number);
    pause();
}

This looks quite good code.  You've avoided many of the common mistakes.

Here are the things I spotted as I walked through.  Most of them are quite minor; the only serious issue is the handling of invalid user input.

srand(time(0));

Don't do this every time you want a random number - a random number generator is intended to be seeded just once.  So move the srand() call to the beginning of `main().

(Yes, I know this program calls generate_random_number() only once.  But we shouldn't need to have that knowledge, and we might want to change that behaviour, or to re-use this function in another program.)

// this function stops the program until useless input is entered

What's the point?  That just annoys the user, who would naturally expect to be returned to their shell after executing a program.  This just makes it look like the program is not responding.  Also, the useless variable is unnecessary - add the * modifier to the %i conversion to inhibit assignment.

int main()

This says that main() can be called with an unspecified number of arguments.  Instead, prefer to explicitly declare that it takes no arguments:

int main(void)

printf("You have to guess a number between 1 and 99.\n");

When the output is a fixed string ending in newline, we can use puts() instead of printf().

    int guess;
    scanf("%i", &guess);

If something that's not a number is entered, then scanf() will fail and guess will be uninitialized (that's Undefined Behaviour, which is Not A Good Thing).  We really, really need to check that scanf() successfully converts 1 input, and take some recovery action if not:

int status;
while ((status == scanf("%i", &guess)) != 1) {
    if (status == EOF) {
        fprintf(stderr, "Read error!\n");
        exit 1;
    }
    scanf("%*[^\n]");  // discard input
    printf("? >");
}

Correctly handling input (and, in particular, unexpected input) is difficult in C!

    else if (guess == random_number)

The if is redundant here, as we've eliminated all other possibilities.  So that can be simply else.


Prime factor in reverse order #include<stdio.h>

int main(){

    int numberGiven,num=2,i=0,stack[100] = {0},top=-1;
    // get the number from user
    printf("Enter the number : ");
    scanf("%d",&numberGiven);

    while(numberGiven >= num){
        // check for prime-ness of number
        for(i=num/2;i>1;i--){
            if(num%i == 0){
                break;
            }
        }
        // prime factors
        while(numberGiven%num == 0 && i==1){
            stack[++top] = num;
            numberGiven /= num;
            continue;
        }
        num++;
    }

    while(top>=0){
        printf("%d\n",stack[top--]);
    }
    return 0;
}

Any possible code optimization and improvement of time complexity ?

There are several functions that I would have factored out to make the code more clear:

bool isFactorOf(int possibleFactor, int number) {
    return number % possibleFactor == 0;
}

bool isPrime(int number) {
    int i;
    int max = ceil(sqrt(num));
    for(i = 2; i <= max; ++i) {
        if(isFactorOf(i, num)) {
            return false;
        }
    }
    return true;
}

Note:

I reverted the order of testing the factor (because smaller numbers are more likely to be factors)
the test can end at the sqrt() because if there was a factor bigger than that, there would have been a corresponding factor smaller than that which we would have found earlier in the loop

The stack should be one data structure with checkable size like:

#define MAX_STACK_SIZE 100
typedef struct {
   int size;
   int data[MAX_STACK_SIZE];
} Stack;

void initialize_stack(Stack *stack) {
    stack->size = 0;
}

void push(Stack *stack, int value) {
    assert(stack->size < MAX_STACK_SIZE);
    stack->size++;
    stack->data[stack->size] = value;
}

int pop(Stack *stack) {
    assert(stack->size > 0);
    return stack->data[stack->size--];
}

bool empty(Stack *stack) {
    return stack->size == 0
}

Now the main loop:

At first lets rewrite your solution with the new functions:

while(numberGiven >= num){
    // prime factors
    while(isFactorOf(num, numberGiven) && isPrime(num)){
        push(&stack, num);
        numberGiven /= num;
    }
    num++;
}

I also removed the unnecessary continue (the loop would continue anyway). Using the short-circuit behavior of && already gives an optimization: The primeness is not tested if num is not a factor. Of course it should not be evaluated multiple times so this is more efficient:

while(numberGiven >= num){
    if(isFactorOf(num, numberGiven) && isPrime(num)) {
        do {
            push(&stack, num);
            numberGiven /= num;
        } while(isFactorOf(num, numberGiven));
    }
    num++;
}

Now we only do the checks once.
The next easy improvement would be to make bigger steps with num as above 2 each prime must be odd (which means step sizes of 2).

The next big speed improvement would come from using a list of precomputed primes (for example by sieving) to avoid the slow primeness test.

The factor finding should go in its own function as well:

Stack primeFactorsOf(int number) {
    Stack stack;
    initialize_stack(&stack);
    int possibleFactor = 2
    while(number >= possibleFactor){
        if(isFactorOf(possibleFactor, number) && isPrime(possibleFactor)) {
            do {
                push(&stack, possibleFactor);
                number /= possibleFactor;
            } while(isFactorOf(possibleFactor, number));
        }
        possibleFactor++;
    }
    return stack;
}

Which leaves your main function as:

int main() {
    int givenNumber;
    Stack factorStack;
    initialize_stack(&factorStack);
    printf("Enter the number : ");
    scanf("%d",&givenNumber);
    factorStack = primeFactorsOf(givenNumber);
    while(!empty(&factorStack)){
        printf("%d\n", pop(&factorStack));
    }
    return 0;
}

Addendum

After thinking a bit more about the algorithm I realized that you can completely remove the primeness check because you test from the lowest to the highest factor. Thus you will always find prime factors before you can find the composite factors because they are composed of these (smaller) prime factors.
Leaving out the rather slow primeness check should give you another significant performance boost.


Powershell script that updates Active Directory user information I wrote this Powershell script years ago for updating AD from a CSV file.  I'd like to try to optimize to run quicker and be more efficient... but I'm not sure where to start / what could improve it.  Any suggestions are welcome.

EDIT: I've updated my original script to this:

$users = Import-Csv C:\Scripts\Employees.csv

foreach ($user in $users) {

$employeeNumber = $User.employeeNumber
$Department     = $User.department
$Title          = $User.title
$Office         = $User.office
$Address        = $User.address
$City           = $User.city
$State          = $User.state
$PostalCode     = $User.postalCode
$Company        = $User.company
$Telephone      = $User.telephone
$Mobile         = $User.mobile
$Fax            = $User.fax
$Custom1        = $User.custom1
$Custom2        = $User.custom2
$Custom3        = $User.custom3
$Custom4        = $User.custom4

Get-ADUser -Filter "EmployeeID -eq '$($user.EmployeeID)'" `
    -SearchBase "OU=Logins,DC=domain,DC=com" |
    Set-ADUser -Replace @{ `
    employeeNumber=$EmployeeNumber;
    department=$Department;
    title=$Title;
    Office=$office;
    streetAddress=$Address;
    l=$City;
    st=$State;
    postalCode=$PostalCode;
    company=$Company;
    telephoneNumber=$telephone;
    mobile=$cell;
    facsimileTelephoneNumber=$Fax;
    ExtensionAttribute1=($user.custom1);
    ExtensionAttribute2=($user.custom2);
    ExtensionAttribute3=($user.custom3);
    ExtensionAttribute4=($user.custom4)
                    }
}

I agree with what @veefu suggests, and would like to build off that. To start with, you have different columns in your CSV as to what Set-ADUser is expecting. To work around this I would suggest creating a property map hashtable.

$PropMap = @{
    EmployeeNumber='EmployeeNumber'
    Department='Department'
    Title='Title'
    office='Office'
    Address='StreetAddress'
    City='City'
    State='State'
    PostalCode='PostalCode'
    Company='Company'
    telephone='OfficePhone'
    cell='Mobile'
    Fax='Fax'
    custom1='ExtensionAttribute1'
    custom2='ExtensionAttribute2'
    custom3='ExtensionAttribute3'
    custom4='ExtensionAttribute4'
}

Then you want to find out what the valid parameters for Set-ADUser are to determine if a given column should be applied as a parameter, or be fed to the -Replace parameter.

#Find the valid parameters for the Set-ADUser cmdlet (only strings, to avoid complex objects and switches, and no common parameters)
$ValidParams = Get-Command Set-ADUser -ShowCommandInfo |% ParameterSets |% Parameters |?{$_.ParameterType.FullName -match 'String' -and $_.Name -notin [System.Management.Automation.PSCmdlet]::CommonParameters} |Select -Expand Name -Unique

Then you import the CSV and loop through the users. For each user you find what properties they have filled in on the spreadsheet, see if it is a parameter for the Set-ADUser cmdlet, and build a hashtable to splat to the cmdlet.

#Import the list of users and updates
$Users = Import-Csv C:\Scripts\Employees.csv

#Loop through users
ForEach($User in $Users){
    #Set an empty hashtable for what this user needs to have updated
    $UserParams = @{}
    #Find the properties for this user that have values
    $UserProps = $User.PSObject.Properties.Name |?{![string]::IsNullOrWhiteSpace($User.$_)}
    #If it has a parameter in Set-ADUser add it to $UserParams
    $UserProps |?{($ParamName=If($_ -in $PropMap.Keys){$PropMap[$_]}Else{$_}) -in $ValidParams} |%{$UserParams.Add($ParamName,$User.$_)}
    #If it doesn't have a valid parameter build a hashtable for the -Replace parameter, and add that to $UserParams
    $UserProps |?{($ParamName=If($_ -in $PropMap.Keys){$PropMap[$_]}Else{$_}) -notin $ValidParams} |% -Begin {$ToReplace = $_} -Process {$ToReplace.Add($ParamName,$User.$_)} -End {$UserParams.Add('Replace',$ToReplace)}

Here I added a little Try/Catch to let you know if it failed to find or update any of the users, and if it failed to find them, or failed to update them, and gives the error. I used the shortened -ea instead of -ErrorAction out of habit.

    #Try to find the user, and apply the updates
    Try{
        Get-AdUser -Filter "EmployeeID -eq '$($user.EmployeeID)'" -SearchBase "ou=Logins,dc=domain,dc=com" -ea Stop | Set-ADUser @UserParams -ea Stop
    }Catch{
        #If the Get-ADUser or Set-ADUser cmdlets failed throw a warning with the user's EmployeeID for investigation

        #Determine if it was Get-ADUser or Set-ADUser that failed, to see if we couldn't find the user or couldn't update the user
        $WarningMessage = If($_.InvocationInfo.MyCommand -eq 'Get-ADUser'){'find'}else{'update'}
        Write-Warning "Unable to $WarningMessage user with EmployeeID (actual error follows): $($User.EmployeeID)"
        Write-Warning "$_`n"
    }
}


Program to calculate age in seconds Any thoughts?

print('*'*44+'\n****How Many Seconds Have You Been Alive****\n'+'*'*44)

while True:
    try:
        print('\n--------------------------------------------')
        Age = int(input('\nHow old are you?: '))

        if Age<1 or Age>90:
            print('(Input Error)*Enter Valid Age*')
            continue

    except(TypeError,ValueError):
        print('(Input Error)*Enter Valid Age*')
        continue

    seconds = str(Age*31536000)

    def splitthousands(x, sep=','):  #Inserts a comma after every three digits from the right.
        if len(x) <= 3: return x
        return splitthousands(x[:-3], sep) + sep + x[-3:]

    print('\nYou have been alive for '+splitthousands(seconds, sep=',')+' seconds.')
    print('\n--------------------------------------------')

    while True:
        try:
            reply = str(input('\nDo you want to play again(Y/N)?: ').title())

        except(TypeError,ValueError):
            print('(Input Error)*Enter Valid Option*')
            continue

        if reply.startswith('Y'):
            break

        else:
            raise SystemExit

I am fully agree with what @Jamal has said. Apart from that I would like to add some more points.
Use consistency in your code
Although PEP8 says there is no strict rule for naming convention, if you stick to one particular convention it'll be easier for you and the reviewers to follow.
In your code you have used reply, seconds which starts with lowercase letter but Age starts with uppercase letter.
I use the following convention

normal variables: lowercase_with_underscore
class names: CamelCase.
constants: UPPERCASE

And about the function which you defined inside the while loop
Only in certain cases(like in decorators) you should define your function
inside an enclosing scope. Defining a function inside while loop means, whenever the while condition become true it will encounter that function block which is time consuming.
Better define your function outside the while block and it improves readability.
Hard coding
You have hard coded the numbers like 1, 90, 31536000. Giving names to these number will help you a lot in the future.
Creating function
Creating a function for the calculation of age-in-seconds will allow you for the re-usability of your work.
After changing all the stuff, my function is looking like the following
SECONDS_IN_A_YEAR = 31536000
LOWEST_AGE = 1
HIGHEST_AGE = 90

def splitthousands(x, sep=','):
    '''
    Inserts a comma after every three digits from the right.
    '''
    if len(x) <= 3:
        return x

    return splitthousands(x[:-3], sep) + sep + x[-3:]

def calc_age_in_seconds(age):
    '''
    calculates the given age in seconds

    :raises: ValueError
    '''

    if age < LOWEST_AGE or age > HIGHEST_AGE:
        raise ValueError

    return age * SECONDS_IN_A_YEAR

def ask_user_and_calc_age_in_seconds():

    print('*'*44+'\n****How Many Seconds Have You Been Alive****\n'+'*'*44)

    while True:
        try:
            print('\n--------------------------------------------')
            age = int(input('\nHow old are you?: '))

            seconds = str(calc_age_in_seconds(age))

        except(TypeError,ValueError):
            print('(Input Error)*Enter Valid Age*')
            continue

        print('\nYou have been alive for '+splitthousands(seconds, sep=',')+' seconds.')
        print('\n--------------------------------------------')

        while True:
            try:
                reply = str(input('\nDo you want to play again(Y/N)?: ').title())

            except(TypeError,ValueError):
                print('(Input Error)*Enter Valid Option*')
                continue

            if reply.startswith('Y'):
                break

            else:
                raise SystemExit

if __name__ == '__main__':
    ask_user_and_calc_age_in_seconds()


Custom iOS chat interface design & functionality Preamble

So, as most of you have likely also noticed, chat components, at least at a basic level, are becoming very common with lots of apps.  I found myself tweaking and redesigning the interface from my last project all the time, so I decided to just create an easy to drop in solution.  I'd love to get some second opinions on the code, the design, the class interface, or whatever else you've got to say about it!

Full Project Here

 Usage

ViewController.h

#import <UIKit/UIKit.h>

#import "ChatController.h"

@interface ViewController : UIViewController <ChatControllerDelegate>

@property (strong, nonatomic) ChatController * chatController;

@end

Launch With This:

if (!_chatController) _chatController = [ChatController new];
_chatController.delegate = self;
_chatController.chatTitle = @"Simple Chat";
_chatController.opponentImg = [UIImage imageNamed:@"tempUser.png"];
[self presentViewController:_chatController animated:YES completion:nil];

Receive Message (Delegate):

- (void) sendNewMessage:(NSString *)messageString {
    NSLog(@"Received msg: %@", messageString);
}

Add Message:

It receives a dictionary with the message set as a content key.  We use the dictionary within the controller so we can pass additional information like userId's, to see who sent the message, or timestamps.  This is just a demo.

NSMutableDictionary * newMessageOb = [NSMutableDictionary new];
newMessageOb[kMessageContent] = @"Some Message To Send";

// Add Message Right To Collection
[_chatController addNewMessage:newMessageOb];

You'll also have to go into the controller and add some logic to assign who sent the message. Right now it's random just so you can see how it looks and works:

int sentByNumb = arc4random() % 2;
message[kMessageRuntimeSentBy] = [NSNumber numberWithInt:(sentByNumb == 0) ? kSentByOpponent : kSentByUser];

You can put whatever logic you'd want there, likely something similar to:

NSString * sentById = message[@"sentById"];
if ([sentById isEqualToString:currentUserId]) {
    message[kMessageRuntimeSentBy] = [NSNumber numberWithInt:kSentByUser];
}
else {
    message[kMessageRuntimeSentBy] = [NSNumber numberWithInt:kSentByOpponent];
}

 Design

[ChatController new];
This is perfectly fine syntax, but an Objective-C purists doesn't necessarily like the new method that much.  new is simply an NSObject method that looks like this:
+ (instancetype)new {
    return [[self alloc] init];
}

And as such, anything that inherits from NSObject will have this method.  But the only reason it exists as far as I know is for something like a security blanket for people coming from other languages where object instantiation might look something like this:
ChatController *chatController = new ChatController();

They want to hang on to their new keyword--their clue that they're instantiating a new object.  And while this is fine for those who choose to use it, a complete class would write its own factory method(s) in addition to the default one inherited from NSObject.
NSArray, NSDictionary, NSNumber, NSDate, etc, etc, etc.  Most of the Foundation classes have their own method that does something similar to what the new method does.  You would be wise to follow suite with a method that looks something like this:
+ (instancetype)chatController {
    return [[self alloc] init];
}

Now, someone like me who prefers doing things the real Objective-C way can do [ChatController chatController] in place of new.
As someone who might use a library like yours, the existence of such a method tells me that you've paid some attention to your instantiation methods and aren't relying on those inherited from NSObject.  This assures me that any instance variables that need to be set before I call any methods (if any at all) are definitely going to be set.
As a note, if you override init, this instance variables will still be set when calling new, because remember, new is simply return [[self alloc] init]; so it calls the init method you wrote.

The fact of the matter is though, whether we use [ChatController new];, [ChatController alloc] init];, or [ChatController chatController];, your class isn't completely ready to use.
What would happen if I presented an instance of your ChatController class before I set the delegate, chatTitle, and opponentImg?  Hopefully, you've written the class in such a way that nil or an empty string is a perfectly fine title, and that nil for opponentImg causes no problems.  But what about the delegate?
Sometimes, objects that can have a delegate function somewhat fine without a delegate.  For example, a tableview has a delegate property, but it also has a datasource property.  The datasource fills the table with information.  The delegate handles user interaction with the table.  But if you don't need to respond to any of the user interactions and only need the table to display information to a user, your table will function just fine without a delegate.  (And a table with static information doesn't need a datasource--the static cells can be completely created in IB).
Is this the case with your ChatController?  Can it function just fine without a delegate?
If these three properties are all truly optional and the class works just fine if they're all set to nil, then you're fine as you are and the following information would be something optional to consider, purely a nicety (one which I always include in my classes).  However, if these properties are not optional and it's not okay to set them to nil, then you really need to implement some factory methods.
Assuming only the delegate is necessary, first we'll create a new init method:
- (id)initWithDelegate:(id<ChatControllerDelegate>)delegate {
    self = [super init];
    if (self) {
        _delegate = delegate;
    }
    return self;
}

This method takes the delegate as an argument and sets this property upon while it's doing its initializing.  But as is, we have to write:
ChatController *chatController = [[ChatController alloc] initWithDelegate:self];

So let's wrap it in a factory method:
+ (instancetype)chatControllerWithDelegate:(id<ChatControllerDelegate>)delegate {
    return [[self alloc] initWithDelegate:delegate];
}

Now, it's as simple as this:
ChatController *chatController = [ChatController chatControllerWithDelegate:self];

Following this same pattern, you should include a factory method that sets all the properties that a user is likely to want to set before doing anything with the object.  For example:
- (id)initWithDelegate:(id<ChatControllerDelegate>)delegate
             chatTitle:(NSString*)chatTitle
         opponentImage:(UIImage*)opponentImage {
    self = [super init];
    if (self) {
        _delegate = delegate;
        _chatTitle = chatTitle;
        _opponentImage = opponentImage;
    }
    return self;
}

+ (instancetype)chatControllerWithDelegate:(id<ChatControllerDelegate>)delegate
                                 chatTitle:(NSString*)chatTitle
                             opponentImage:(NSString*)opponentImage {
    return [[self alloc] initWithDelegate:delegate
                                chatTitle:chatTitle
                            opponentImage:opponentImage];
}


Use an existing invoice if one exists, else create one Here are the requirements:

If initial_invoice? is false, existing_invoice always exists.
If initial_invoice? is true and existing_invoice exists, I'd love to use the existing_invoice.

I'd love to refactor this code.

 existing_invoice = find_existing_invoice(invoice_obj[:id])
   invoice = if !initial_invoice?(invoice_obj) || existing_invoice.present?
                existing_invoice
              else
                ac = Account.find_by(stripe_customer_id: invoice_obj[:customer])
                create_initial_invoice(invoice_obj, ac)
              end

  private

  def find_existing_invoice(id)
    Invoice.find_by(stripe_invoice_id: id)
  end

  def initial_invoice?(invoice_obj)
    sub_id = invoice_obj[:subscription]
    return false if sub_id.nil?

    sub = Stripe::Subscription.retrieve(sub_id)
    return false unless invoice_obj[:period_start] == sub[:created]
    true
  end

update

invoice = if initial_invoice?(invoice_obj)
            return existing_invoice if existing_invoice.present?

            ac = Account.find_by(stripe_customer_id: invoice_obj[:customer])
            create_initial_invoice(invoice_obj, ac)
          else
            existing_invoice
          end

The refactor goal was to make clear the logic for getting an invoice.

THIS IS THE MOST IMPORTANT POINT: Original code tells me there are 2 kinds of invoices so I knew I wanted a "if" that stated very simply and high level the logic for deciding which. So I wrote that and worked all the rest of the code around it.
Moving code into the get_xxx methods I saw that fetching the existing invoice was in both methods.
The above had me realize that no matter what, we use an pre-existing invoice if it's there. So I pulled that line out and put it at the top. Now it is obvious what's really going on.
I renamed invoice_obj because that sounds like it's an invoice too. But it's not. Its properties are used for fetching an actual invoice. So I thought of invoice_obj as metadata of a real invoice.
Make both "if" branches the same "level of abstraction". I'm trying to express that there are 2 kinds of invoices. I'm hiding the detail code that actually does it - that's a different level of detail.

I want it to say this:

if ...
  get_initial_invoice(metadata)
else
  get_invoice(metadata)

and not this:

if ...
  get_initial_invoice(metadata)
else
  Invoice.find_by(metadata[:id])

Refactored Code

 return existing_invoice if existing_invoice.present?

 invoice = nil

 if initial_invoice?(invoice_metadata)
    invoice = get_initial_invoice(invoice_metadata)
 else
    invoice = get_invoice(invoice_metadata)
 end

 return invoice

 private

 def get_initial_invoice(invoice_metadata)
    ac = Account.find_by(stripe_customer_id: invoice_metadata[:customer])
    create_initial_invoice(invoice_metadata, ac)
 end

 def get_invoice(invoice_metadata)
    return Invoice.find_by(invoice_metadata[:id])
 end

 def initial_invoice?(invoice_metadata)
   return false if invoice_metadata[:subscription].nil?

   sub = Stripe::Subscription.retrieve(invoice_metadata[:subscription])
   invoice_metadata[:period_start] == sub[:created] ? true : false
 end


PHP Validation Class I'm looking for advice and ways on making it better.

Code

<?php

Class Validate {

    private $_errors = array();

    public function __construct()
    {
        require_once 'errors.php';
        $this->errorText = $errorText;
    }

    public function rule($value, $name, $inputRules)
    {

        $inputRules = explode('|', $inputRules);
        foreach ($inputRules as $inputRule) {

            if (!strlen($value) && $inputRule != 'required') {
                break;
            }

            if (preg_match('/\[(.*?)\]/', $inputRule, $match)) {

                $rule = explode('[', $inputRule);
                $rule = $rule[0];
                $param = $match[1];
                if (!method_exists($this, $rule)) {
                    throw new Exception("Method {$rule} does not exist");
                    exit;
                }

                $call = array($value, $param);
            }
            else {
                if (!method_exists($this, $inputRule)) {
                    throw new Exception("Method {$inputRule} does not exist");
                    exit;
                }
                $rule = $inputRule;
                $call = array($value);
            }

            $response = call_user_func_array(array($this, $rule), $call);

            if ($response) {
                $error = $this->errorText[$rule];
                $replace = array(
                    ':name' => $name,
                    ':param' => (isset($param)) ? $param : NULL
                );
                $response = str_replace(array_keys($replace), array_values($replace), $error);

                $this->_errors[] = $response;
            }

        }

    }

    public function exec()
    {
        return (empty($this->_errors)) ? false : $this->_errors;
    }

    /*
    * Rule functions
    */

    public function min_length($value, $param)
    {
        return (strlen($value) < $param);
    }

    public function max_length($value, $param)
    {
        return (strlen($value) > $param);
    }

    public function email($value)
    {
        return !filter_var($value, FILTER_VALIDATE_EMAIL);
    }

    public function required($value)
    {
        return (strlen($value) !== 0);
    }

    public function ip($value)
    {
        return !filter_var($value, FILTER_VALIDATE_IP);
    }

    public function match($value, $param)
    {
        return ($value != $param);
    }

    public function match_exact($value, $param)
    {
        return ($value !== $param);
    }

    public function match_password($value, $param)
    {
        return ($value !== $param);
    }

    public function alphanum($value)
    {
        return !ctype_alnum($value);
    }

    public function url($value)
    {
        return !filter_var($value, FILTER_VALIDATE_URL);
    }

    public function numeric($value)
    {
        return !(is_numeric($value));
    }

    public function min($value)
    {
        return ($value < $param);
    }

    public function max($value) {
        return ($value > $param);
    }

}

Technical Issues

public function __construct()
{
    require_once 'errors.php';
    $this->errorText = $errorText;
}

Will not do what you think it will do.

$val1 = new Validate();
$val2 = new Validate();

The second instance will not include 'errors.php', and thus $errorText will not be defined.

You should probably consider generalizing your error message handling since you might need to have different messages or internationalization.

In other words, your class should probably either return error codes (class constants), or your class should have some kind of facility for requesting a different error message at run time.

If you do stick with your current approach though, consider structuring it something like:

public function __construct()
{
    $this->errorText = $this->getErrorText();
}

private function getErrorText()
{
    include 'errors.php';
}

Your errors.php would then look like:

<?php
return array(
    'something' => 'Some message'
    'somethingElse' => 'some other message',
    ...
);

This would of course mean that the file is included on every object instantiation though.  A different approach could be to store the messages in a static variable the first time they're needed.

Also, while I'm talking about this, errors.php could be a problematic path.  You should probably use something like dirname(__FILE__) . '/errors.php'; so the path is more resistant to outside factors.

if (!method_exists($this, $rule)) {
    throw new Exception("Method {$rule} does not exist");
    exit;
}

There's two issues here:

exit will never be reached
exit shouldn't here

When you throw an exception, you bail out of the current scope up until you hit a catch block.  No code under the throw will be executed.

function f() {
    throw new Exception();
    //No code here is ever excecuted
}

function f() {
    if (...) {
        throw new Exception();
        //Code here is never excecuted
    }
    //Code here will be executed only if the throw above is not reached
}

function f() {
    try {
        if () {
            throw new Exception();
            //Code here is never exceuted
        }
        //Code here is executed if the throw is not reached
    } catch (Exception $e) { }
    //Code here is always executed
}

It gets a bit more complicated than that, but those examples should illustrate the basic behavior.

exit shouldn't be in there anyway though.  Would you actually want script execution to completely stop?  Typically exit should only be used if there is no way to continue the program execution without compromising security or stability.

Imagine if instead of throwing exceptions, you had only the exits there.  This means that no error message would be displayed.  Nothing would be logged.  The code would just bail.

Imagine if someone was using your class based only on the API.  They would have no idea why the code exited.

Typically low level flow control like exiting or redirecting to a different page, so on, should be handled in dedicated "controller" code and not in classes that have responsibilities unrelated to that.

Throwing an exception is the right thing to do here. It allows the code that called rule to decide how to handle it.  rule should only responsible for saying "Hey, ummm, something wen't horribly wrong," not deciding how to handle it.  (In fact, an uncaught exception is basically an exit with debugging information included :p.  You do have to be careful with uncaught exceptions though as you need to make sure they don't get displayed to end clients.  Some exceptions, like PDOException, may contain sensitive data like database credentials.)

Design Issues

Your class does way too much. This is just using a class as a collection of functions. Each validation can be seen as a "responsibility" and thus your class completely violates the single responsibility principle.

Imagine that in the future you want to add a new validation.  How can you do this?  Well, you have two options, both of which are unpleasant:

Edit the source code. What if many people are using your class though, or you're using it across 10 applications?  Suddenly you have a lot of version management going on.  Since you control the class, you could just commit it all to git which would alleviate the synchronization, but what about end-consumers of your code?  This isn't a viable option for them.
Extend the class. This is also a bad option. You would have to change all of the object types in your code to be a MyValidation instead of Validation.  Depending on how widespread this was, this could be a huge chore.

Or, you have a third option.  Scrap your current design and abstract each validation into its own class.  You could have a very simple interface:

interface Validator
{

    /**
     * Validates the given $data against whatever rule(s) the implementation of this
     * interface enforces.  Returns an array of error messages, or an empty array
     * if $data is valid.
     *
     * @param mixed $data
     * @return array An array of error messages
     */
    public validate($data);

}

And then you could build on this:

class RangeValidator implements Validator
{

    private $_from;
    private $_to;

    const ERROR_INVALID_TYPE = 'type';
    const ERROR_OUT_OF_RANGE = 'range';

    //You could pull this into an abstract base class to handle code -> message mapping automatically.
    //That would also allow for easy internationalization later.
    private $_messages = array(

    );

    public function __construct($from, $to)
    {
        //You could make this a lot looser and perhaps put it in methods setFrom and setTo.
        //Just an example.
        if (!is_int($from)) {
            throw new InvalidArgumentException("\$from must be an int.  Given value: '{$from}'");
            }
            if (!is_int($to)) {
                throw new InvalidArgumentException("\$to must be an int.  Given value: '{$from}'");
        }
        $this->_from = $from;
        $this->_to = $to;
    }

    public function validate($data)
    {
        if (is_int($data) || (is_string($data) && ctype_digit($data))) {
            if ($data >= $this->_from && $data <= $this->_to) {
                return array();
            } else {
                return array(self::ERROR_INVALID_TYPE => $this->_messages[self::ERROR_INVALID_TYPE]);
            }
        } else {
            return array(self::ERROR_INVALID_TYPE => $this->_messages[self::ERROR_INVALID_TYPE]);
        }
    }

}

This looks very laborious at first, but it gives you a certain degree of flexibility you didn't have before.  Consider how you add a new validator now.  You just create a new class completely unrelated to any of the other ones.  (Technically it would implement Validator, and perhaps extend an abstract base class.  What I mean though is that it doesn't change any of the other classes.)

In this system, consumption of your code is much simpler too.  How does someone that doesn't have write access to your git repository create their own validator?  They just implement validator in their own namespace rather than in yours.  (Oh, side note, you should probably be using namespaces.)

For simplicity, you could make a "composite" Validator that just ties a bunch of validators together:

class EvenValidator implements Validator
{
    //Imagine that this validates whether or not a number is even
    //(Yes, really weird example :p)
}

class CompositeValidator implements Validator
{

    $this->_validators = array();

    public function __construct(array $validators = array())
    {
        foreach ($validators as $validator) {
            $this->addValidator($validator);
        }
    }

    public function addValidator(Validator $validator)
    {
        $this->_validators[] = $validator;
    }

    public funtion validate($data)
    {
        $errors = array();
        foreach ($this->_validators as $validator) {
            $errors += $validator->validate($data);
        }
        return $errors;
    }

}

You could then use it like:

$range = new RangeValidator(1, 100);
$even = new EvenValidator();
$comp = new CompositeValidator(array($range, $even));

$comp->validate(5); //Returns an array of one message: 5 isn't odd
$comp->validate(2); //Returns an empty array
$comp->validate(222); //Returns an array of one message: 222 out of range
$comp->validate(223); //Two messages: 223 out of range and odd

This is some pretty clumsy usage here.  With more than 5 seconds of thought though, an interface could be designed that allowed for very robust functionality while leaving the code highly maintainable and extensible.

You could even take it a step farther than a composite validator and make a "Form" class that has "Element"s which each have zero or more "Validator"s.  (The approach take by Zend Framework, and I'm sure others).

If you're familiar with any PHP frameworks, you might note that all of that above looks eerily familiar.  In particular, that's a modified version of the Zend_Validate interface from the Zend Framework.

I would suggest you pick a framework, go through the code, figure out how they designed things, and then ask yourself why they designed them that way: what the alternatives could have been and why they picked the path they chose.  If you do look at frameworks for design, make sure you look at more than one.  Though most of the major PHP frameworks/libraries are very well written overall, all of them have at least one area where they far from shine.

Also, if you haven't already, read everything you can find about SOLID.


Finding all pairs of numbers in a collection whose sum is some particular number I had to write the method that extract all pairs of numbers from collection of numbers, which sum matches the particular number.

static void Main(string[] args)
{
    var inputCollection = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    var targetNumber = 12;

    var pairs = ExtractPairs.Extract(inputCollection, targetNumber);

    foreach (var pair in pairs)
    {
        Console.WriteLine(pair.First + ", " + pair.Second);
    }
}

public class ExtractPairs
{
    public struct Pair
    {
        public int First;
        public int Second;
    }

    public static List<Pair> Extract(List<int> input, int targetNumber)
    {
        var pairs = new List<Pair>();
        var current = input[0];
        do
        {
            for (int i = current; i < input.Count; i++)
            {
                if (current + input[i] != targetNumber) continue;
                var pair = new Pair
                {
                    First = current,
                    Second = input[i]
                };
                pairs.Add(pair);
            }
            current++;
        } while (current < input.Count);

        return pairs;
    }
}

I think my algorithm should be more productive, but not sure in which way. Any suggestion and/or code will be helpful.

You haven't clarified what you're expecting your input to be but your code doesn't work unless the input is a set of positive integers starting at 1 and increasing 1 at a time.
For example:
var inputCollection = new List<int> { 5, 6, 7 };
var targetNumber = 12;

var pairs = ExtractPairs.Extract(inputCollection, targetNumber);

Clearly, 5 + 7 = 12 but your code returns no pairs! That's either a huge bug or the algorithm is expecting a very restricted input. I'd put my money on a huge bug.

Don't make structs with public mutable fields (unless you're in a very specific performance critical scenario). As pointed out in comments, I should have backed up this advice with some evidence. Here's an SO question about it or simply quoting the MS guidelines for struct design

X DO NOT define mutable value types.
Mutable value types have several problems. For example, when a property getter returns a value type, the caller receives a copy. Because the copy is created implicitly, developers might not be aware that they are mutating the copy, and not the original value. Also, some languages (dynamic languages, in particular) have problems using mutable value types because even local variables, when dereferenced, cause a copy to be made.

public struct Pair
{
    public int First;
    public int Second;
}

Make them readonly properties and add a constructor. I'd probably just use a Tuple<int, int> though.

Prefer formatting strings over concatenation:
Console.WriteLine(pair.First + ", " + pair.Second);

could be:
Console.WriteLine("{0}, {1}", pair.First, pair.Second);

In C#6 we also have string intperpolation:
Console.WriteLine($"{pair.First}, {pair.Second}");

In this simple case, the concatenation is actually fine. It's clear because it's short. As things become longer and more complex, the format string approach can make the final string clearer to see for a human. There are also a great many options for things like padding and formatting numbers and dates that are easily done in the format string.
Just an FYI, the concatenation is turned into a call to string.Concat:
Console.WriteLine(string.Concat(new[] { pair.First, ", ", pair.Second }));