A design pattern often used, is to have a non generic base type and a generic type derived from it or a type implementing a non generic as well as a generic interface. An example is

public abstract class Comparer<T> :
    System.Collections.Generic.IComparer<T>, System.Collections.IComparer

You can see the full implementation here public abstract class Comparer<T> : IComparer, IComparer<T>.

You can see that it does an explicit implementaion of IComparer members and an implicit implementation of IComparer<T>. This hides the IComparer members when not accessed through this very interface. Original code:

public abstract int Compare(T x, T y);

int IComparer.Compare(object x, object y) {
    if (x == null) return y == null ? 0 : -1;
    if (y == null) return 1;
    if (x is T && y is T) return Compare((T)x, (T)y);
    ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
    return 0;
}

A possible approach for your metric class, would be to implement two interfaces IMetric and IMetric<T>. The collection would then have an element type of IMetric.

public interface IMetric
{
    string Name { get; }
    object Value { get; }
    eLogicalOperator LogicalOperator { get; }
    object Threshold { get; }
    bool Faulty();
}

public interface IMetric<out T> : IMetric
{
    new T Value { get; }
    new T Threshold { get; }
}

Implementation:

public class Metric<T> : IMetric<T>
{
    public Metric(string name, eLogicalOperator logicalOperator, T value, T threshold)
    {
        Name = name ?? String.Empty;
        LogicalOperator = logicalOperator;
        Value = value;
        Threshold = threshold;
    }

    public T Value  { get; }
    public T Threshold  { get; }

    object IMetric.Value => Value;
    object IMetric.Threshold => Threshold;

    public string Name  { get; }
    public eLogicalOperator LogicalOperator { get; }

    public bool Faulty()
    {
        //TODO: implement;
    }
}

I don't know, however, how you would implement the Faulty method in a generic way. Maybe you could inject the logic and use a factory method to create metric objects.

Probably a better approach is to create an abstract Metric<T> class having only the Faulty method abstract to be able to implement specialized variants.

public class DecimalMetric : IMetric<decimal>

Yet another, elegant possibility is to pass a delegate doing the comparison, instead of the operator enum.

public Metric(string name, T value, T threshold, Func<T,T,bool> isValid)

This allows you to provide a type specific comparison and saves you a complex processing for different operators. I prefer to ask the positive question "is valid". It feels better than specifying what is wrong. You can call it like this

new Metric<int>("int test", 5, 10, (v, threshold) => v < threshold)

Usage (still with you original constructor):

var list = new List<IMetric>();
list.Add(new Metric<int>("int", eLogicalOperator.LowerThan, 5, 10));
list.Add(new Metric<double>("double", eLogicalOperator.LowerThan, 2.45, 10.0));

object value = list[0].Value;

switch (list[0]) {
    case Metric<int> intMetric:
        int i = intMetric.Value;
        break;
    case Metric<double> doubleMetric:
        double d = doubleMetric.Value;
        break;
    default:
        break;
}

// or

switch (list[0].Value) { // of type object
    case int i:
        int myInt = i;
        break;
    case double d:
        double myDouble = d;
        break;
    default:
        break;
}


Calling synchronize is completely unnecessary and is actually a performance bottleneck.  For more information about synchronize, take a look at this Stack Overflow answer.  So we can go ahead and remove that line.

We can also get rid of the println as that's not really doing us much good.  There's not much point to it at all, especially if this is an iOS application.

We can make our logic a little better here too.  Let's avoid grabbing our value out of NSUserDefaults multiple times using an if let.  We can also take advantage of the fact that if the value has never been set for our key, grabbing it with integerForKey will return 0.  So, we can handle all scenarios the same:

let kKEY_TestsTaken = "testsTaken"
let defaults = NSUserDefaults.standardUserDefaults()
let testsTaken = defaults.integerForKey(kKEY_TestsTaken)
defaults.setInteger(testsTaken + 1, forKey: kKEY_TestsTaken)

The only remaining comment I have is that we can make our method name more clear.  Also, there's no reason not to give the user the ability to increment the test count by more than one.

func incrementTestCount(value: Int = 1) {
    let kKEY_TestsTaken = "testsTaken"
    let defaults = NSUserDefaults.standardUserDefaults()
    let testsTaken = defaults.integerForKey(kKEY_TestsTaken)
    defaults.setInteger(testsTaken + value, forKey: kKEY_TestsTaken)
}


I have no problem with +=, -= and even *=. But for /= and %=... perhaps I am just not used to them enough to like seeing them. I would recommend not using %=, but that is mostly my personal preference.

Other comments:

Instead of using the heightInInches as a field of the class, I would recommend passing it as a parameter to the method. Your method is only dependent of this single variable so I don't really see a reason to having it dependent on your class, especially since your method actually modifies this variable. You'd be much safer in having your method as

public String getHeightInFeetAndInches(int heightInInches) {

You could even make your method static if you would like (which I personally would recommend)
Your VALUE_OF_ONE_FOOT should be static as it is a constant value.
It is totally impossible for your leftOver value to be less than zero unless your heightInInches is also less than zero. And so far I haven't seen a single person with a negative height. Did you mean if (leftOver <= 0)?
I would have the last space as a part of the includeInches variable, as if it would be empty right now your return would end with a trailing space.
Please use more spaces and make this line }else if(leftOver <= 1) { into } else if (leftOver <= 1) {
As @palacsint has pointed out, your code has a serious bug. I believe you should use the following:

int leftOver = heightInInches % VALUE_OF_ONE_FOOT;
int newHeight = heightInInches / VALUE_OF_ONE_FOOT;

This would also have the benefit of not modifying your heightInInches variable (although I still think you should pass it as a parameter to the method instead of using it as a field).
As pointed out by P. Lalonde in the comments below, your VALUE_OF_ONE_FOOT should be renamed to something like INCHES_PER_FOOT. All constants are values of something.
Feature Request: Add support for the metric system ;)


Efficient way to copy unordered String into ordered String

I'd put token names and positions in a Map like this:

Map<String, Integer> tokenIndexes = new HashMap<String, Integer>();
tokenIndexes.put("token1", 0);
tokenIndexes.put("token2", 2);
tokenIndexes.put("token3", 4);
// ...

and then in the "sorting" part:

String[] newRow = new String[150];

for (int i = 0; i < row.length; i+=2) { // go two by two as you have keys in even indexes
    if(tokenIndexes.contains(row[i])) {
        int index = tokenIndexes.get(row[i]);
        newRow[index] = row[i];
        newRow[index + 1] = row[i + 1];
    } else {
        // handle missing token
    }
}

This way I would get rid of all "if-else" statements, although now I have to maintain a Map (which I think is easier than maintaining a list of "if-else").

UPDATE

I'm supposing you just receive that String array and you're unable to change the way the information is retrieved. If you can change the initial array with a Map that would simplify your code even further.

If that's the case then try this to capture your tokens instead of putting everything in an array (I'm supposing a key is the first token to appear):

Map<String, String> info = new HashTable<String, String>();
boolean isKey = true;
String lastKey = null;
String token;
while(tokensAvailable()  /* or (token = readToken()) != null */) {
    token = readToken();
    if(isKey) {
        lastKey = token;
    } else {
        info.put(lastKey, token);
    }
    isKey = !isKey;
}

And then when you have to print your table, you can do something like this:

printOut("VAL_1    --   VAL_2   --   VAL_3");
printOut(String.format("%08d  --  %10.2  -- %s", info.get("numericVal1"), info.get("monetaryVal2"), info.get("val3")));

String.format() is useful in these cases, you can control the format (like the width) of how every field is printed.


Extending an array to a specified length, alternating directions

This function working correctly but I want to see suggestions for
  optimizations and improvements.

Your source code is undocumented. See Godoc: documenting Go code.

By design, Go has a short, readable specification: The Go Programming Language Specification. As you write code, read useful parts of it in detail, for exanple, make (to make precise allocations), append (which may require multiple reallocations), copy (which has minimal bounds checking and may do block copies), and Index Expressions (which often require a bounds check), and so on.

Browse the Go standard library for useful packages. For example, the testing package provides testing and benchmark facilities.

Read and apply the Go Code Review Comments.

Your algorithm takes an array element view of the problem. Consider other algorihms. For example, a repeating, alternating pattern of input and reverse input.

  I want to see other way.

That's an excellent idea. I usually try to come up with three different ways to do things, although I often settle for two. I use code reviews to ask other people for ideas.

Here's one other way. It's a little different and much more efficient than your way. It uses the Go standard library and code review conventions, and Go's test and benchmark facilities.

alternate.go:

package main

import "fmt"

// alternate returns a list of length n
// with alternating a and reverse a.
func alternate(a []int, n int) []int {
    b := make([]int, n)
    // copy a
    copy(b, a)
    // copy reverse a
    for i, j := len(a)-1, len(a); i >= 0 && j < len(b); i, j = i-1, j+1 {
        b[j] = a[i]
    }
    // copy repeating pattern
    for i := 2 * len(a); i < n; i *= 2 {
        copy(b[i:], b[:i])
    }
    return b
}

func main() {
    a := []int{1, 2, 3, 4}
    for i := 0; i < 4*len(a)+2; i++ {
        fmt.Println(alternate(a, i), i)
    }
}

Output:

$ go run alternate.go
[] 0
[1] 1
[1 2] 2
[1 2 3] 3
[1 2 3 4] 4
[1 2 3 4 4] 5
[1 2 3 4 4 3] 6
[1 2 3 4 4 3 2] 7
[1 2 3 4 4 3 2 1] 8
[1 2 3 4 4 3 2 1 1] 9
[1 2 3 4 4 3 2 1 1 2] 10
[1 2 3 4 4 3 2 1 1 2 3] 11
[1 2 3 4 4 3 2 1 1 2 3 4] 12
[1 2 3 4 4 3 2 1 1 2 3 4 4] 13
[1 2 3 4 4 3 2 1 1 2 3 4 4 3] 14
[1 2 3 4 4 3 2 1 1 2 3 4 4 3 2] 15
[1 2 3 4 4 3 2 1 1 2 3 4 4 3 2 1] 16
[1 2 3 4 4 3 2 1 1 2 3 4 4 3 2 1 1] 17
$

alternate_test.go:

package main

import (
    "fmt"
    "testing"
)

func TestAlternate(t *testing.T) {
    a := []int{1, 2, 3, 4}
    n := 10
    got := fmt.Sprint(alternate(a, n))
    want := fmt.Sprint([]int{1, 2, 3, 4, 4, 3, 2, 1, 1, 2})
    if want != got {
        t.Errorf("want: %v got: %v", want, got)
    }
}

func BenchmarkAlternate(b *testing.B) {
    a := make([]int, 42)
    for i := range a {
        a[i] = i
    }
    b.ReportAllocs()
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        alternate(a, 1024)
    }
}

func arrayExm(array []int, limit int) []int {
    var res []int
    length := len(array)
    for i := 0; i < limit; i++ {
        if (i/length)%2 == 0 {
            res = append(res, array[i%length])
        } else {
            res = append(res, array[length-i%length-1])
        }
    }
    return res
}

func BenchmarkArrayExm(b *testing.B) {
    a := make([]int, 42)
    for i := range a {
        a[i] = i
    }
    b.ReportAllocs()
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        arrayExm(a, 1024)
    }
}

Output:

$ go test -v -bench=. alternate.go alternate_test.go
=== RUN   TestAlternate
--- PASS: TestAlternate (0.00s)
goos: linux
goarch: amd64
BenchmarkAlternate-4    500000    2576 ns/op    8192 B/op    1 allocs/op
BenchmarkArrayExm-4      50000   25783 ns/op   16376 B/op   11 allocs/op
PASS
ok      command-line-arguments  4.388s
$


A different way:

preg_match(':^/[^/]*/[^/]*/:', realpath(__DIR__), $matches);
$realPath = $matches[0];

This matches the first and second files in path, and stores them in $matches.


Interface

assert bytes(decode(encode(list('foo'.encode())))).decode() == 'foo'

To avoid using encode on strings or decode on bytes, you can use byte literals: b'foo'. This simplifies the writting to:

assert bytes(decode(encode(list(b'foo')))) == b'foo'

But then this let me wonder, why do the caller have to convert the arguments themselves? Why the need for list and bytes. A proper usage would be

assert decode(encode(b'foo')) == b'foo'

Which might let someone wonder decode to/encode from what? But assuming the module is properly named, that should not be an issue.

Now onto building functions that accept/returns bytes

Iteration and padding

When it comes to iterating over something in Python, it is deemed inelegant (and somewhat slower) to use indices rather than directly accessing content. Meaning for element in array: is way better than for i in range(len(array)): element = array[i]. Here you can argue that you can't easily iterate over groups of 3 or 4 elements at a time, but its forgetting about the itertools module and its variety of recipes.

grouper is the one you need:

from itertools import zip_longest

def grouper(iterable, n, fillvalue=0):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

There is thus no need to manually handle the padding in encode and you can simplify iteration:

for first, second, third in grouper(unpadded_buf, 3):
    encoded_padded_buf += [ first >> 2 ]
    encoded_padded_buf += [ (first & 3) << 4 | second >> 4 ]
    encoded_padded_buf += [ (second & 15) << 2 | third >> 6 ]
    encoded_padded_buf += [ third & 63]

It also has the advantage to handle any iterable the same way. Meaning you don't need to convert your bytes to list beforehand, it will do just fine.

Extra characters

You don't need to differentiate the case where len(unpadded_buf) % 3 is 1 or 2. You can perform the same task using:

extra = len(unpadded_buf) % 3
if extra:
    return asciied[-extra:] + '='*extra
return asciied

You can also note that there is no reason to make a copy of asciied, like you don't make a copy of decoded_buf in decode.

ALPHABET?

It feels like this variable is misnamed, it is not an alphabet, it is a convertion table TO_BASE64. Same for _alphabet, I would have named it FROM_BASE64 and computed it once, as a constant, as its content would never be different.

I would also incorporate {'=': 0} to simplify the map call.

So far, the code could be:

import string
from itertools import zip_longest

TO_BASE64 = dict(zip(range(64),
                     string.ascii_uppercase + string.ascii_lowercase +
                     string.digits + '+/'))
FROM_BASE64 = {v: k for k, v in TO_BASE64.items()}
FROM_BASE64['='] = 0

def grouper(iterable, n, fillvalue=0):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

def encode(unpadded_buf):
    encoded_buf = []
    for first, second, third in grouper(unpadded_buf, 3):
        encoded_buf += [ first >> 2 ]
        encoded_buf += [ (first & 3) << 4 | second >> 4 ]
        encoded_buf += [ (second & 15) << 2 | third >> 6 ]
        encoded_buf += [ third & 63]

    asciied = ''.join(TO_BASE64[n] for n in encoded_buf)
    extra = len(unpadded_buf) % 3
    if extra:
        return asciied[-extra:] + '='*extra

    return asciied

def decode(asciied):
    encoded_buf = (FROM_BASE64[n] for n in asciied)
    decoded_buf = []
    for first, second, third, fourth in grouper(encoded_buf, 4):
        decoded_buf += [ first << 2 | second >> 4 ]
        decoded_buf += [ (second & 15) << 4 | third >> 2 ]
        decoded_buf += [ (third & 3) << 6 | fourth ]

    return bytes(decoded_buf)

if __name__ == '__main__':
    assert decode(encode(b'foo')) == b'foo'

Adding elements to a list

You extend your "result" lists using other lists. It is rather inefficient as the list you use to extend the first one will be discarded right away. You’d be better of appending values to the "result" instead. Or use helper generator functions to build results as they are computed without having to populate a list that will be discarded right after:

import string
from itertools import zip_longest

TO_BASE64 = dict(zip(range(64),
                     string.ascii_uppercase + string.ascii_lowercase +
                     string.digits + '+/'))
FROM_BASE64 = {v: k for k, v in TO_BASE64.items()}
FROM_BASE64['='] = 0

def grouper(iterable, n, fillvalue=0):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

def _encoder(stream):
    for first, second, third in grouper(stream, 3):
        yield first >> 2
        yield (first & 3) << 4 | second >> 4
        yield (second & 15) << 2 | third >> 6
        yield third & 63

def encode(unpadded_buf):
    asciied = ''.join(TO_BASE64[n] for n in _encoder(unpadded_buf))
    extra = len(unpadded_buf) % 3
    if extra:
        return asciied[-extra:] + '='*extra

    return asciied

def _decoder(stream):
    for first, second, third, fourth in grouper(stream, 4):
        yield first << 2 | second >> 4
        yield (second & 15) << 4 | third >> 2
        yield (third & 3) << 6 | fourth

def decode(asciied):
    return bytes(_decoder(FROM_BASE64[n] for n in asciied))

if __name__ == '__main__':
    assert decode(encode(b'foo')) == b'foo'


Since ranges are immutable you would need to create your own range class that encapsulates the basic range object. This class will give you that and still keep and the methods associated with the basic range object.

class Myrange
  attr_accessor :range
  def initialize(a,b=nil,exc=false)
    if a.is_a? Range
      @range = a
    else
      @range = Range.new(a,b,exc)
    end
  end
  def addto_begin(x)
    Myrange.new(@range.begin + x..@range.end)
  end
  def addto_end(x)
    Myrange.new(@range.begin..@range.end+x)
  end
  def addto_begin!(x)
    @range = @range.begin + x..@range.end
    Myrange.new(@range)
  end
  def addto_end!(x)
    @range = @range.begin..@range.end+x
    Myrange.new(@range)
  end
  def to_s
    @range.to_s
  end
  def inspect
    self.to_s
  end
  def method_missing(*args,&blk)
    @range.send(*args,&blk)
  end
end

x = Myrange.new(1,10)
x = x.addto_begin(3)
p x #=> 4..10
y = x.addto_begin!(3)
p x #=> 7..10
p y.addto_end(3) #=> 7..13
p x.include? 9 #=> true :: Range methods still work


I like rolfl's approach, but I have one thing to add which would make it more compact and flexible:

Use a private constructor to provide a custom save value.

The biggest benefits of using either my or rolfl's approach is that you don't need to remember to add new enum values to the HashMap. In my approach especially, it gives you a clear overview of the enum values with their corresponding save values. As long as you only use one constructor (which I highly recommend) it is impossible to forget to give a save value for the enum.

This approach also allows you to customize their save-values much easier. You can rename your enums all you want, all you need to remember is to not change the saveValue, unless you want incompatibility issues.

enum ComponentState {
    TURNED_OFF("off"),
    TURNED_ON("on"),
    SUSPENDED("susp"),
    TO_REPAIR("repair");

    private final String saveValue;

    private ComponentState(String saveAs) {
        this.saveValue = saveAs;
    }

    private static final Map<String, ComponentState> FUZZY = buildMap();

    private static Map<String, ComponentState> buildMap() {
        Map<String, ComponentState> mapto = new HashMap<>();
        for (ComponentState state : ComponentState.values()) {
            mapto.put(state.saveValue, state);
        }
        return mapto;
    }

    private static final ComponentState fuzzyValueOf(String name) {
        return FUZZY.get(name);
    }

    public String getSaveValue() {
        return this.saveValue;
    }
}

If you want to have multiple possible save values for the same enum, then use a String... parameter: (However, in this case you need to make sure that you don't use an empty constructor for a field, as that wouldn't give it a specified save value)

    private final String[] saveValues;
    private ComponentState(String... saveAs) {
        this.saveValues = saveAs;
    }
    public String getSaveValue() {
        return this.saveValues[0];
    }

I really can't recommend using the .ordinal approach as ratchet freak suggested, even though it is nice and tidy, consider this enum:

Suit {
    DIAMONDS, HEARTS, SPADES, CLUBS;
}

Now what if you'd like to re-order them?

Suit {
    CLUBS, SPADES, DIAMONDS, HEARTS;
}

Congratulations, spades has become diamonds, clubs is hearts. Down is up and up is down. Logic goes on ski vacation with it's buddy reason.

If you use the .ordinal approach, remember to never ever ever switch places of them. (Me, talking from experience? What makes you think that?)


Your Convert function cycles through the values 4, 1, 7. You do this by comparing the given state with each possible state, and then return the next state. This could be made much simpler by using an index rather than values. Then instead of calling Convert, we can increment the index and if necessary wrap the index around by using a modulo operation. When we need the value, we can use the index to look it up in an array that contains these values.

This would look similar to:

int[] states = {4, 1, 7};
int i = 0;

// get the value:
states[i]

// increment the index:
i = (i + 1) % states.Length;

If we really want to go overboard with this, we could define a type that represents these cyclical states:

class Cycle<T>
{
    private readonly T[] values;
    private int i = 0;

    public Cycle(params T[] values)
    {
        this.values = values;
    }

    public T Value
    {
        get
        {
            return values[i];
        }

    }

    public static Cycle<T> operator++ (Cycle<T> cycle)
    {
        cycle.i = (cycle.i + 1) % cycle.values.Length;
        return cycle;
    }
}

Used as:

var states = new Cycle<int>(4, 1, 7);

// get the value:
states.Value

// increment the index:
++states;

While using such a class makes for a very nice interface, it's not exactly the most efficient thing to do. Using an array as shown at the top is probably a good compromise between good code and performance. In particular, both of my solutions allow you to set the values of the cycle at runtime, rather than hardcoding all values in an enum.


Traversing a multidimensional structure and applying strip() to all strings

I don't understand why you are checking for an __iter__ attribute, as you don't seem to use it. However I would recommend a couple of changes:

Use Abstract Base Classes in the collections module to test duck types, such as "Iterable"
Use types.StringTypes to detect string types

.

import collections
import types

def strip_spaces( item ):
    if isinstance( item, types.StringTypes ):
        return item.strip()

    if isinstance( item, collections.Iterable ):
        if isinstance( item, list ):
            return [ strip_spaces( value ) for value in item ]

        elif isinstance( item, dict ):
            return dict([ ((strip_spaces(key), strip_spaces(value)) \
                                    for key, value in item.iteritems() ])

        elif isinstance( item, tuple ):
            return tuple( [ strip_spaces( value ) for value in item ] )

    return item


Largest rectangle areas after drawing boundaries

I do have a solution for this question but apology because I am proficient in python
please add the answer who can write the same logic in JS also.
Thanks
what I have done is maintain array of width and height and get amximum width difference and height difference between adjcent location of H and W. which leads to maxArea of rectangle
This is not efficient solution as it was giving timelimit exceed on 3-4 test cases.so appreciate if anyone can optimize it.
def getMaxArea(w, h, isVertical, distance):
    # Write your code here
    def insort(test_list, k):
        for i in range(len(test_list)):
            if test_list[i] > k:
                break
        return test_list[:i] + [k] + test_list[i:]

    maxy = 0
    wline = [0,w]
    hline = [0,h]
    res = []
    for i in range(len(isVertical)):
        if isVertical[i]:
            wline = insort(wline, distance[i])
        else:
            hline = insort(hline, distance[i])
        wmax = 0
        hmax = 0
        for i in range(1,len(wline)):
            if wline[i] - wline[i-1] > wmax:
                wmax = wline[i] - wline[i-1]
        for i in range(1,len(hline)):
            if hline[i] - hline[i-1] > hmax:
                hmax = hline[i] - hline[i-1]

        res.append(hmax * wmax)
    return res


Int-Enum to String and vice a versa in Swift

Is the .none case really needed? It serves as a "fallback" in init(rawString: String)
if an unknown string is received from the network. But it is not listed in
the mapping dictionary, i.e. it can not be converted back to a string.

My suggestion is to remove that case, and use a failable initializer for the
conversion from a string:

init?(rawString: String) {
    let loweredStr = rawString.lowercased()
    guard let type = NetworkType.networkDict[loweredStr] else {
        return nil
    }
    self = type
}

Using a custom extension for the conversion to a string is not really necessary,
the same can be achieved directly with

func rawString() -> String? {
    return NetworkType.networkDict.first(where: { $1 == self }).map { $0.0 }
}

But the real question is: Why does this return an optional? It would return nil
if one of the enum cases is not covered in the dictionary. Let us assume that
you add another case five_g in the enumeration and forget to update the dictionary.
Now NetworkType.five_g.rawString() returns nil. What string do you send to the
server?

One possible approach would be to force-unwrap the string, so that this
programming error is detected early:

func rawString() -> String {
    return NetworkType.networkDict.first(where: { $1 == self }).map { $0.0 }!
}

But there is still a chance that the error remains undetected during development
and the deployed application crashes later.

A safer (and actually shorter and easier) approach is to define a string-based
enumeration, which implicitly defines the conversion to strings
and back:

enum NetworkType: String {
    case gprs
    case two_g = "2g"
    case three_g = "3g"
    case four_g = "4g"
    case lte
    case wifi
}

To make the comparison work, an ordinal number is associated with
each case:

extension NetworkType: Comparable {
    var ordinal: Int {
        switch self {
        case .gprs: return 1
        case .two_g: return 2
        case .three_g: return 3
        case .four_g: return 4
        case .lte: return 5
        case .wifi: return 6
        }
    }

    public static func < (a: NetworkType, b: NetworkType) -> Bool {
        return a.ordinal < b.ordinal
    }
}

Now the conversion is done using the built-in methods:

// String to NetworkType:
if let network = NetworkType(rawValue: "gprs") {
    // ..
} else {
    // unknown string from network
}

// NetworkType to String:
let rawString = NetworkType.gprs.rawValue

The conversion to a string cannot fail anymore. If another case is added, the compiler ensures that it is added to var ordinal as well.


Project Euler #8 in C++: greatest product of k consecutive digits

Extra multiplication

    unsigned long long product=1;
    for (int j=start;j<end;j++){
        product*=ctoi(number[j]);
    }

You can do one less multiplication.

    unsigned long long product = ctoi(number[j]);
    for (int j = start + 1; j < end; j++) {
        product *= ctoi(number[j]);
    }

Obviously this would fail if K were less than 1, but that's outside the problem scope.

ctoi is not a free operation

You also perform ctoi at least K times for each digit.  You could do this just once with something like

    std::vector<int> digits;
    for (char c : number) {
        digits.push_back((int)(c - '0');
    }

Then operate on digits rather than number.

Benchmark optimizations

            if (ctoi(number[l-K])!=0){
                product=(product/ctoi(number[l-K]))*ctoi(number[l]);
            }else{
                product=prodK(number,l-K+1,l+1);
            }

In theory, this saves K-1 multiplications at the cost of doing a multiplication, a division, and a comparison/branch.  But don't forget that it adds a comparison/branch to every iteration.  You might find that is cheaper to always do the K-1 multiplications.

Benchmark it both ways with a variety of inputs to see.

Don't waste math

You have

    for (int j=start;j<end;j++){

and

                    product=prodK(number,l-K+1,l+1);

But you could just have

    for (int j = start; j <= end; j++){

and

                    product = prodK(number, l-K+1, l);

That saves you an addition.  Might not be worth much, but it also might be better than nothing.

Assignments can be expensive

            max=(product>max)?product:max;

This will produce the correct answer, but it does an assignment every time.  You don't need to do the no-op assignment.  Benchmark against

            if (product > max) {
                max = product;
            }

That's more code, but it's faster unless the compiler already optimizes out the no-op assignment.  Probably not a lot faster, as this is a comparatively simple assignment.

Simplify compare

    for (int i=0;i<T;i++){

i<T is often implemented as i - T < 0.  But do you need to do the i - T?

Since you never use T for anything other than this loop, you could say

    for (; T > 0; T--) {

That saves having an i variable at all, and now you compare T to 0 directly.

Benchmark

These are suggestions that assume that the compiler is operating in a certain way.  If I'm wrong about that, then some of these suggestions may be counterproductive.  Note that the compiler may have similar or better optimizations that it is already doing.  You benchmark to confirm (or refute) such assumptions.


First of all, I wouldn't call it "rotate" as rotate has a significant meaning in programming. What you're doing though is picking up n random values and rotating them by themselves, and not in context to the array itself.

Anyways, I'll just explain in the code for the rest.

function rotate(arr, n){

  // I wouldn't want to mutate the original array in the operation
  // so instead I operate on a shallow copy of the array.
  var arrToOperate = arr.slice();

  // Then we select indices by random.
  // The | 0 at the end truncates the decimal part, like floor.
  // We sort, since rotation needs to know who is last/first.
  var selectedIndices = [];
  for(var i = n; i--;) selectedIndices.push((Math.random()*arr.length) | 0);
  selectedIndices.sort();

  // Now the actual rotation. If value isn't the zeroth number, get the next
  // otherwise get the one from the other end.
  for(var j = n; j--;) arrToOperate[selectedIndices[j]] = arr[selectedIndices[(!j ? n : j) - 1]];

  return arrToOperate;

}

alert(JSON.stringify(rotate([10,20,30,40,50,60], 3)));

Looping backwards is personal preference, because I don't have to use comparison operators, and I can always use 0 as the terminator value.

The | 0 is also a personal preference, as it is shorter (and sometimes faster) than Math.floor.


Programmatically using `exec` to load files

Looping
while True:
    if test_load(): return  # Run until files load

should simply be
while not test_load():
    # ...

Getting files
It's good that you're using a generator, but you should consider basing it off of pathlib instead of os. Also, it seems like you should care less whether your file starts with underscores, and more that it's a file instead of a directory. For instance:
return (
    file
    for file in Path(dir).iterdir()
    if file.is_file()
)

Dynamic loading
You're not just loading any files - you're loading arbitrary Python modules. Since your examples only show variables being initialized, I'm going to go out on a limb and say: please, please don't load Python code when you should simply be loading data, from any of the common formats - a pickle, or JSON, or CSV, or what-have-you. It's easier, faster, more secure and generally less of a headache.


Object Oriented Programming Improvements

The first thing you can do to improve code like this is to use dependency injection, instead of instantiating objects with new inside of objects.

// Setup your class hierarchies like this.

abstract class Controller
{
    protected $model;

    protected function __construct(Model $model)
    {
        $this->model = $model;
    }
}

class RootController extends Controller // or HomeController extends Controller
{
    public function __construct(Model $model)
    {
        parent::__construct($model);
    }
}

Then you execute:

$controller = new RootController(new RootModel());  // But, read on.

Notice the use of type hinting in the __construct function. Program to an interface, not an implementation.

Use abstract classes (which you cannot make an instance of) to factor out common properties and methods into one place. Extend abstract classes with specific species of classes. This is where the power of polymorphism via the Strategy Pattern comes in to play!

By type hinting with abstract classes, or interface types, you will not have to change your code simply because a different species of child object need to be used at some other point in time.

If you find that the parents of several classes should have the same functionality or constants, factor again and define a PHP Interface and slap it on to a class like this.

class RootController extends Controller implements Printable
{
    public function __construct(Model $model)
    {
        parent::_construct($model);
    }
}

Where in this case, Printable would be a set of virtual functions, and or constants, that form a contract, forcing any class that implements Printable to define certain public functions / hooks so that it can be used as a "Printable" object by unrelated code in other places.

Model-View-Controller Improvements

In terms of MVC, you may want to consider how a Model is going to send data to a View. Using a Controller's method as the working area for passing dat from a Model to a View is common. If a Controller's method can act as a working space for a particular command, then "M" and "V" (Model and View) can use "C's" method as a place to coordinate things.

Given the following, you could use your programming knowledge to devise a solution where a View is passed data from a Model, without injecting an instance of said Model into a View. In other words, you do not want to do this.

abstract class View
{
    protected $model;

    protected function __construct(Model $model)
    {
        $this->model = $model;
    }
}

class NewsletterView extends View
{
    public function __construct(Model $model)
    {
        parent::__constrcut($model);
    }
}

Summarizing, there are two well known options:

Use a method of a Controller (i.e. a command). Have the Model pass a data structure (array or iterable object) to the View.
Give the View a reference to the Model and delegate the chore of getting data to the Model within the View. However, as noted this is not what you want to do.

Note that option #2 can create strong coupling between a Model and a View, because the View must then use methods off of the Model instance to get at data. If a Model's methods change (such as the names, or method parameters), the View will have to change, accordingly.

What you want to do is have a setup like this.

abstract class Controller
{
    protected $model;
    protected $view;

    protected function __construct(Model $model, View $view)
    {
        $this->model = $model;
        $this->view = $view;
    }
}

class NewsletterController extends Controller // or HomeController extends Controller
{
    public function __construct(Model $model, View $view)
    {
        parent::__construct($model, $view);
    }

    /**
    * A totally made up method.
    */
    public function register(array $suscriberData)
    {
        $viewData = $this->model->addSubscriber($suscriberData));
        $this->view=>updateRegistrationPage($viewData);
    }
}

Then you execute:

$controller = new NewsletterController(new NewsletterModel(), new NewsletterView());

(Note: A dependency injection container can resolve class dependencies off screen and just issue you the object you request! Very handy, but not mandatory.)

Your URL to such a command would be:

http://yourdomain.com/newsletter/register

Where "newsletter" is your Controller, and "register" is the command.

Typically, the machinery of a framework (Front Controller / Router / Dispatcher), or just good programming generally, handles transforming the path component of a URL (REQUEST_URI) into an instance of a Controller. In that case, because instances are being created dynamically, you will want to use a class autoloader (as in PHP-FIG PSR-4) at minimum. Using an autoloader can eliminate all but one require statement for accessing classes. You will need one require statement to bring your autoloader code into scope. :-)

This is why people are encouraged to use namespaces with their OO PHP code. Using a PSR-4 compliant autoloader will automatically find and load your custom classes! The implication being, that your include_path no longer needs to list every dog-on path that you have classes loading from! ;-)

However, if you use modular HTML templates for your web pages (require header.php, require footer.php, require aside.php, etc ..), be sure to have the location of those files in your include_path!

Dependency injection containers are not mandatory, but they do simplify the usage of objects by decoupling where a class is instantiated from where it is used. In other words, a DI container is a very precise gumball machine for objects and other data. :-)


Detect loop in linked list (Floyd cycle finding algorithm)

DRY. The first loop of lengthOfLoop is literally identical to doesLoopExist. Replace it with

    loopExist = doesLoopExist();

This also hints that doesLoopExist should be Node * doesLoopExist(), and return a node on the loop or nullptr.
The destructor invokes UB when applied to the list with a loop. At the end of the loop the next pointer points to an already deleted node.
insert should be better called append.


While sharing styles is possible, I find it a little cumbersome and personally, I would not do it. Instead, I'd recommend going one level higher: do not share styles, share components.

That's what React is about - sharing components. In React Native, you won't have to import a component and styles (and pass the styles to the component), you'll just have to import the component. There will be less duplication.

I'd recommend you take a look at styled-components or glamorous-native, and see their utilities for defining styles, extending them and other utilities. They will make working with styles and components easier.


combinations of an integer list with product limit

Welcome to Python programming!

Your code has various formatting issues, including the fact that when copying it here, you messed up the indentation of the docstring in your function – copying what you write here into my development environment will not work because of that. But let's look at the semantics.

On a high level view, this sounds like a problem I would try to solve recursively.

All the products of one number that are less than or equal to a target (you don't state that equal-to is permitted, but the line if prod(B) > lim : makes me think that is what you want) are exactly the numbers n <= limit, and from there we can generalize to implementing ‘The product of k numbers ≤ p if x is the first number and the product of the remaining k-1 numbers ≤ p//x.’ Note that this works with integer division – If you allow floats or if your limit is exclusive, you need float division.

For that recursive solution, I would use a generator and yield every partial solution up the call chain until I get to the original loop that wants my results.

But let us assume that, for whatever reason, you indeed want a function that solves this iteratively, not recursively.

Then, even before I look at your function, it has issue: 2*3*11*13 = 858 < 1000, but that combination does not appear in your list, so you would do well trying to manually generate maybe two examples where you know the answer, and try to produce them using your function.

If you feel it difficult to use the mental arithmetics, trust the tools you mention:

def combinations_with_limit(lst, length, lim):
    return [x for x in itertools.combinations(lst, length)
            if prod(x) <= lim]

is quite a readable and explicit process. It might throw away a lot of things, but it should help you get test cases.

Once you have a working solution, there are several things in your code to look out for.

Calculating the product separately for various combinations, and even twice in your middle loop, will be expensive. Store it somewhere and manipulate it while moving about, instead of running prod too often, in particular if you have a need to access it twice, like in your if and elif.
You are manipulating both H and B in parallel. That feels dangerous: You need great care to make sure that H goes through all combinations, keeping the right length, and never gains any duplicate elements, and then you add the computational overhead of a full list comprehension on top to generate your Bs. That sounds easy to get wrong, and as your results show, one of the conditions indeed goes wrong.


Simulated annealing for magic square-of-squares puzzle

This is much more clear thanks to your edit.

Why do you store this as a list of squares? Can you store it as a unique list of positive integers, and square them later? That would make this massively simpler.

Another thing that would make this massively simpler is if you're able to guarantee that the list is maintained in some kind of order. In the example code below I do not assume this, so have to sort it myself. Maintaining order should be easy because the last_square mutation will not change order.

  Will my function always have the behaviour I've specified?

Sounds like you need to write some unit tests :) You will have to mock your random function to make them predictable.

  I care about checking if np.sqrt(c) != int(np.sqrt(c)) because a number whose square root is an integer is a square number.

Fine, but... you said that there was already a guarantee that these numbers are positive squares.

I tried to put together a vectorized version of this that does not loop. Rule number one when writing efficient Numpy code is to attempt to avoid loops. This solution roots, flattens and sorts the data, then looks for the closest gap. I do not know if it will perform better than yours, nor whether this is the most efficient implementation of this approach.

The performance will be influenced by the length of your data and the sparsity of your numbers. For highly sparse numbers the looping approach will probably do better. For highly dense numbers the approach below will probably do better.

def last_square_new(x):
    assert (x > 0).all()
    x = x.copy()

    # The n-dimensional random index. Cannot yet be used as an index.
    nd_index = np.random.default_rng().integers(
        np.zeros(x.ndim), x.shape
    )
    # What will the index of the chosen element be once the array is flattened?
    flat_index = nd_index[0]*x.shape[-1] + nd_index[1]
    # Make this usable as an index.
    nd_index = nd_index[:, np.newaxis].tolist()

    xsq = (np.sqrt(x) + 0.5).astype(np.uint64)     # Sqrt with safe conversion to int
    chosen = xsq[nd_index][0]                      # The randomly chosen element's sqrt
    xsq = xsq.flatten()                            # Flatten the root array
    s_indices = xsq.argsort()                      # Indices that would sort the root array
    flat_index = s_indices[s_indices][flat_index]  # Move the flat index to its sorted position
    xsq = xsq[s_indices][:flat_index+1]            # Sort the root array and truncate

    d_indices = np.arange(xsq.size-1)[np.diff(xsq) > 1]  # Which indices have gaps?
    if d_indices.size != 0:                              # Are there any gaps?
        gap_index = d_indices[-1]                        # Index of the closest gap (low side)
        best = xsq[gap_index+1] - 1                      # Best missing root
        x[nd_index] = best**2                            # Assign it to the output

    return x


Time interval class that enhances constructor argument handling of its parent class

If you don’t expect to be further subclassing MyInterval, you could just use a helper method for construction.

class MyInterval(Period):

    @classmethod
    def create(cls, start, end, inclusive=True, **kwargs):
        start = _toDate(start)
        end = _toDate(end)

        if inclusive:
            end = end.add(days=1)

        return cls(start, end, **kwargs)

Alternatively, you could use a helper method to avoid the duplicated code (but not duplicated execution).

class MyInterval(Period):

    @staticmethod
    def _fixup(start, end, inclusive):
        start = _toDate(start)
        end = _toDate(end)

        if inclusive:
            end = end.add(days=1)

        return start, end

    def __new__(cls, start, end, inclusive=True, **kwargs):
        start, end = cls._fixup(start, end, inclusive)
        return super().__new__(start, end, **kwargs)

    def __init__(self, start, end, inclusive=True, **kwargs):
        start, end = self._fixup(start, end, inclusive)
        return super().__init__(start, end, **kwargs)


Complete missing data in timeseries pandas

Don't forget you can chain operations (btw you missed the pandas import):

sensed_time = pd.DataFrame(index=index, columns=['was_sensed'])
sensed_time = sensed_time.fillna(1)
sensed_time = sensed_time.sample(frac=0.6)

x = pd.DataFrame(index=index, columns=['was_sensed']).fillna(1).sample(frac=0.6)

You can verify if this works by doing a sensed_time.shape == x.shape

Regarding the construction of your code, it seems like it would be a better idea to have the data object as a class, and get properties from it.

For instance, something along the lines of:

    class SmartPhoneData(object):
        def __init__(self, name=None):
            self.name = name or "Nokia6_32GB"
            self.data = pd.DataFrame(index=index, columns=['was_sensed']).fillna(1).sample(frac=0.6)

        def calls_per_day(self):
            print(f"SmartPhone Data: {self.data}")

        @property
        def minutes(self):
            return self.data.reindex(pd.date_range(sensed_time.index.min().date(), sensed_time.index.max().date() + pd.DateOffset(1), freq='1Min'))

        @property
        def hours(self):
            return self.data.groupby([pd.Grouper(freq='1H')]).count()

        @property
        def days(self):
            return self.data.groupby([pd.Grouper(freq='1D')]).apply(label_sensed_days, hours_in_day=24, percentage_valid_hours=0.8, percentage_valid_minutes=0.8)

    your_phone = SmartPhoneData()
    my_phone = SmartPhoneData("iPhone X")

    your_phone.calls_per_day()
    my_phone.calls_per_day()

Obviously I just took a single line from your code where it was similarly named (to match the function).
So if you do this - make sure you know how the data gets changed when you run each function. For instance, each of the @properties just does a return and doesn't modify the DataFrame, however some of your options might actually change the data contents (even if there is no assignment (e.g.: x = a + b doesn't change a or b, but a (not real code) self.data(column_names = ["one", "two"]) will change it). I hope that made sense?

Good Luck!


consistent indentation style

You have the opening bracket of your class blocks on the same line:

public class Register {
    private double purchase;

public class RegisterTest {

but other brackets that open blocks are on the next line.
No matter what style you choose, be consistent. I suggest you put the brackets on the next line all the time as this is what the majority of your code looks like already.

initialisation of variables

In your constructor, only one variable is initialised according to a parameter.

public Register(double tax)
{
    this.tax = tax;
}

Sure, numeric types have default values, but what are they?
It's best to assign values for variables to make things clear.

public Register(double tax)
{
    this.tax = tax;
    purchase = 0;
    payment = 0;
}

that other constructor

Your empty default constructor should be calling your other constructor.
This way you can set the default value for the parameter, make sure everything is initialised and reuse the existing code:

public Register()
{
    this(0.0);
}

public Register(double tax)
{
    this.tax = tax;
    purchase = 0;
    payment = 0;
}

combine operators

Do this

a += b;

instead of that

a = a + b;

calculate the factor for the tax only once

You do this calculation (tax/100) over and over again, although it has a constant result. Do it only once in the constructor to calculate the right factor and later just multiply by that factor:

public Register(double tax)
{
    this.tax = 1 + tax/100;

welcome to Panama

As I tried to point out in a comment, doing the tax calculation is totally optional in your code. If you forget to call the method, it simply doesn't happen.

Your Register is easily manipulated to save taxes. Financial systems are often complicated and people hate to deal with them. Now if your class tries to be helpful with doing financial calculations, it should ensure that the calculations are done right. But as you expose many public methods that have to be called in a certain order, somebody using your class could easily screw that up (either to their advantage or disadvantage). In a real world application, you'd have to run checks on all values if they are within acceptable boundaries.

So far this review is mostly suggesting things that could be considered good practices, but with that last paragraph, it's clear that a line has to be crossed and more fundamental changes are necessary that are likely incompatible with the book you are reading and how it intends to develop more complex concepts proceed at your own ris... uh oooh here it coo...

....oooomes. Whoa, what a bumpy ride! Everybody still on board? Hey, where's the... hmmm looks like that Register class went missing. Whoops! But no worries I'm sure we can come up with a new one.

My expectation from a cash register is to do one main operation on it: I tell it the price to pay, the amount of money given and it will tell me how much change should be given. That would be a method then that I call pay which has the following signature:

double pay (double price, double payment)

I can do this all over again with different values for the next customer in the queue. The values change whenever I interact with the register. The only thing that stays constant is the tax. This means that only tax should be a member of the class, because it persists throughout multiple method calls. The rest of the information comes in as parameter values.

Here's how that looks:

public class Register
{
    private final double tax;

    public Register()
    {
        this(0.0);
    }

    public Register(double tax)
    {
        this.tax = 1 + tax/100;
    }

    public double pay(double price, double payment)
    {
        return payment - price * tax;
    }

    public static void main (String[] args)
    {
        Register register = new Register(10);

        double change = register.pay(100, 200);
        System.out.println(change);
    }
}

I got lazy and added main to Register. I find myself doing that a lot to create a small executable example program for a specific class contained in that class. In some sense, this is not just self documenting code, but executable documentation. Of course having a separate class is the better choice for more sophisticated testing (unit tests etc.).

tax calculation

  tell them the amount the actual tax is

I guess you are referring to that method:

public double getTotalTax()
{
    return (purchase*0.10);
}

The problem with that is that it performs a calculation with a fixed tax factor. If the number passed to the Register is a different tax, this number would be wrong.

To add this method to the new class, it needs to receive the price as a parameter, because purchase is not a member of the class any more.
An advantage is that the tax can be calculated, without making a purchase.

public double calculateTax(double price)
{
    return price * (tax - 1);
}

As tax is a factor > 1, 1 has to be subtracted. Wait!, now this calculation has to be done over and over again. Isn't that bad? Yes, but I suspect that calculating the tax happens a lot less often. If need be, this factor could also be stored in a variable of the class.

purchase counting

I would not add up all purchases in the register itself. In programming, if you have many of something, there's often a way to "hold" many things. In general these are called data structures and come in a variety of flavours from simple arrays (that String[] args is one such example) to generic collections.

If somebody wants to purchase many items, they come with such an array for example. Both in real life and online stores, people shop around filling a shopping basket and throw that at the cashier when they are finished. (some roll it, but throwing is most common)

Now imagine your shopping basket is held by the cashier all the time and whenever you want to add or remove something, you have to go to that guy to do it for you. Give him a break, fill your basket yourself.

Here's how a method taking many prices could look like:

public double pay(double price, double payment)
{
    return payment - price * tax;
}

public double pay(double[] prices, double payment)
{
    double total = 0;

    for (double price : prices)
        total += price;

    return pay(total, payment);
}

You can do this with more bling bling in Java 8, but the more important thing to take away is calling the other method to do the calculation there, to keep it in one place and not duplicate it.

I'd say that's it, but guess who turns up with even more stuff when you think "that's it"? Yes, it's

the god d*** store manager

Yeah, it's your third day here and he's already complaining. One problematic thing is that his requests are not very good:

  Modify the CashRegister class

I wouldn't do that. The Register class is working fine. Never touch a running system. There are two better approaches to this:

Create a subclass CountingRegister extends Register, do the counting in the overridden pay methods.
Create a decorator/wrapper for the Register class that does the counting in its pay methods before delegating them to it's decoratee/wrappee1.

You haven't heard about inheritance, composition or patterns yet, but this is how I would do it.

Full example code:

public class Register
{
    private final double tax;

    public Register()
    {
        this(0.0);
    }

    public Register(double tax)
    {
        this.tax = 1 + tax/100;
    }

    public double pay(double price, double payment)
    {
        return payment - price * tax;
    }

    public double pay(double[] prices, double payment)
    {
        double total = 0;

        for (double price : prices)
            total += price;

        return pay(total, payment);
    }

    public double calculateTax(double price)
    {
        return price * (tax - 1);
    }

    public static void main (String[] args)
    {
        Register register = new Register(10);
        double change;

        change = register.pay(100, 200);
        System.out.println(change);

        double[] prices = new double[]{25, 4, 39};
        change = register.pay(prices, 200);
        System.out.println(change);

        System.out.println("tax for 100 " + register.calculateTax(100));
    }
}

1 the thing that's decorated/wrapped, like employer - employee.


To be frank, I don't really know why you need such methods to print out individual characters, I'll just make my suggestions based on what you have...

Your class name anycode should be in PascalCase.
Your method names should be in camelCase.
Eclipse tells me that the assignments int digit = 0; in print_digits3 and print_digits2 are not used.
You have this comment: // type recasting to int is a must, it does not work without it - no idea why - that's because when you divide an int with a double, the result will be double type but you are assigning that to an int value. Therefore, you are required to cast the double into an int first for the assignment to be correct.
Recommended to use Integer.valueOf() instead of new Integer().

Not sure what's your aversion to using the char[] way of doing the same task, but here's a suggested approach anyways for comparison (to your print_digits4 method):

private static void printDigits( int num ) {
    for ( char c : String.valueOf( num ).toCharArray() ) {
        System.out.println( c );
    }
}


Random walker using Processing.JS on Khan Academy, with new walkers generated on mouse click

I would put noStroke in a different location.

You are trying to make this code more efficient. You call noStroke each time one of these guys is called. You really only need to call it once right? So change the state once in your draw function:

draw = function() {
    noStroke();
    for(var i = 0; i < walkers.length; i++) {
        walkers[i].walk().display();
    }
};

And remove it from your Walker.display function:

Walker.prototype.display = function() {
    fill(this.r, this.g, this.b, 20);
    ellipse(this.x, this.y, this.radius, this.radius);
    return this;
};


The basic method you're using seems to me rather roundabout. If you're going to write a loop to walk through the collection anyway, why not just check for the correct criteria there? e.g., something like this:

Integer diff = nums[1] - nums[0];

for (int i=2; i<nums.length; i++)
    if (nums[i] - nums[i-1] != diff)
        return false;
return true;

This can save quite a bit of work, and (especially if the numbers don't form an arithmetic sequence) may save a fair amount of storage as well. More importantly, it makes the intent immediately obvious, which (it seems to me) that inserting all the differences into a hash table doesn't.

One other specific detail of your code bothers me:

if(result.size() > 1)
    return false;
return true;

Anything of the form if (x) return true; else return false; can be expressed as return x;. In your case, the sense is reversed, so it can be return !x;, so you just want return result.size() == 1; (but, as noted above, I'd rather eliminate this entirely).

If you really want to use the approach you've taken, I think it becomes a lot more reasonable if you take your loop and wrap it up into a generic algorithm. I'd probably call it adjacentDifference. Then you end up with something on this general order:

Set<Integer> result = new HashSet<Integer>();

Collections.sort(Arrays.asList(nums));
Algorithms.adjacentDifference(nums, result);
return result.size() == 1;

That's simple and neat enough that as long as you're sure this is outside the critical path (i.e., the extra time and space used don't matter) it would at least be worth considering.


Creating a loading sequence of an application

Do you think there is a nicer way how to express this without any external dependency?

Use Babel preset to only include browsers from the last two years. In that case, the promise polyfill is not needed. For example

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["since 2016"]
      }
    }]
  ]
}

  Additionally, I would like to DRY up the lines with require.ensure. I am not entirely sure how this works, but is there some way how to specify name of loaded file dynamically, perhaps using context?

Use a wrapper function to pass the strings as arguments:

return setupRenderer((resolve) => { ensurance('./infosite', 'infosite')});

And define the function before the call:

function ensurance(path, name){
  require.ensure([path], (require) => resolve(require(path)), name);
}

References

Babel: env preset
caniuse: promises


What would you have done differently? How to approach this?

You are already using iteration, by using a for-loop to iterate over the characters in text.
However, programming is about automating tasks. So thinking like a programmer means finding ways to let the computer do things for you, so you don't have to. For example, instead of creating the dict alphabet by hand, which means typing out all 26 characters and their index, you can let the program do this for you, by making use of the chr() and ord() functions, which convert characters to ASCII values and back, respectively:
alphabet = {}
for i in range(26):
    alphabet[chr(ord('a') + i)] = i + 1

But you can write that more compactly using dict comprehension:
alphabet = {chr(ord('a') + i): i + 1 for i in range(26)}

And now you should realize that you actually don't need alphabet, but can convert the characters in text immediately into indices:
mylist = [ord(letter) - ord('a') + 1 for letter in text]

And if you want you can just replace the whole function with:
def alphabet_position(text):
    return ' '.join([ord(letter) - ord('a') + 1 for letter in text])

However, if you feel more comfortable using for-loops, then by all means keep using those. It also helps if you create a function that converts a single letter to an index; this breaks up your code into simpler chunks that are more easy to reason about:
def alphabet_position_of_letter(letter):
    return ord(character) - ord('a') + 1

def alphabet_position(text):
    positions = [alphabet_position_of_letter(letter) for letter in text]
    return ' '.join(positions)

The above is a bit more verbose, but now the function and variable names help describe what everything means.


SQL Group and Filter - Refining down a search including Dates

Overall, that looks good. You've followed basic SQL styling rules, capitalising keywords for example, and the both queries are consistent. Anyone looking at that is going to struggle to find things to complain about.

A couple little things, the first AS in your second query isn't capitalised. I would change it to AS to make the query more consistent.

I'd say that the table aliases in the second query should be more meaningful than just a and p. Other than that, good job.

I would recommend using the first query, it avoids the join and, presumably, returns the same correct results.


Greasemonkey script for filtering out results from experteer.com

If you want to maximize the speed, to iterate big arrays, use

for (var i = 0, l = array.length; i < l; i++)

instead of

for (var i = 0; i < array.length; i++)

Moreover, if you want to get the elements of a class, there's no need to use querySelectorAll, you can use the faster getElementsByClassName (see benchmark)


Is it ok to add a static method to the IEqualityComparer implementation?

The AreEqual() does not do what one would expect.

As you have implemented the method, you say null != null.
GetHashCode()
You should consider replacing the tenary with a simple if statement. IMHO you would gain in readability.

public override int GetHashCode(byte[] array)
{
    unchecked
    {
        if (array == null) { return 0; }

        return array.Aggregate(17, (current, element) => current * 31 + element.GetHashCode());
    }
}

using a static method here, won't do any harm IMHO.


Basic Subnet Mask Calculator + A Little Extra

Here are some things that may help you improve your program.

Prefer const to #define

For constants such as TOTAL_BITS, it's generally better to use a named const value rather than a #define.  The primary reason is that the const definition enforces type checking, while the macro does not.  However, see the next suggestion.

Use sizeof for portability

The code currently contains these lines:

#define TOTAL_BITS 32
#define N_OCTETS ((TOTAL_BITS / 8))

typedef uint32_t BitField;

However, I think I'd define everything instead as const values all derived from the type.  That is, I'd suggest this:

typedef uint32_t BitField;
const int BitFieldOctets = sizeof(BitField);
const int BitFieldBits = 8 * BitFieldOctets;

Think carefully about signed vs. unsigned

If generateSubnetMask is passed a negative number, what should it do?  I'd suggest that the passed number should be unsigned instead of int and that the value could be checked to make sure it does not exceed the naximum number of bits.

Be careful when shifting negative values

By default, constants are int, so this code:

return ~0 << nHostBits;

Should probably instead be written like this:

return ~0u << nHostBits;

Avoid pointless recalculations

The code has this function:

void printOctets(BitField maskAddress) {
    for (int octetN = BitFieldOctets - 1; octetN >= 0; octetN--) {
        BitField mask = generateOctetMask(octetN);
        printf("%d", (maskAddress & mask) >> (octetN * 8));

        if (octetN > 0) {
            printf(".");
        }
    }
}

This is more complex than it needs to be.  First, the mask can be generated just once for the high byte and then shifted, eliminating a number of calculations that don't need to be done:

void printOctets(BitField maskAddress) {
    BitField mask = generateOctetMask(BitFieldOctets - 1);
    for (unsigned i=BitFieldOctets; i; --i) {
        printf("%d", (maskAddress & mask) >> (BitFieldBits - 8));
        maskAddress <<= 8;
        if (i != 1) {
            printf(".");
        }
    }
}

This works by keeping the mask in place over the most significant byte and then shifting the address to the left each iteration.  An alternative would be to use a union as the BitField type to allow access to each byte very simply.  That approach, however, requires that you account for the endian-ness of your machine, which this code does not.

Consider restructuring for simplicity and clarity

The printBinary code is currently like this:

void printBinary(BitField n) {
    bool areDropping = true;  // So we can drop leading 0s.

    for (BitField mask = 1u << 31; mask > 0; mask >>= 1) {
        bool isSet = n & mask;

        if (isSet) {
            areDropping = false;
            printf("1");

        } else if (!areDropping) {
            printf("0");
        }
    }
}

Instead, I'd break this into two different loops: the first to skip leading zeroes and the second to actually print the bits.  Here's one way to do that:

void printBinary(BitField n) {
    BitField mask = 1u << (BitFieldBits - 1);
    // skip leading zeroes
    for (; mask && !(mask & n); mask >>= 1);
    // print all other bits
    for (; mask; mask >>= 1) {
        putchar(n & mask ? '1' : '0');
    }
}

Note that here I'm using the named constants rather than the "magic number" 31.


Finding words of a given length only using given letters

The following code shows I would have done what you asked in Python 2.7. Other readers will tell you the ways in which it is a) not Pythonic and b) wrong.

Start with a module comment describing what the code is intended to do. (This is available to the code as __doc__.)
Use the various Python string delimiters to avoid escaping.
Name variables consistently.
strip() text strings read from a text file.
Make letters a set to reflect its usage.
Create the list of matching words with a list comprehension.

Here is the code.

"""
    Find all the words in a reference dictionary with a specified number of letters
    that contain all the letters in a specified list of letters.

    The number of letters and the list of letters must be specified on the command line.

    The reference dictionary may be specified on the command line. If is not then
    dict.txt is used.

    The matching of letters is case-insensitive.
"""
import sys

if len(sys.argv) < 3:
    print >> sys.stderr, __doc__
    sys.exit('Usage: %s letters number_of_letters [dictionary_file]' % sys.argv[0])

letters = set(sys.argv[1].upper())
wordsize = int(sys.argv[2])
dictname = 'dict.txt' if len(sys.argv) <= 3 else sys.argv[3]

try:
    wordlist = [w.strip() for w in open(dictname).readlines()]
except IOError:
    sys.exit('''Couldn't find dictionary file "%s"''' % dictname)

matches = [w for w in wordlist
             if len(w) == wordsize
                and all(c in letters for c in w.upper())]

print 'Found %d results:' % len(matches)
print matches


It's hard to analyze without the whole context, but a possible workaround could be to add the whole keys in a collection, and apply a filter like _.some of underscore.js.

var aColection = [this.Config.Ranks, this.Config.Message,..]
_.some(aCollection, function (element) {
  return this.Config[key] === element
})

If you don't want add this library to your core code, you can simply copy  the definition of some.

GitHub


Don't include root directory in HTML tree

Let's separate it by responsibilities into renderKids, renderName, traverseTree so that:

the main function can start explicitly from where you want
functions become immutable, free of side-effects
less repeated code
a single return is used
hopefully, the intent and flow become more obvious

function renderTree(json) {

  function renderKids(kids) {
    const ul = document.createElement('ul');
    for (const kid of kids) {
      ul.appendChild(traverseTree(kid))
    }
    return ul;
  }

  function renderName(name) {
    const span = document.createElement('span');
    span.textContent = name;
    return span;
  }

  function traverseTree(node) {
    const li = document.createElement('li');
    if (node.kids) {
      li.appendChild(renderName(node.name));
      li.appendChild(renderKids(node.kids));
    } else {
      li.textContent = node.name;
    }
    return li;
  }

  return renderKids(json.kids || []);
}

Usage: const output = renderTree(await readJson('./tree.json'))

Note, traverseTree is not asynchronous so there's no need for async keyword.


ms.Close(); //close the MemoryStream when done

It's a good thing that you close the ms (MemoryStream) but there are two more to dispose.

The bitmap and graphics instances also need to be disposed/closed. The same applies to the NetworkStream but I got the impression that you don't know the using statement that allows you to automatically handle resources so:

NetworkStream stream = getSelectedClient().GetStream();
..
stream.Close();

would become:

using(var networkStream = getSelectedClient().GetStream())
{
    ..
} // at this point it will be closed/disposed by the runtime

The benefit of this is that it will be correctly disposed even if an exception occurs. Without it you would need to write the try/finally yourself (what a using actually does for you (or rahter the compiler))

NetworkStream networkStream = null;

try
{
    networkStream = getSelectedClient().GetStream();
    ..
}
finally
{
    networkStream?.Close();
}

You can use the same pattern for bitmaps, graphics and anything else that is IDisposable.


Find the non repeating number in the integer array

If the array is sorted you do not need hashmaps to achieve O(n). If you have a random/unsorted array you can use hashmaps to achieve the purpose, see Paulo's answer for that. Note that sorting requires O(n log(n)).

If you want to know how often each integer is in the original collection you will also need hashmaps, but if you only want to know a nonduplicate number in a sorted array the following code will work:

// N is the number of ints in sorted
int nonduplicate(int sorted[], const int N){
    //To prevent segfaulting when N=1
    if(N==1){ return sorted[0]; };

    for(int i=0;i < N-1;i++){
        if(sorted[i] == sorted[i+1]){
            // Next number in collection is the same so the current number is not unique
            // Set i to the first location of the next different number
            do{
                i++;
            }while(i < N-1 && sorted[i] == sorted[i+1]);
        }else{
            // The next number is different so the current is unique
            return sorted[i];
        }
    }
    // Is the last number unique?
    if(sorted[N-1] != sorted[N-2]){
        return sorted[N-1];
    }
    // No unique numbers
    return -1;    // Or some other value you reserve for it
}

Note that this code is faster because it doesn't have the overhead of a hashmap and may stop before traversing the whole array, but does have the same big-O limit.


Notes
I gave it a shot, there isn't really much that I felt could be improved upon though. I'm sure performance would be better if you were using CSS3 transitions (the implementation certainly would be nicer <3 CSS3) but I assume you wanted better browser coverage.

Ideally put your CSS in a separate file to keep your markup clean.

I put a function around your code so that the symbols can be properly minified.

I introduced a menuVisible variable which will be false if the menu is not showing and not in transition. The reason I did this was to simplify the conditions on scroll, resize and button click events that run every time.

Fluent syntax for $(window) when hooking up events, saves converting window into a jQuery object twice.

Refactored a little so the functions are better split up and to clean up document ready.

Something I noticed when playing with your menu from the link you gave, it's actually not very smooth at all on my desktop if the menu is transitioning at the same time as your slideshow. I suggest you halt the animation on your slideshow when the button is pressed, that will probably make the biggest difference to how smooth the page is.
Alternatively you could disable the slideshow all together or remove the animation when it's in the mobile media query, scrolling may suffer as a result of the slideshow animation as well.

Code
HTML

    content Goes Here

CSS
#mobNav {
    background: url(images/top_bg.jpg) repeat;
    background-size: 100%;
    position:absolute;
    left:-200px;
    width:200px;
    height:100%;
}

JS
(function ($, window, document) {
    var mobNav, mainNav, top, shift;
    var menuVisible = false;

    $(document).ready(function($) {
        mobNav      = $("#mobNav");
        mainNav     = $("#mainnav");
        top         = $("#top");
        shift       = $("#shift");

        mobNav.html(mainNav.html());

        $(window).on("scroll", scroll);
                 .on("resize", hideMenu);
        $("#mob_nav_trigger").click(function(e) {
            e.preventDefault();
            showMenu();
        });
    });

    function scroll() {
        if ($(window).scrollTop() > 300)
            top.fadeIn();
        else
            top.fadeOut();
        hideMenu();
    }

    function showMenu() {
        var winWidth = $(window).width(),
            docHeight = $(document).height();
        mobNav.css("minHeight", docHeight)
              .addClass("visible_now")
              .animate({
                  left: menuVisible ? -mobNav.outerWidth() : 0 },
                  function () {
                      if (menuVisible)
                          menuVisible = false;
              });
        shift.css("minWidth", winWidth)
             .animate({ marginLeft: menuVisible ? 0 : 200 });
        if (!menuVisible)
            menuVisible = true;
    }

    function hideMenu() {
        if (menuVisible) {
            mobNav.css("left", -mobNav.outerWidth());
            shift.css("margin-left", "0");
            menuVisible = false;
        }
    }
})($, window, document);


Given an array of Strings, return the number of sets of anagrams

Bug

I fed "aad" and "abc" to your program, and it considered the two strings anagrams of each other.  The problem is that you are trying to use a hashcode to determine whether two strings are anagrams of each other.  However:

Your hashcode is not very good because it simply adds the characters of the string together.  Therefore "aad" and "abc" were considered equivalent.
No matter what, a 32 bit hashcode is going to have some problems because there are more than 2^32 different anagram possibilities if you use long enough strings.  Even a 64 bit hashcode would not be enough.

I suggest that you think about creating a sorted string (i.e. alphabetized) as your hash key instead of a numerical hashcode.

Simplification

This code:

       if (mapList != null && mapList.get(hashcode) == null) {
            List<String> list = new ArrayList<String>();
            mapList.put(hashcode, list);
            list.add(arr[i]);
        } else {
            List<String> list = mapList.get(hashcode);
            list.add(arr[i]);
        }

could be simplified to:

        List<String> list = mapList.get(hashcode);

        if (list == null) {
            list = new ArrayList<String>();
            mapList.put(hashcode, list);
        }
        list.add(arr[i]);


Having 3 parallel 2D arrays in javascript for simple data is a bit overkill. Put those in a single 2D array or you can fold it into the grid's nodes.

If you want step by step visualization then you'll need to break up your function into sections: init, step and finalize.

init is everything before the main while loop.

step is the while loop body

finalize is only triggered when the loop otherwise breaks or exits.

Whether you group all the data it needs (like pqueue, dist, etc.) into an object that gets passed in or become globals doesn't really matter when it's for educational reasons. But if they are in a single object then it's easier for the visualizer to get that as well.


Sorting an array of objects by a property which may be missing

Here's a single-pass example. Very similar to @janos' code (which has a good complexity analysis). The only difference is in how various cases with undefined are treated.

function sort(searchResult) {
  return searchResult.sort((tc1, tc2) => {

    const tc1RefUndefined = tc1.reference == null;
    const tc2RefUndefined = tc2.reference == null;
    if (tc1RefUndefined || tc2RefUndefined) {
      if (tc1RefUndefined && tc2RefUndefined) {
        return 0;

        // or if consistency in grouping (within the groups) is necessary:
        // return tc1.otherProperty comparedTo tc2.otherProperty
      } else if (tc1RefUndefined) {
        return -1;
      } else {
        return 1;
      }
    }

    return tc1.reference.localeCompare(tc2.reference);
  });
}


Linked List in Java (Garbage Collection)

Yes, in theory.  That depends on when the garbage collector decides to run.  (There are lots of great explanations about how finicky it is on Stack Overflow.)  But it will become eligible for garbage collection and is gone for all intents and purposes.  Data becomes eligible for garbage collection when no references to it exist, and, assuming node_at(length-1).next is the only reference to it, the Node then qualifies once you change that reference.


Bash to find all placeholder variables in a file and replace will real variables

First up, the shell variable USER is already defined in bash, and is the log-in name of the current user.... so, if you log in as 'rolfl' then echo $USER will print rolfl. There are a number of programs and other systems that may be confused if you change the USER environment variable the way you have.

Next, I don't think that the symbolic link you create does what you think it does:

ln -s /home/log.conf $FILE

This will try to create a symbolic link at /home/logging/log.conf that points to the (presumably pre-existing) file /home/log.conf

This means that whenever anyone processes your settings script, they all modify the same file /home/log.conf and, since the first person will replace the tokens with their name, the other users will have nothing to do....

I presume the line:

ln -s /home/log.conf $FILE

should be

cp /home/log.conf $FILE

Apart from this though, the program seems reasonable (I have not run it). My only comment is that this uses relatively advanced features of the shell. In my experience, it is often better to write these things in perl because people expect perl to do more complicated things. I don't know if this is sounding right, but, even though perl may be slower than this solution, it is also something that sys admins are familiar with, and will be happier to maintain than a complex shell script.... Still, if the people maintaining this code are familiar with what you are doing (and the fact that you are asking on CodeReview rather than using your peers is a suggestion that is not the case) then I would say it is fine.


Dijkstra algorithm implementation with adjacency list

Advice 1

int n = adj.size();

I would change int to size_t, since it counts size that may not be negative.

Advice 2

for (int j = 0; j < n - 1; ++j) {
    ...
}

I would change it to

while (!candidates.empty()) {

}

This omits some unnecessary computation in case the graph is disconnected.

Advice 3

candidates may be renamed to open, open_list or frontier; that is more or less conventional naming for that data structure in pathfinding community.

Advice 4

I would change typedef std::vector<std::vector<int>> Weights; to typedef std::unordered_map<int, std::unordered_map<int, size_t>> Weights;. This makes filling the edge weights much more easier; especially on sparse graphs:

w[a][b1] = 3;
w[a][b2] = 1;
...

Advice 5

if (!visited[neighbor] && (dist[next] + weights[next][neighbor] < dist[neighbor])) {
    ...
}

This condition is a bug. It should be

if (dist[neighbor] == INT_MAX || (dist[next] + weights[next][neighbor] < dist[neighbor])) {
    ...
}

(Note dist[neighbor] == INT_MAX and || instead of &&. You can try changing || to && and see its effect here.)


Army strength based on level and modifiers

Here's one way to do it:

from random import randint

def n_gen_army(level, strength, weakness, params=dict_of_dicts):
    """Returns random floats according to ranges specified by params."""
    if strength:
        key = 'strength'
    if weakness:
        key = 'weakness'
    else:
        key = 'default'

    lower_bound, upper_bound = params[key][level]

    return round(randint(lower_bound, upper_bound), 4)

weakness_dict = {
                0: (1000, 5000),
                1: (10000, 50000),
                2: (50000, 75000),
                3: (100000, 200000),
                4: (200000, 500000),
                }

strength_dict = {
                0: (10000, 25000),
                1: (50000, 100000),
                2: (100000, 300000),
                3: (100000, 300000),
                4: (800000, 1100000),
                }

default_dict = {
               0: (5000, 10000),
               1: (25000, 50000),
               2: (75000, 150000),
               3: (150000, 250000),
               4: (300000, 900000),
               }

dict_of_dicts = {'weakness': weakness_dict,
                 'strength': strength_dict,
                 'default': default_dict
                }

>>> n_gen_army(2, 0, 0)
115061.0

Some other notes:

In your original code, if strength and weakness are both 1, then only the setting for weakness matters.  My code preserves that, but is that behavior really what is intended?  Or did you want elif instead of your second top-level if?
Why are you using round?  Do you really want floats returned instead of integers?  If you want integers, don't use round.  If you want integers rounded to the nearest 10 or 100, why not generate random integers in a 10-fold (or 100-fold) reduced range and then multiply be 10 (or 100)?
Avoid capitalization in function names if you can.  PEP8 and all that.  All-lowercase (for functions) is good python style.
You're only using one function from random, so from random import randint is better than loading in the whole module with import random.
You seem to be using weakness and strength as boolean variables so if weakness: is better than if weakness == 1.


explode and implode are faster (according to PHP's man page for preg_split), and more readable IMO.

$la_jobrole = explode(' ', $lo_designer->role);
$ls_jobPrimary = array_shift($la_jobrole); // Get the first item from the array
$ls_jobSecondary = implode(' ', $la_jobrole); // Glue the remaining pieces back together

Personally I would avoid using either list or preg_replace in this case. They're slower and harder to read, and I would certainly avoid that looping thing.


Getting cars and bicycles from a database and writing them into two different arrays

As far as I see the only difference is the type inside the SQL query. So why not pass that as parameter.

You could also think of creating additional classes for car and bicycle which call the getTop method of another class with the right parameters or if you extend the vehicle class set the corresponding type inside the constructor. Just to give you some more examples what you might be able to do or at least consider.

The following code is probably one of the easiest way to accomplish the DRY principle. But be aware that it's untested code.

class TopVehicles extends Connection {
    private $sql = 'SELECT model, price FROM vehicles WHERE type = ? ORDER BY price DESC limit 10';

    function __construct() {
        parent::__construct();
    }

    public function getTop($type) {
        $stmt = $this->mysqli->prepare($this->sql);
        $stmt->bind_param("s", $type);
        $stmt->execute();
        $stmt->store_result();
        $row_cnt = $stmt->num_rows;
        $stmt->bind_result($model, $price);

        while ( $stmt->fetch() ) {
            $_result[] =
            array(
                'Model' => $model,
                'Price' => $price
                );
        }

        $stmt->free_result();
        $stmt->close();
        return $_result;
    }

$obj = new TopVehicles(); // should be TopVehicles, shouldn't it?
$_TopCars = $obj->getTop('car');
$_TopVehicles = $obj->getTop('bicycle');

UPDATE: Without seeing the final code a code review is rather hard. It's true that you can't bind column names in a prepared statement. But what you could do is to manipulate the SQL string first. So here is a way how to accomplish that:

private $sql = 'SELECT %s FROM %s WHERE type = ? ORDER BY %s limit ?';

public function getTop($table, array $columns, array $orderByColumns, $type, $amount) {
    $sql = sprintf($this->sql, implode($columns, ', '), $table, implode($orderByColumns, ', '));
    $stmt = $this->mysqli->prepare($sql);
    $stmt->bind_param("si", $type, $amount);
    ...

$_TopCars = $obj->getTop('vehicles', array('model', 'price'), array('price DESC', 'model ASC'), 'car', 10);

Note: This snippet is again untested and there is enough room for improvement, but it should provide you with an idea on how you could do it. But make sure that you don't add SQL Injection vulnerabilities by using user input directly. This snippet contains also @Alex L's suggestion to pass the amount as parameter, too.

Note: Your class names also indicate that your code violates the http://en.wikipedia.org/wiki/Liskov_substitution_principle. TopVehicles are no Connection. I'd say it's better to dependency inject the connection.

class TopVehicles {
    private $mysqli;
    private $sql = 'SELECT model, price FROM vehicles WHERE type = ? ORDER BY price DESC limit 10';

    function __construct($mysqli) {
        $this->mysqli = $mysqli;
    }
    ...
}


you have a nice, correct program here!
...please see what I made of it with little scope on "fewer lines" and little "performance" and of course some Java8 tweaks:

import java.util.LinkedList;//why always Array-Array?(especially for 2 - 20 entries)
import java.util.List;
import java.util.Scanner;

public class Solution {//adjusted class name for code upload

  public static void main(String[] args) {
    readInput()// don't need the variable, but same call as in original program
    .stream().forEach(//just as a showcase for streams and lambda but no real improvement
      /*TestCase*/ t -> {System.out.println(t.outcome);}
    );
  }

  private static List<TestCase> readInput() {//no changes, except the return (list) type
    final List<TestCase> testCases = new LinkedList<>();//"final" becuase it is..., LinkedList: no(0) initial capacity
    try (Scanner k = new Scanner(System.in)) {//try with ressources {@link: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html}
        int numTestCases = Integer.valueOf(k.nextLine());//original code
        for (int i = 0; i < numTestCases; i++) {//...
            testCases.add(//...
               new TestCase(//new "TestCase" with ...
                   k.nextLine(),//the next line <- blocks
                   k.nextLine() //..and the next line <-blocks
               )
            );
        }
    }
    return testCases;
  }

  private static class TestCase {//This is "nicer" to read/understand than nested lists
    //we don't really need these (they could also be local constructor variables):
    private final int students;
    private final int minAttendees;
    private final int[] arrivals;//(I) prefer arrays>list, when knowing the size in advance and size < 65536 (2^16)
    //we only need this:
    final String outcome;

    private TestCase(String courseData, String studsData) {
         /*This is the "power" but also "the weakness" of this approach:
         It does everything (possible) in one loop/line/routine -
         it saves lines of code (and maybe little exec. time)!
         But it is less flexible, and for big routines
          (many students, and maybe not "keyboard scanner")
         this would definitely be a bottleneck.*/
        String[] tmp = courseData.split(" ");//according to original code, reuse of String[] variable
        students = Integer.valueOf(tmp[0]);//according to original code/input format
        minAttendees = Integer.valueOf(tmp[1]);//...
        tmp = studsData.split(" ");//...
        arrivals = new int[students];//..initialize...
        int attendees = 0;//...
        for (int i = 0; i < students; i++) {//only one loop...
            arrivals[i] = Integer.valueOf(tmp[i]);//...copying...
            if (arrivals[i] <= 0) {//...evaluating...
                attendees++;
            }
        }
        outcome = attendees < minAttendees ? "YES" : "NO";//..and finally aggregating
    }
  }
}


Ruby script to send PragPub magazine to Kindle

For the first snippet there is no much room for improvement, but you can use File.write:

begin
  content = open(url).read
  File.write(filepath, content)
rescue OpenURI::HTTPError => e
  abort "Unable to download #{url}: #{e.to_s}"
end

For the options parsing part, I'd definitely recommend something better than optparse, for example https://github.com/jashmenn/trollop/


Functions

Everything is in one function. You should stick to the single responsibility principle. Basically, a function should have one job.

In a way, that does mean your whole game should be in the function, but it'd be better to have parts of it separated out. For example, getting an int from the user could be a function:

def get_int(message)
    return int(input(message))

lives = get_int("How many lives would you like? ")
max_value = get_int("Please choose the largest number that can be generated: ")

Now this may seem unnecessary, but now you could add input validation. Caridorc pointed out a bug, so you should do error handling. The best way to do this in Python is to catch any ValueErrors that get thrown.

    try:
        return int(input(message))
    except ValueError:
        print("Please enter an integer only")

Now the code wont crash when an invalid string is entered, but it also wont return a value. So you want to loop over this with while until a valid number is entered and returned, ending your loop. This is how it would look:

def get_int(message)
    while True:
        try:
            return int(input(message))
        except ValueError:
            print("Please enter an integer only")

Now you have error handling set up, but you can still use one line to get each value:

lives = get_int("How many lives would you like? ")
max_value = get_int("Please choose the largest number that can be generated: ")

Pythonic style

While we're on while, there's a more Pythonic way to do your main game loop. Instead of using replay, just use another infinite loop with while True and end your loop with a break, like this:

if replay != 1:
    print("Thank you for playing. See you next time")
    break

Also you don't need brackets around the condition, Python looks nicer without them and evaluates it just fine.

Instead of using

num_of_guesses = num_of_guesses + 1

use Python's += operator:

num_of_guesses += 1

In fact, instead of that at all, you could just use a for loop instead of a while loop here:

for num_of_guesses in range(1, lives + 1):
    guess = get_int("Please enter your guess: ")
    if guess == random:
        print("Good guess, that is correct! You got the right answer on guess number", num_of_guesses, ", well done!\n")
        break  #if answer is correct this will exit the while loop
    else:
        print("Unlucky, that guess was incorrect. You have", (lives - num_of_guesses), "lives remaining.\n")
if num_of_guesses > lives:
    print("You have run out of guesses. The correct answer was:", random)

range lets you just loop over a list of numbers. In this case, it loops from one up to lives. Range will iterate up to but not include the second parameter, which means if you pass lives + 1 the last loop will be on the value of lives.

You could also make use of Python's else clause for for loops. An else after a for loop in Python will be executed if the loop fully runs it's course without reaching a break command. If break gets called then the else block is skipped. This works perfect for your case, so I'd write it like this:

for num_of_guesses in range(1, lives + 1):
    guess = get_int("Please enter your guess: ")
    if guess == random:
        print("Good guess, that is correct! You got the right answer on guess number", num_of_guesses, ", well done!\n")
        break  #if answer is correct this will exit the while loop
    else:
        print("Unlucky, that guess was incorrect. You have", (lives - num_of_guesses), "lives remaining.\n")
else:
    print("You have run out of guesses. The correct answer was:", random)

Readability

You have good names here. They're clear and readable, without being too long or overlapping. Although, I would advise against using random as a variable name. It doesn't cause a clash here since you used from random import randint, but it causes mild confusion. Something like answer would actually be more useful for indicating what the number is for.

However you have a lot of comments that don't need to be here. For example:

        break  #if answer is correct this will exit the while loop

This is quite a verbose comment. At most I would have # Correct answer. People reading this code probably know how break works. Your comments should focus on intent and abstract meaning. Python programmers can read your code and know what each part does, but why it does it, and what you want to do that for are useful to know in comment form. (as a beginner, perhaps you want to remind yourself of what these things do. This may be of benefit to start with, but I suggest reducing them as soon as you feel comfortable with it).


Python's standard library includes a class that would simplify your first snippet: collections.defaultdict. This class allows you to set a default for missing keys, so if you make it a list you can append without having to check if it already exists.

You could also simplify the iteration using zip; see e.g. "Iterate a list as pair (current, next) in Python".

Using that would make it:

from collections import defaultdict

def build_successors_table(tokens):
    table = defaultdict(list)
    for prev, word in zip(['.']+tokens, tokens):
        table[prev].append(word)
    return table

For the second snippet note that, per the style guide, all imports should happen at the start of your script - there's no benefit to trying to import random every time the function is called.

Continually appending strings is relatively inefficient, as a new string object is created each time. Instead, it's typical to create a list of words and then use ' '.join(words) to combine them back together.

It is more efficient to test membership (x in y) on a set (O(1)) than a list (O(n)).

import random

def construct_sent(word, table):
    words = []
    while word not in {'.', '!', '?'}:
        words.append(word)
        word = random.choice(table[word])
    return ' '.join(words) + word

Both functions would benefit from docstrings explaining what they do and how to use them (e.g. what the parameters are expected to be).