Refactoring a class hierarchy to remove subclasses

Edit: As David pointed out in the comments, I am completely wrong about constructors in the abstract classes. I hid the (ir)relevant section to avoid confusion and attempted to edit the rest of the post so it fit the new context. In case I missed something, Abstract classes CAN have constructors because they CAN'T be instantiated therefore any references to the init() method that may be left over should be assumed to be parent::__construct() instead. Thank you again David.

  Abstract classes can not, or rather should not, be instantiated. Therefore they should never have a constructor. If you want to have a shared "constructor" there are a couple different things you can do. The easiest method is to create an init()-like function and call that in your real constructors.  Another method is to extend an actual class. Since you don't seem to be trying to instantiate this class, as some who use "abstract constructors" are wont to do, then I think the first solution should be adequate, though I should add that the init() method should not be public to avoid "accidental" reinstantion.

    protected function init() {
        $this->_result = new ParserResult();
    }

Abstract classes are still classes. Therefore anything defined in it is still defined in its children. Thus, redefining properties should actually be handled in construction, because, if I'm remembering this correctly, redefining them in the children actually throws warnings. Either way, the better place is in construction.

public function __construct() {
    $this->_invalidSegmentMessage = 'Invalid GS segment: ';
    $this->_segmentRegex = "/^GS\*IN\*\w{2,15}\*\w{2,15}\*(\d{6}|\d{8})\*\d{4}\*\d{1,9}\*X\*\d{1,12}$/";

    parent::__construct();
}

So, there are a few principles being violated in your createSegmentObject() method. The first, and most obvious, is the "Don't Repeat Yourself" (DRY) principle. This can be observed by how similar all these methods are. If we take into account the Inversion of Control (IoC) Principle as well, then we can see that it is violating both of these principles. IoC is something I've never really thought about before, so I don't feel entirely comfortable explaining it. Google it if you're not sure what it is, I'll be reading up on it more myself after this post. I think you began to notice something was amiss, which is why you added it to the abstract class, you just didn't go quite far enough with it. The third principle, which is making this a little more difficult to see, is that this method also violates the Single Responsibility Principle. This method should be concerned with creating a segment, not creating AND setting. Leave that for after you call the method. If we try setting it immediately then we can't extend it.

//abstract class
protected function createSegmentObject( Segment $segment ) {
    $elements = explode('*', segment);

    $segment->setSupplierId( $elements[ self::SUPPLIER_ID_INDEX ] );
    $this->segment = $segment;
    $this->elements = $elements;
}

//extending class
protected function createSegmentObject( Segment $segment ) {
    parent::createSegmentObject( $segment );

    $this->segment->setGroupReference( $this->elements[ self::GROUP_HEADER_INDEX ] );
}

//usage
if ($this->isValidSegment()) {
    $this->createSegmentObject();
    $this->_result->setSegment( $this->segment );
}

In case you are curious, createSegmentObject( Segment $segment ) is assuming that your "segments" are using a common interface or abstract class and that it is called "Segment". If you are not using one of these, then I would seriously think about doing so. Assuming for now that you are, then we can declare the parent class as the common denominator and type hint our parameters for it. This will ensure that any object passed to the above method must be a type of Segment and will be able to produce the expected results every time, else PHP will throw errors.

So, we've just eliminated most of the need for multiple classes. The only thing holding us back are these unique properties and the occasional extensions. The interesting thing about these classes is that the properties are very structured and unique. So what do we do when we have a common data structure that needs to be saved and reused? If we create a database with each row denoting a segment and each field a property, then we can construct our segments by calling that specific row in the database. Of course, we should inject these parameters into our constructor to avoid our class becoming dependent. I'll leave the database implementation to you, but here's the constructor:

public function __construct( $id, $group, $type, $regex ) {
    $this->_supplierIdIndex = $id;
    $this->_groupHeaderIndex = $group;
    $this->_invalidSegmentMessage = "Invalid $type segment: ";
    $this->_segmentRegex = $regex;

    parent::_construct();
}

That leaves us with just extensions holding us back now. We could create an elaborate comparison table and pick and choose when to use what, or we can automate the process and use a factory pattern. Again, I'm going to leave this up to you, for multiple reasons, but the main one being that I haven't played with factories yet and wouldn't be sure where to begin. Besides, without the rest of the subclasses I couldn't begin.

I believe some of this is what Saul linked to, but I just skimmed over it. I did spy something about a factory in there, so maybe much of this is the same, but it lacked a lot of the explanations that I felt were necessary. Hopefully this helps.


Improvement to Luhn-Checksum Algorithm in Java

There is not much to improve in your code, it's compact and efficient. These are few suggestions:
Input validation
When the input number is negative the result is always true. To avoid confusion you can launch an exception.
public static boolean validate(int id) {
        if (id < 0) {
            throw new IllegalArgumentException("Input cannot be negative.");
        }
        // ..
}

Clarity
The Luhn Checksum algorithm is described very well on Wikipedia and by you on your question, but your implementation is not easy to follow. For example:
totalSum += id%10;

Here the last digit of id is added to totalSum. Adding a method (with the explanation of the operation in the name) makes it more readable:
totalSum += getRightMostDigit(id);

Same for:
id /= 10;

This operation removes the last digit of id, which can be changed to:
id = dropRightMostDigit(id);

I would also change the input variable name from id to number, but this is personal taste.
Perfomance
It's hard to improve performance and keep readability for your method. The only change I would suggest is to replace the getLuhn method with a static array.
This change makes it two times faster on my machine and gets rid of the additional method.
Code refactored
public static boolean validate(int number) {
    if (number < 0) {
        throw new IllegalArgumentException("Input cannot be negative.");
    }
    // Array containing:
    // - for index in [0,4]: the double of the index value
    // - for index in [5,9]: the sum of the digits of the doubled index value. E.g. index = 6 -> 6*2 = 12 -> 1+2 = 3
    int[] luhn = new int[] { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };

    int totalSum = 0;
    while (number > 0) {
        totalSum += getRightMostDigit(number);
        number = dropRightMostDigit(number);
        if (number > 0) {
            totalSum += luhn[getRightMostDigit(number)];
            number = dropRightMostDigit(number);
        }
    }
    return totalSum % 10 == 0;
}

private static int getRightMostDigit(int number) {
    return number % 10;
}

private static int dropRightMostDigit(int number) {
    return number / 10;
}

Personal opinion
Many implementations of the Luhn Checksum accept a String as input, so they can be used to validate credit cards or simply to operate on numbers bigger than an int. What is the use case of your algorithm?
The purpose of your implementation can also be included as a comment, it will help others to understand whether they need it or not.


Since ListItemCollection implements IEnumerable, but not IEnumerable<ListItem>, you have to use Cast before you can use other LINQ methods.

After you do that, you can use GroupBy, as Steve Michael suggested and then work with the result almost exactly like with your groups:

var categoryGroups = this.Items.Cast<ListItem>()
    .GroupBy(i => i.Attributes["category"]);

foreach (var categoryGroup in categoryGroups)
{
    RenderOptionGroupBeginTag(group.Key, writer);

    foreach (var item in group)
    {
        this.RenderListItem(item, writer);
    }

    RenderOptionGroupEndTag(writer);
}

Some other changes I made to the code:

I used foreach instead of ForEach(). ForEach() looks like a LINQ method, but it behaves very differently, since it doesn't do any querying. I think that in cases like this, foreach in the most suitable option.
Changing groups (and group) to categoryGroups means that the code is clearer and so you can get rid of the loop comment.
I also removed the other comments, because I think the code is clear about what it does. If you want to emphasize that RenderOptionGroupBeginTag creates <optgroup>, maybe you should rename it? Probably to something like RenderOptgroupBeginTag.


Predicate class implementation in TypeScript

As pointed out as a comment, I was unhappy about the extractCondition function.
This function handles, variables which do conform your Predicate<T> type. Which is fine, but I think this doesn't belong here.
Because a Predicate should have an accept or, if we talk about the Java implementation, test function.
This is not given when we can pass on any random function which do return a boolean. But does not conform our design of a Predicate.

Next naming, the PredicateBuilder seems okay-ish, but it feels wrong. As it isn't a builder in the classical sense.
Furthermore we have to work around functional interfaces, and this is I think the main pain point. To achieve this I would propose to rename the Predicate<T> interface, as it should be describing what a Predicate holds (a function which takes a parameter and returns a boolean). Therefore the name Predicate is available again and should be used instead of PredicateBuilder.

The repetition regarding and, or, etc... feels also some kind off. But I think that's because you always do extractCondition and other stuff (I've eliminated this in my suggestion, as the Java Predicate implementation does basically the same). Plus I've create a static method Predicate#of(...) to easier "get" a new Predicate. This reduces the mess a bit, but changing the operands is also still a bit clumsy, in my opinion.

Oh and btw. I've felt free to use arrow functions :-)

interface InternalPredicate<T> {
  (x: T) : boolean
}

class Predicate<T> {
  constructor(private condition: InternalPredicate<T>) {}

  public static of = <T>(condition: InternalPredicate<T>) => {
    return new Predicate(condition);
  }

  public and = (input: Predicate<T>): Predicate<T> =>
    Predicate.of((x: T) => this.apply(x) && input.apply(x));

  public or = (input: Predicate<T>): Predicate<T> =>
    Predicate.of((x: T) => this.apply(x) || input.apply(x));

  public not = (): Predicate<T> =>
    Predicate.of((x: T) => !this.apply(x));

  public apply = (x: T): boolean => this.condition(x);
}

Those are my two cents to the Predicate implementation, feel free to discuss them with me.

Alternative solution to eliminate the InternalPredicate and to support functions which are booleans:

type PredicateType<T> = (x: T) => boolean;

class Predicate<T> {
        constructor(private condition: PredicateType<T>) {}

        private static isInstance = <T>(input: Predicate<T> | PredicateType<T>): Predicate<T> => (input instanceof Predicate) ? input : Predicate.of(input);

        public static of = <T>(condition: PredicateType<T>) => new Predicate(condition);

        public and = (input: Predicate<T> | PredicateType<T>): Predicate<T> =>
          Predicate.of((x: T) => this.apply(x) && Predicate.isInstance(input).apply(x));

        public or = (input: Predicate<T> | PredicateType<T>): Predicate<T> =>
          Predicate.of((x: T) => this.apply(x) || Predicate.isInstance(input).apply(x));

        public not = (): Predicate<T> =>
          Predicate.of((x: T) => !this.apply(x));

        public apply = (x: T): boolean => this.condition(x);
}

It comes pretty close the the extractCondition approach, but the main difference here is, that a new instance is created if the input is a raw function. This adds up to be more robust to changes and being less error prone. Another advantage is, we don't care about how the predicate internally works, we're just in charge of returning a predicate based on the input. This clears up the use case of the function a bit more.

EDIT: As discussed in the comments, it is nicer to merge the private isInstance function into the static of function.


From what you have provided you can combine  the two queries into one. You should also consider removing constants like "1", 2, 4 with meaningful names.

var yourCondition = criteria.CorporateSummaryExpand == "1";
var data = from linq_row in trend_data.AsEnumerable()
           group linq_row by linq_row["questionnaire_uniquename"] into g
           where (criteria.CorporateSummaryExpand != "1") || (yourCondition  && g.First<DataRow>()["questionnaire_uniquename"].ToString() != "[Questionnaire].[Questionnaire].[Question].&[OFSP]&[OFSP5000]"
                   && g.First<DataRow>()["questionnaire_uniquename"].ToString() != "[Questionnaire].[Questionnaire].[Question].&[OFSP]&[OFSP5008]"
                   && g.First<DataRow>()["questionnaire_uniquename"].ToString() != "[Questionnaire].[Questionnaire].[Question].&[OFSP]&[OFSP1130]")
           select new
           {
                questionnaire_uniquename = g.First<DataRow>()["questionnaire_uniquename"].ToString(),
                question_name =yourCondition  ? g.First<DataRow>()["response_label"].ToString() : g.First<DataRow>()["question_name"].ToString(),
                question_score_type = g.First<DataRow>()["question_score_type"].ToString(),
                sparkline_data = g.Select(s => s["trend_score"].ToString()).ToArray()
           };
int rowspan = yourCondition ? 4 : 2;


I'm going to suggest something completely different to your current implementation... I'll dump the code first (see js fiddle) notice that the fiddle has changed from running the script 'onload' to 'no wrap - in '

// Wrap it all in an IIFE if you want.
var SECONDS_IN_A_MONTH = 60*60*24*30; //seconds * minutes * hours * days

// Search for elements to be turned into counters
$('.search-counter').each(function() {
    var $this, searches, interval, counter;
    $this = $(this);
    searches = parseInt($this.data('searches'), 10);

    if (searches < 1  || isNaN(searches)) return;

    interval = (SECONDS_IN_A_MONTH/searches)
    counter = 0;

    // Start the counter at zero.
    $this.html(counter);

    setInterval(function () {
        $this.html(++counter);
    }, interval);
});

I've modified your html to include the number of searches per month in a data attribute. I've also added a class to the elements that will be turned into counters. This allows the javascript to deal with any number of counters on a page. E.g. a counter would look like:

 "Chess" has had...

searches

I don't think you gain anything by splitting up the calculation of the interval. If you think it about another way, you're trying to calculate the time between searches which is clearly just the number of seconds in a month divided by the number of times the search was executed.

If you can't change the html, or would rather keep your code then I have a few points.

It's nicer to start the counter at zero.
It's better not to rely on hoisting - put simply, only use a function after you've written it.
document.getElementById(elementId).innerHTML = counter; will have to search the DOM on every 'tick'. Cache the element
I used 30 for days in a month rather than 28 - use whichever period the data is from.

All pretty minor stuff really.


Spread values to an object (Computed property names)

Your solution is okay; although I'd make appendOtherInfo() a local function of createOptions(). But the problem is, in terms of abstraction - you build a function that you want to re-use and that gives you the feeling it is generic enough for all future use cases for your drop down. However, there are two problems - your "generic" function is just generic enough for flat objects and cannot easily handle nested objects.

Furthermore because it's only argument is an object, different properties in it have different meanings - this is not good for code readability.

So my advice is, why bother writing something that is seemingly generic, but actually not generic enough that it will ever see proper reuse.

Instead simply use direct mappers; they are more readable and they give you the full flexibility, so instead of:

<react-select options = { createOptions({
  data: people,
  valueKey: 'id',
  labelKey: 'name',
  type: 'type',
  capitalCity: 'city'
})}>/

Simply do:

<react-select options = { people.map(peopl => {
  value: peopl.id,
  label: peopl.name,
  type: peopl.type
  capitalCity: peopl.city
}
}>/

(I did not look up <react-select>'s API):
Do not hide simple extracting and remapping behind functions if there is no need to - make code explicit and readable.

You can happily use destructuring with renaming and ..., if you only need to map label and value as well:

<react-select options = { people.map(peopl => ({
  const {id: value, name: label, ...other} = peopl;
  return {value, name, ...other}})
)}>/

Or to be explicit and combining above:

<react-select options = { people.map(peopl => ({
  const {id: value, name: label, type, city: capitalCity} = peopl;
  return {value, name, type, capitalCity}})
)}>/


Switching tabs, with previous/next arrows, using jQuery

Firstly, the obvious:

Both .addClass and .removeClass can deal with multiple classes at once, so wherever you have something like

  $('#div1').removeClass( 'hide' );
  ...
  $('#div1').removeClass( 'show' );
  ...

you can instead write

  $('#div1').removeClass(['hide', 'show']);

You have a few places where you're just removing the same set of classes from a series of elements. You might consider crafting your selector differently to select them all at once, or at the very least define an intermediate function so that you can write something like

stripClasses(["#div1", "#div2", ...], ['hide', 'show']);

All of this actually seems to be pointless, because if the idea is just to navigate through tabs with arrow buttons, you can use the built-in selected option, both to find out which is currently active and to change it.

The fundamental reason you've got so much complexity in that code block is that you seem to have decided to manually manage all the class changes that go along with moving from one tab to another. You don't actually need to do that.

Something like

$("#tabs").tabs();

$(".left-arrow").click(function () { changeTab("#tabs", -1)});
$(".right-arrow").click(function () { changeTab("#tabs", +1)});

function changeTab(elem, by) {
    var sel = $(elem).tabs("option", "selected");
    var newTab = bounded(0, sel+by, 3);
    $(elem).tabs("option", "selected", newTab);
}

function bounded(lower, num, upper) {
    return Math.min(upper, Math.max(lower, num));
}

should work fine (change the newTab expression to get different behavior, like wrapping, out of it). Just be mindful of your local namespaces and styles.


You are ignoring the whole point of decimals. Which is to avoid rounding errors from floating point caclulations.

You must cast TaxRate, ListPrice, ContributionPercentage, etc. to Decimal and only then do your calculations using Decimal values. Casting at some point is unavoidable, if you have no control over signatures. You can, however, implement a wrapper, which would do the casting and expose Decimal properties. That will make your code more pretty.


Too many JavaScript sort functions to accomplish the same type of sorting

function makeSorter(sortType) {
    sortType = "data-"+sortType;
    return function (a, b) {
        return $(a).attr(sortType) - $(b).attr(sortType);
    };
}

$('#sort-options').change(function () {
    var sortType = $(this).val();
    var $selectedList = $($(".drop-zone.ui-tabs-selected a").attr('href')).find('.connectedSortable');
    var $listItems = $('li', $selectedList);

    $listItems.sort(makeSorter(sortType));

Note that if val is "custom" it won't work, so I recommend replacing "custom" with "sort-order".


Looks good. I'm not sure what feedback you are looking for, but here's a little:

use const where you can, instead of let
the naming is a little confusing at times, hash vs. key. Maybe if you call the hash function calcHash then you can call the value it returns a hash and not have to call it a bucketKey... or maybe the function should be calcBucketKey.
it seems like the scoping of arr may be off... especially in expandArr. I believe the argument is going to override the global definition, so I don't think that the last line that re-assigns arr is going to change the global, but rather a local variable going out of scope.
consider using the modulo operator to loop around the array. It can save some checks against the array size.


Timeouts when calculating stock ratings using LINQ

Exception handling

You are doing some very creative exception handling here. If an exception occurs, no matter what kind of, you are just calling the method again. Do you think there is some magic going on, cleaning the exceptions by calling the code again ?
If you need to call the method again you shouldn't do this from within the method, but from outside at the calling point.
You should also do this only in cases of exceptions where you can assume that by giving some time they could be resolved. But you shouldn't do this infinite. You should use some sort of counter and stop if it has reached a value/border.

"Fill" exception

The linq seems to be unrelated to the exceptions caused by the "Fill" methods. If the exceptions occur if any of the fill methods is called, then there is no linq involved. You should better check how you have implemented these methods.

EDIT

I guess the problems are inside the .FillBySymbol() method. Without seeing this method it is hard to tell the cause of the problems but I assume that your sql query is just returning to many data.

General

You should extract the evaluating of the date withing 60 days from now to a separate variable.

DateTime searchDate = DateTime.Now.Subtract(TimeSpan.FromDays(60));

var nyseQuery = from c in sandp500Table
                where c.Date >= searchDate
                join d in dailyNyseTable on c.Date equals d.Date
                select new StockMarketCompare { stockClose = d.AdjustedClose, marketClose = c.AdjustedClose };

You have some code duplication which could be removed.

This

var sp500StockDataQuery = from c in sandp500Table
                          select new StockData { Close = c.AdjustedClose, High = c.High, Low = c.Low, Volume = c.Volume, Date = c.Date };

and this

var nyseStockDataQuery = from c in dailyNyseTable
                         select new StockData { Close = c.AdjustedClose, High = c.High, Low = c.Low, Volume = c.Volume, Date = c.Date };

together with the call to .AsParallel().ToList()

If both DailyGlobalDataDataTable and DailyNyseDataDataTable share a base class or an interface whith the properties AdjustedClose, High,Low,VolumeandDate` this can be extracted like

private static List<StockData> GetStockData(commonBaseOrInterface table)
{
    return (from c in table
            select new StockData { Close = c.AdjustedClose, High = c.High, Low = c.Low, Volume = c.Volume, Date = c.Date }
            ).AsParallel().ToList();;
}

this can then be called like

calc.sp500Data = GetStockData(sandp500Table);
calc.stockData = GetStockData(dailyNyseTable);

Naming

Based on the naming guidelines methods should be named using PascalCase casing.

Nit picking

Your indention of the code could be better.


Small bash script to start and stop named services

Don't Repeat Yourself

You start/stop/restart apache2 and mysql the same way, so you don't need to duplicate their code. You could create a generalized function that can handle these or any standard service well, like this:

startstop_service() {
    cmd=$1
    name=$2
    sudo service $name $cmd
}

Naming

You renamed the universal and intuitive command names start/stop/restart to the shorter but kind of obscure st/sh/re. I recommend to stick with the originals. Among other things, the startstop_service in my previous point will work out of the box.

The case statement

The case statement in Bash is more concise and easier to read than many if-elif-elif-else statements, for example:

case "$1" in
    start|stop|restart) cmd=$1 ;;
    *) echo "usage: $0 [start|stop|restart] servicenames"; exit 1
esac
shift

Minor things

Your script doesn't use any Bash specific features, /bin/sh would be enough
It's better to validate the cmd parameter once, instead of for every single service name as in your code
If the cmd is invalid, it's good to exit the script with a non-zero exit code (typically exit 1), to indicate failure
You can simplify for name in "$@"; do as for name; do

Suggested implementation

Here's an alternative implementation using the above suggestions:

#!/bin/sh -e

NGINX=/home/prahlad/programs/nginx-1.6.0/sbin/nginx
PHP=/home/prahlad/programs/php-5.4/sbin/php-fpm
PHP_NAME=$(basename $PHP)

startstop_service() {
    cmd=$1
    name=$2
    sudo service $name $cmd
}

startstop_nginx() {
    cmd=$1
    case $cmd in
        stop) $NGINX -s stop ;;
        start) $NGINX ;;
        restart)
            $NGINX -s stop
            sleep 1
            $NGINX
            ;;
    esac
}

startstop_php() {
    cmd=$1
    case $cmd in
        stop) pkill $PHP_NAME ;;
        start) $PHP ;;
        restart)
            pkill $PHP_NAME
            sleep 1
            $PHP
            ;;
    esac
}

case "$1" in
    start|stop|restart) cmd=$1 ;;
    *)
        shift
        servicenames=${@-servicenames}
        echo "usage: $0 [start|stop|restart] $servicenames"
        exit 1
esac
shift

for name; do
    case "$name" in
        php-fpm) startstop_php $cmd ;;
        nginx) startstop_nginx $cmd ;;
        *) startstop_service $cmd $name ;;
    esac
done

Notice that apache2 and mysql are not even mentioned in this script, they are automatically handled by the generic startstop_service function. The script will work with any other standard service too.

As @vnp pointed out, the sleep 1 calls are dodgy, I did not fix that. To fix that, look for pid files created by those services, and use them to check if the service is still running or not.

The bigger picture

Ideally, you should standardize everything: make it possible to start/stop/restart your custom php-fpm and nginx just like other services. That way you can remove the service-specific logic from this script (doesn't really belong here anyway), and then it can work for any service you throw at it. Unfortunately I don't know enough Ubuntu to guide you, but I'm sure the guys on askubuntu.com can help with that.


Your project is setup wrong

Pytest

The simplest solution to most import problems is to just make your project a setuptools package. And install your package.

Whether or not your project is a library or application to fix pytest is really, really simple. You make your project a setuptools package (Which you should already have done if you're making a library). This is by configuring the setup.py file that explains to pip, setuptools, etc how to install your project.

From here you install your package and things just work.

$ pip install .
$ pytest

Applications

Now you might be saying that's cool and all it works for pytest. But now it's broken when I run my program, using python. There are two solutions to that.

Execute your application as a module. Add a __main__.py to the top level directory which will be your application's entry point. Make sure you move your if __name__ == '__main__' code here. And then just use:

$ python -m my_project

Setup an entry point for the setuptools package.

Once you get the above working, then all you need to do is ensure your main guard is only calling a function main. If this is the case, then you can say main is your entry point in your setup.py.

entry_points={
    'console_scripts': [
        'my_project=my_project.__main__:main',
    ],
},

Usage is then just:

$ my_project

This is how the cool kids publish applications to PyPI.

But what about my code? Where's my code review?

Oh yeah, your code is an unneeded hack job. Seriously just make a setuptools package. You get some benefits from it like your project always being on the path, being able to install projects from a private PyPI repository, being able to use tox and nox, having a customizable entry point mapped to a cool name, and not having to use hacks to get your tests to work. I feel I'm biased here, but I really don't see any downsides. Heck I now only use pip to install to Apache.

From here you can just use either of the import strategies you want. I prefer relative imports, but absolute imports might be your jam.

Absolute imports.

from my_project import subpackage
subpackage.foo()

Cool relative imports.

from . import subpackage
subpackage.foo()

MVCE of all of the above

I remember when I was trying to convert to relative imports I Googled and all that I could find was hack jobs. People saying the names of some PEPs that talk about what I'm on about, but only talk about __name__, __files__ and '__main__'. Overall I feel the subjects a shit show mess.

And so if you're like I was and just trying to make some sense of all this nonsense, I have a small MVCE for you. If you copy the files and commands verbatim then you too can have a properly configured Python project.

./src/my_project/__init__.py

./src/my_project/__main__.py (Works with from my_project.foo import FOO too.)

from .foo import FOO

def main():
    print(FOO)

if __name__ == '__main__':
    main()

./src/my_project/foo.py

FOO = 'Bar'

./tests/test_foo.py

import my_project.foo

def test_foo():
    assert my_project.foo.FOO == 'Bar'

./setup.py

from setuptools import setup, find_packages

setup(
    name='my_project',
    packages=find_packages('src'),
    package_dir={'': 'src'},
    entry_points={
        'console_scripts': [
            'my_project=my_project.__main__:main',
        ],
    },
)

Running it

$ cd src
$ python -m my_project
Bar
$ cd ..
$ pip install .
$ pytest
===== 1 passed in 0.05s =====
$ my_project
Bar

In Addition

If you configure your project correctly then your problems should magically disappear. If you still have problems then you should double check you have installed your project.

You may want to use the -e flag when you install the project, so that you don't need to pip install . each time you change a file.

Better yet use this as a stepping stone to upgrade to modern Python development and use tox or nox to run you tests. Not only do these come with the benefit that they test your setuptools package is correctly configured. They also let you, and your coworkers, not fret over having to install a virtual environment and ensure pip install -e . has ran. Just setup a config file and then you all only need to run tox or nox for things to just workTM.


Using a static variable will have the same effect as using a singleton!
Imagine if you had two instances of ProductsCache:
var a: ProductsCache = new ProductsCache();
var b: ProductsCache = new ProductsCache();
a.products = someArrayCollection;
b.products = anotherArrayCollection;

Now, because it's using a static variable, a.products will be anotherArrayCollection.
"Do I really need to learn factories and dependency injections?"
Yes, please, learn Dependency injection! You won't regret it! I don't think for this particular case you need a Factory pattern, but it never hurts to learn that too.
Dependency Injection is not that hard actually, the golden rule is: Whenever an object needs your ProductsCache, give them a reference to your ProductsCache. Don't use something like ProductsCache.instance.products. Tell objects about the ProductsCache you want them to use, don't let them ask a singleton about it. Very easy rule to remember: Tell, don't ask.


Is this UnitTest for updating an object in data-access layer sensible?

First of all, your single method is doing multiple things:

Get Range by id
Copy properties from one instance to another
Commit

Let's try to separate responsibilities:

 Range GetRangeById(Repository repo, int id)
 {
    return repo.Query<Range>().SingleOrDefault(r=>r.Id == id);
 }

 void UpdateRange(Range rangeToUpdate, Range range)
 {
        // I'd even make this Range extension method
        rangeToUpdate.Status = range.Status;
        rangeToUpdate.FirstPsn = range.FirstPsn;
        rangeToUpdate.LastPsn = range.LastPsn;
        rangeToUpdate.PageCount = (int)(range.LastPsn - range.FirstPsn);
        rangeToUpdate.CourierId = range.CourierId;
        rangeToUpdate.WorkflowServer = range.WorkflowServer;
        rangeToUpdate.DoubleFeedInd = range.DoubleFeedInd;
 }

 void IAutoTisDal.UpdateRange(Range range)
  {
     using (var repo = _repositoryFactory.GetRepository(_baseline))
     {
        var rangeToUpdate = GetRangeById(range.Id);
        if (rangeToUpdate == null)
           throw new Exception(string.Format("Range ID {0} not found", range.Id));

        UpdateRange(rangeToUpdate, range);
        repo.Commit();
     }
  }

Two new methods are already easier to understand and test.
And, honestly, I don't think that writing test for IAutoTisDal.UpdateRange makes much sense. It won't provide much value.


Sharing a database connection with multiple modules

If you are creating a database wrapper, why not make a lib out of the wrapper and stick it into a lib directory that other modules/classes can import? So, your Users class would be in a directory structure like this:

project/
    account.py
    lib/
        database.py
    user.py
    zombie.py

Your database.py would look something like:

import pymysql

class Database:
    @staticmethod
    def connect_dbs():
        econ = _mdb.connect(host='db.com',
                            user='user', passwd=pass,
                            db='db', charset='utf8')
        return econ

Then, in the user.py, you'd simply do an import like:

from .lib.database import Database as MyDatabase

Then, to get the connection, something along the lines of:

my_connection = MyDatabase.connect_dbs()

EDIT: As an example, see this repl.it:

class Database:
    connection = None

    def __init__(self):
        print "Instantiating!"

    def connect_dbs(self):
        if self.connection is not None:
            return self.connection

        self.connection = 1
        return self.connection

class User:
    db = None

    def __init__(self):
        self.db = Database()

    def save_user(self):
        print self.db.connect_dbs()

U = User()
for i in range(30):
    U.save_user() # Only instantiates the connection once, then reuses it 30x


Restricting types not related through inheritance without using instanceOf by creating own class hierarchy

You can create the same thing by not creating all those subclasses. I also see that you can't use the instanceOf method. My first intention was getting this test method to work:

System.out.println(Field.fromObject(new ArrayList()).getFeatureValue().getClass());
System.out.println(Field.fromObject(new Integer(6)).getFeatureValue());
System.out.println(Field.fromObject(new Integer(6)).getFeatureValue().getClass());
System.out.println(Field.fromObject(Boolean.TRUE)); // null or error

As you can see, I call Field and not an implementation of the Field class. But I also want the correct class back as what class I put in there, so the output should be:

class java.util.ArrayList
6
class java.lang.Integer
null

In order that Boolean is a type what can't be created. After searching on this topic you come always back to instanceOf or what you did. The thing what I wanted is something I can refactor really easy, so it needed to be on 1 place to refactor.

Enum could help me with that, but still having trouble with subclasses what also need to be valid. (ArrayList if List is allowed)

I refactored your code to this. If you need to create the subclasses, you could still look at the static method.

public class Field<T> {

    private T featureValue;

    Field(T value) {
        this.featureValue = value;
    }

    public T getFeatureValue() {
        return featureValue;
    }

    public static <T> Field<T> fromObject(T value) {
        for (Allowed allow : Allowed.values()) {
            if (allow.getClazz().isAssignableFrom(value.getClass())) {
                return new Field<>(value);
            }
        }
        return null;
    }

    private enum Allowed {

        INTEGER(Integer.class),
        STRING(String.class),
        LIST(List.class);

        private final Class clazz;

        private Allowed(Class clazz) {
            this.clazz = clazz;
        }

        public Class getClazz() {
            return clazz;
        }
    }
}

As you can see, we iterate the Enum values to check the restrictions. With this solution you can add also the following test:

List<String> list  = Field.fromObject(new ArrayList<String>()).getFeatureValue();

As you can see, no casting is required.

The next is broken code:

List<String> list  = Field.fromObject(new ArrayList<Boolean>()).getFeatureValue();

which is also good because these are 2 different types.


Your code is totally imperative. In some cases (probably in most) it's faster, but this not the best way to use OCaml :) Here is my solution in functional style:

Printing the list of lists can be done by iterating over list of lists:

let print lst =
  List.iter (fun l ->
      List.map string_of_int l
      |> String.concat " "
      |> print_endline
    ) lst

Next recursive function does:

Selects head element of the list and makes it heading element of the resulting list
Recursively calls itself on the list of all previous elements (minus resulting subset) + tail.

let rec permutations result other = function
  | [] -> [result]
  | hd :: tl ->
    let r = permutations (hd :: result) [] (other @ tl) in
    if tl <> [] then
      r @ permutations result (hd :: other) tl
    else
      r

All together. Initial result is empty and the stored list of previous elements is also empty:

let () =
  permutations [] [] [1; 2; 3]
  |> print


static Scanner p2Name = new Scanner(System.in);
        static Scanner p1Name = new Scanner(System.in);
        static Scanner p3Name = new Scanner(System.in);

        static Scanner p1Num = new Scanner(System.in);
        static Scanner p2Num = new Scanner(System.in);
        static Scanner p3Num = new Scanner(System.in);

You don't need all those scanners.  One is plenty.

        static Scanner scanner = new Scanner(System.in);

Then replace each call using one of the other variables with scanner.

It's possible that you may have to call scanner.nextLine() after calling scanner.nextInt().  I haven't tried it.

@BKSpurgeon in Java

Here's the @BKSpurgeon solution converted to Java:

Program.java

class Program {

    public static void main(String[] args) {
        GameMaster g = new GameMaster(3);
        g.printResults();
    }

}

Player.java

class Player {

    static Scanner scanner = new Scanner(System.in);

    private String name;
    private int number;

    public Player(int playerPosition) {
        name = inputName(playerPosition);
        printName();
        number = inputNumber();
        //scanner.nextLine(); // uncomment if needed
    }

    private void printName() {
        System.out.println("Welcome "+ name + "!");
    }

    private int inputNumber() {
        System.out.println("Please enter a number between 0 and 9");

        return scanner.nextInt();
    }

    private String inputName(int playerPosition) {
        System.out.println("Player " + playerPosition + ", please enter your name");

        return scanner.nextLine();
    }

    public String calculateResult(int winningNumber) {
        return name + ((winningNumber == number) ? " won!" : ", you lose!");
    }

}

GameMaster.java

public class GameMaster {

    private final int winningNumber;
    private final List<Player> players = new ArrayList<>();

    public GameMaster(int playerCount) {
        winningNumber = chooseWinningNumber();

        for (int i = 1; i <= playerCount; i++) {
            players.add(new Player(i));
        }
    }

    public void printResults() {
        for (Player p : players) {
            System.out.println(p.calculateResult(winningNumber));
        }
    }

    private static int chooseWinningNumber() {
        return (int) (Math.random() * 10);
    }

}

I made a few tweaks to comply with Java coding conventions, but the structure is mostly the same.

I haven't tried to run it, so beware of typos, etc.


Use of templates with templated Deck class

Bottom line: your code here is focused and solid. It's a well-written introductory use of templates. However I'm not sure it's a great scenario in which to use them. First I'll talk about ways to improve its reusability, and then I'll say more about why I think it's a questionable scenario.
As you start trying to implement your own templatized data structure, there are a lot of concerns to think about. Above all else you need to consider how your data structure will be used; what operations will consumers of it expect, what limitations will they have to put up with, and whether any of the data structure's implementation choices lock them into bad patterns. In general I would say you would do well to follow the lead of the STL data structures unless you have specific reasons not to. Here are a few of the places where you currently differ:
void Deck<T>::add(T const &)
This one actually is pretty much spot on. But I want to talk about the implications of how it's implemented. You are requiring T to be copyable. Thus if a consumer of this class needs to compare cards, T will need to compare itself through means other than by its address. This isn't particularly unusual, but I just wanted to be clear that comparing T instances by address is invalidated by Deck<T>'s implementation.
The biggest question mark here is the lack of a range insertion, perhaps via constructor or add(InputIterator first, InputIterator last). Similarly there's no index-based insertion, but that wouldn't mix well with the two vectors that are often out of sync.
T Deck<T>::draw()
Before C++11 introduced move semantics, there was not necessarily a low cost way to examine and remove an item from a data structure. This is why vector and other data structures let you examine the front or back, but don't return the removed item on a pop_back(). While it's perfectly good to wrap the functionality of the underlying storage, as the cost of copying T goes up, so does the cost of this implementation of draw(). Implementing it in some other fashion (typically as two separate methods for peeking and removing) is suggested before C++11.

Taking into account what Corbin and Loki Astari point out, it's more relevant to consider weak and strong exception guarantees (essentially the ability to reason about correctness in unusual situations) instead of the cost of copying (thanks especially to RVO). Whether you need to care about either is still completely dependent on your use case in practice, and thus only of extreme importance in general purpose data structures, or in ones you know need to offer it.

Inside draw()
Your implementation of draw() verifies that the playable deck has items remaining. This is certainly good for catching errors, but leads to repeated checks for the same data. Either the calling code will look like while (true) { ::: draw(); ::: } and will have to use a try/catch to find out when the deck was empty, or it will look like while (!deck.empty()) { ::: draw(); ::: }. The former is a questionable way to use exceptions, as an empty deck is hardly an unexpected condition, but the latter means both the caller and callee are repeating the empty check. It's also possible that the caller knows this in other ways, such as having put 52 cards in the deck and then looping 52 times to empty it.
As an aside, it can still be useful to have this sort of check available by another name (consider the difference between vector<T>::operator[] and vector<T>::at), or available through a compile-time option (such as a DEBUG build). But it's typically good to make an unchecked version available (vector's operator[] case).
void Deck<T>::reset()
I'm lumping a couple comments in here, and this is less about following the STL's lead. Like in draw(), as the cost of copying T goes up or the size of your deck goes up, so does the cost of reset(); is it possible that you don't need to save the original order? If you don't, then perhaps it would be better to consider a different implementation:
one vector<T> containing the order of the deck, one vector<T>::const_iterator or vector<T>::size_type containing the index/iterator through which you've already played. This would have a lot of repercussions, so I'm going to show the methods that it would impact, assuming the class has a size_type deck_top, and that we remove original. I like the shorter code, but that has less to do with the index and more to do with the other changes.
template <class T> bool Deck<T>::empty() const
{
    return deck_top >= playable.size();
}

template <class T> T const & Deck<T>::draw() // note we can now return a reference
{
    return playable[deck_top++];
}

template <class T> void Deck<T>::reset()
{
    deck_top = 0;
}

template <class T> void Deck<T>::shuffle()
{
    std::random_shuffle(playable.begin() + deck_top, playable.end());
}

This of course has multiple tradeoffs besides the ones I already mentioned. Perhaps the biggest is that there's still no way to remove cards (temporarily or permanently), so it's hard to model a game that shuffles a partial deck while people are still holding some cards in their hands. I think you will rapidly find that it's hard to make this data structure usable for all the scenarios you think you want it to support without making it almost as generic as vector itself. At which point you will have to consider whether it's worth reusing the data structure, or if it's really just for a single program's use.
Final notes
As a generic comment, I'm undecided on card vs. item. I think card conveys the intended use better, and doesn't really get in the way if someone wants, say, a "Deck" of tiles instead. But I do agree in general with the point about not boxing yourself in by your parameter names.


Publishing a description about a selected band

I have several comments on both your HTML and your JS.

We'll start with the HTML:

You can keep it much cleaner by separating Javascript from it completely. For example, instead of doing this:

<button onclick="addEntry()">Add row</button>

you would do this:

<button id="add-entry">Add row</button>

and in your script:

$('#add-entry').on('click', addEntry);  // binds addEntry() to the
                                        // click handler for that element

You don't need a form element as you aren't submitting anything. See my revised version below for how to access the checked radio option with jQuery.
I would use div elements instead of br to create new lines, because it will be much easier to go in later and change the style (for example, if you wanted to add padding, or increase the spacing between the radio options).
You can use an ol element to get a numbered list instead of manually inserting a number next to each new entry.

JS:

You included jQuery but you're not using it anywhere in your code (it makes it very easy to manipulate the DOM).
You can put these statements inside a $(document).ready() block, which means they will get executed when the document is guaranteed to be ready for manipulation.
In addEntry() you have a couple variables that you didn't use at all.

To answer your question, I wouldn't use an OO paradigm for this at all. You aren't doing anything that OOP would improve or make easier. Here is my revision of your code with the changes I mentioned above (demo on jsfiddle):

        <title>Foo</title>

<input type="radio" name="band" value="Led Zeppelin">Led Zeppelin</input>

<input type="radio" name="band" value="Red Hot Chili Peppers">Red Hot Chili Peppers</input>

<input checked="checked" type="radio" name="band" value="The Beatles">The Beatles</input>

<input id="description" type="text" value="Enter something"/>

        <button id="add-entry">Add row</button> <button id="remove-recent-entry">Remove most recent entry</button>


A couple problems

You don't allocate enough space for the return buffer.  You need to allocate 2*len + 1 bytes to handle the worst cast scenario.  The +1 is for the null terminating byte.

If the count goes above 9, you will output a non-digit character instead of a digit.  If the count goes above 256, the digit will wrap around back to '1' and your compression will have failed to encode the original string.


Laravel - super long relation, it doesn't feel right

I suggest you figure out a way to view the execution history for all of the SQL statements across your application. This can be an absolute god-send when trying to untangle or optimize your queries.

I'd recommend using https://github.com/barryvdh/laravel-debugbar . It has a lot of other features as well but presents everything very neatly. There are ways to view the history with custom event listeners and such (https://stackoverflow.com/a/27753889/3224736) but the extra effort for debugbar would be worth it, IMO.

As for your specific query, I believe it'd compile into four separate queries. Three for each time you call first() and one for the update.

Eloquent does allow defining distant relationships with properties like hasManyThrough (https://laravel.com/docs/5.2/eloquent-relationships#has-many-through) but they can get as messy as manually querying the relationships. I'd give it a try, at least.

The other option is to use joins for the three selects. Something like

Enterprise::where('bedrijfsnaam', $ent)
    ->join('rooms', function ($join) {
        $join->on('enterprise.id', '=', 'rooms.enterprise_id')
             ->where('rooms.name', '=', $room);
    })
    ->join('objects', function ($join) {
        $join->on('rooms.id', '=', 'objects.room_id')
             ->where('objects.name', '=', $obj);
    })->first();

(That's just me guessing at your schema, though. You can modify that as needed).

Using one big join would compile into one query, meaning one round trip to the database. Just be sure you have proper indexes on your columns or the query could get bogged down.

-

Or you can investigate eager loading and lazy eager loading your relationships.

That would at least reduce the apparent complexity of your query. But those are most useful if you anticipate iterating the relationships, rather than just selecting one of them. They wouldn't likely do much to speed up your current query.

As complete tangents, I'd recommend investigating two items.

Make sure your models define fillable arrays. Without them, passing the entire $input into it, even if you try to manually prune it, can lead to nasty security/integrity holes.
See if you can use a route or action instead of a raw redirect. Laravel is built to use MVC through-and-through so you might as well learn how to use it early on, rather than patch all your manual stuff later.


Get all AD groups and Exchange features of users

The lack of proper indentation hides the fact that for each user you request all the members of every group. That's 15000*1000 = 15 million remote calls, most of which redundant. Even if 100 calls would get answered per second, it would still take more than a day to receive all answers.

The solution is simple: Only call Get-ADGroupMember once for each group, cache the results and then use them to check what groups each user is a member of.

If Get-CASMailbox can return the mailbox information for all users at once instead of one call/user (haven't used it but the documentation indicates it might) you reduce the number of calls even further.


Check if a string contains matching brackets

Let's first take a look at the code

The code could use some space to breathe by adding spaces before and after operators. For example for(;ptr<arr.Length;ptr++) would be more readable like
for (; ptr < arr.Length; ptr++)
The expected bracing style would be to place an opening bracket on a new line.
Omitting braces {} although they might be optional can lead to hidden and therefor hard to find bugs. I would like to encourage you to always use them.
Comments should describe why something is done. Comments like if ( IsClose(ch) ) // found a closing bracket are superflous and reduce the readability of the code.
I know that naming things is a hard task but one should at least try to do this in a way that a reader of the code can grasp the meaning of a variable fast which isn'tthe case for oppBracket.  If a method returns a bool one should name that method like a question. E.g AreBracketsProper would be a better name.

Using recursion is a way one can use, but recursion isn't the holy grail for such a task. You need a ref int and an optional oppBracket to achieve the goal by using recursion.

I would use a Stack<Stack<T>> for keeping track of the nesting levels and instead of two char[] arrays I would use two strings and would use IndexOf(char) to get the index of a bracket and to check if the current char is a bracket at all.

If I find an opening bracket I will create a new Stack<int> which contains the value of openingBrackets.IndexOf() and then I will Push() it on the Stack<Stack<int>>. If I find an closing bracket I will take the last index from the Stack<int> if ther is any and check if it is the same as the value returned from closingBrackets.IndexOf(). This coul truned into an extension method as well, like so

static class BracketHelper
{
    private const string openingBrackets = "{[(";
    private const string closingBrackets = "}])";

    public static bool AreBracketsProper(this string value)
    {
        if (value == null) { throw new ArgumentNullException(nameof(value)); }
        if (string.IsNullOrWhiteSpace(value)) { return true; }

        var stacks = new Stack<Stack<int>>();
        var currentStack = new Stack<int>();
        foreach (char c in value)
        {
            var bracketIndex = 0;
            if ((bracketIndex = openingBrackets.IndexOf(c)) > -1)
            {
                currentStack = new Stack<int>();
                currentStack.Push(bracketIndex);
                stacks.Push(currentStack);
            }
            else if ((bracketIndex = closingBrackets.IndexOf(c)) > -1)
            {
                while (currentStack.Count == 0 && stacks.Count > 0)
                {
                    currentStack = stacks.Pop();
                }

                if (currentStack.Count == 0 || bracketIndex != currentStack.Pop()) { return false; }
            }
        }
        return stacks.Count == 0 || stacks.Pop().Count == 0;
    }
}

Which could be called as an extension method like so

("{}".AreBracketsProper() == true).Dump();
("{[]()}".AreBracketsProper() == true).Dump();
("{[()][{}]{}}".AreBracketsProper() == true).Dump();
("{[}]}".AreBracketsProper() == false).Dump();
("{[{(}])}".AreBracketsProper() == false).Dump();
("{[][][][{(})}]}".AreBracketsProper() == false).Dump();
("{[]}}".AreBracketsProper() == false).Dump();
("{".AreBracketsProper() == false).Dump();
("}".AreBracketsProper() == false).Dump();


Elegant way to "construct" kind-of enum values in go

Note that unlike C enums, your const declarations define some values of AccessLevelValue, but in Go they are not considered to exhaustively define all valid values of AccessLevelValue.

Also, the values are integer constants - why are you passing around pointers to them?

You might consider a switch statement:

function int2AccessLevel(level_int int) *AccessLevel {
    switch level_int {
    case 10: return GuestPermissions;
    case 20: return ReportedPermissions;
    // ...
    default: panic("Unrecognized value for AccessLevel");
    }
}


Determine value in range, inject to HTML to be used in CSS

Why is $lim01 never used?  Is it always equal to 1?

Only one of the subscription packs applies, if at all.  You should first make it clear which subscription pack applies.

$subscription_pack = (($x >= $lim03) ? 3 :
                     (($x >= $lim02) ? 2 :
                     (($x >= $lim01) ? 1 : NULL)));
# Note: inactive rather than deactive
$active1 = $active2 = $active3 = 'fb-sub-inactive';
if ($subscription_pack == 1) { $active1 = 'fb-sub-active'; }
if ($subscription_pack == 2) { $active2 = 'fb-sub-active'; }
if ($subscription_pack == 3) { $active3 = 'fb-sub-active'; }

I also suggest reworking the CSS so that you can drop the fb-sub-inactive class altogether.


Converting array of bytes to the hex string representation

Yes, but I doubt you'll see any practical difference with such short input.

Two ideas: reduce the number of possible dynamic allocations, and do the conversion yourself with a small lookup table.

You can do both of these by pre-allocating the string container (you know the target size already), then doing the hex conversion manually. Something like this:

constexpr char hexmap[] = {'0', '1', '2', '3', '4', '5', '6', '7',
                           '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

std::string hexStr(unsigned char *data, int len)
{
  std::string s(len * 2, ' ');
  for (int i = 0; i < len; ++i) {
    s[2 * i]     = hexmap[(data[i] & 0xF0) >> 4];
    s[2 * i + 1] = hexmap[data[i] & 0x0F];
  }
  return s;
}

Running this on my machine, with a test string that is 128k times 256 chars (from 0 to 255) gives me about 1.1s for your code, and about 0.18s for mine (redirecting to /dev/null to avoid I/O issues).

This should be at least not-worse than your version for small strings - there's no opportunity for the compiler to make a sub-optimal inlining decision on the string stream operators in particular, and (named) RVO will take care of eliding the copy from the return value to the caller's std::string hex.

Small benchmark to test this on (bad quality) pseudo-random 300 char long strings:

#include <sstream>
#include <iomanip>
#include <stdio.h>
#include <ctime>
#include <vector>

std::string hexStr(unsigned char *data, int len)
{
  std::stringstream ss;
  ss << std::hex;
  for (int i = 0; i < len; ++i)
    ss << std::setw(2) << std::setfill('0') << (int)data[i];
  return ss.str();
}

constexpr char hexmap[] = {'0', '1', '2', '3', '4', '5', '6', '7',
                           '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

std::string hexStr2(unsigned char *data, int len)
{
  std::string s(len * 2, ' ');
  for (int i = 0; i < len; ++i) {
    s[2 * i]     = hexmap[(data[i] & 0xF0) >> 4];
    s[2 * i + 1] = hexmap[data[i] & 0x0F];
  }
  return s;
}

int main()
{
  srand(time(NULL));
  std::vector<std::string> data;

  for (int i = 0; i < 1000; i++) {
    std::string packet;
    for (int i = 0; i < 300; i++)
      packet += static_cast<char>(rand() % 256);
    data.push_back(packet);
  }
  for (int i = 0; i < 10; i++) {
    clock_t beg = clock();
    for (auto const &s : data) {
      std::string hex = hexStr((unsigned char *)s.c_str(), s.length());
      printf("%s\n", hex.c_str());
    }
    fprintf(stderr, "Elapsed 1: %f\n",
            (clock() - beg) / (1.0 * CLOCKS_PER_SEC));
    beg = clock();
    for (auto const &s : data) {
      std::string hex2 = hexStr2((unsigned char *)s.c_str(), s.length());
      printf("%s\n", hex2.c_str());
    }
    fprintf(stderr, "Elapsed 2: %f\n",
            (clock() - beg) / (1.0 * CLOCKS_PER_SEC));
  }
}

Sample output compiled with clang++ (3.5) -std=c++11 -O3 (doesn't vary too much), stdout redirected to /dev/null:

Elapsed 1: 0.018132
Elapsed 2: 0.001365
Elapsed 1: 0.017858
Elapsed 2: 0.001373
Elapsed 1: 0.018429
Elapsed 2: 0.001313
Elapsed 1: 0.018918
Elapsed 2: 0.001229
Elapsed 1: 0.019134
Elapsed 2: 0.001244
Elapsed 1: 0.018915
Elapsed 2: 0.001239
Elapsed 1: 0.018031
Elapsed 2: 0.001266
Elapsed 1: 0.018051
Elapsed 2: 0.001239
Elapsed 1: 0.017071
Elapsed 2: 0.001315
Elapsed 1: 0.017841
Elapsed 2: 0.001239


Transforming tuple with (int month, int year) in string "mm/yyyy"

You can use the datetime module:

import datetime as dt
result = (2, 2017)
date = dt.date(year=result[1], month=result[0], day=1)
date_str = date.strftime("%m/%Y")


OP's approach is very tangled.

No provisions are made for a final carry-out of the sum.

char result(char r, int c) { should at least been used description names: char add_digit_carry(char digit, int carry) {

for (int i = strlen(c)-1; i > -1; i--) --> Little things like i >= 0; are certainly easier to follow.

strlen() returns type size_t.  Array indexing and sizing is best done with that type.

The basic way to add strings is just like grade-school math:  add the 1 places, form the sum and carry.  Then add the next most significant column along with the carry.  Repeat for all digits and consider a carry out.

Assuming memory issues are not a big concern ....

#include <assert.h>
#include <stdlib.h>
#include <string.h>

// c = a + b
char *KFM_add(char *c, size_t c_size, const char *a, const char *b, int base) {
  assert(base >= 2 && base <= 10 && c_size > 0);
  size_t a_end = strlen(a);
  size_t b_end = strlen(b);
  size_t c_end = c_size - 1;

  c[c_end] = '\0';
  int carry = 0;

  while (a_end > 0 || b_end > 0 || carry > 0) {
    int sum = carry;
    if (a_end > 0) {
      sum += a[--a_end] - '0';
    }
    if (b_end > 0) {
      sum += b[--b_end] - '0';
    }
    assert(c_end > 0);
    c[--c_end] = sum % base + '0';
    carry = sum / base;
  }

  // return memmove(&c[0], &c[c_end], c_end); // Corrected code @JS1
  return memmove(&c[0], &c[c_end], c_size - c_end);
}

#include <stdio.h>

int main(void) {
  char a[] = "111";
  char b[] = "01";
  char c[80];

  puts(KFM_add(c, sizeof c, a, b, 2));  // Output 1000
}

Should one want to explore binary addition closer:

#include <stdbool.h>
  ...
  bool carry = 0;
  while (a_end > 0 || b_end > 0 || carry > 0) {
    bool a_bit = (a_end > 0) ? (a[--a_end] - '0') : false;
    bool b_bit = (b_end > 0) ? (b[--b_end] - '0') : false;
    assert(c_end > 0);
    c[--c_end] = (a_bit ^ b_bit ^ carry) + '0';
    carry = (a_bit & b_bit) | (b_bit & carry) | (carry & a_bit);
  }
  ...


Conversion from Roman to decimal numbers

public class Romans_to_Decimals

"when in Rome, do as the Romans do!"
keep to Java naming conventions when programming java.

for (int i = number.length() - 1; i >= 0; i--)

use the fore each notation if possible. In your case this would require a different approach to the problem tough...

switch (array[i])
 //..
    if (i != 0 && array[i-1] == 'I')

use variables with explicit names.

 case 'X':
                    if (i != 0 && array[i-1] == 'I')    //IX = 9
                    {
                        result += 9;
                        i--;
                    }
                    else
                    {
                        result += 10;
                    }
                    break;
            case 'C':
                    if (i != 0 && array[i-1] == 'X')    //XC = 90
                    {
                        result += 90;
                        i--;
                    }
                    else
                    {
                        result += 100;
                    }
                    break;
 for (char currentDigit:  number.toCharArray())

identify the variable elements whithing this code duplication and make them actula variables, then extract the logic to a method the getst the variables as parameters. Uning an enum to represent individual roman digits helps a lot:

    public class RomanNumbers {
        enum DigitValue {
            DIGIT_INVALID('-', 0),
            DIGIT_I('I', 1),
            DIGIT_V('V', 5),
            DIGIT_X('X', 10),
            DIGIT_L('L', 50),
            DIGIT_C('C', 100),
            DIGIT_D('D', 500),
            DIGIT_M('M', 1000),;
            private final char digit;
            private final int value;

            DigitValue(char digit, int value) {
                this.digit = digit;
                this.value = value;
            }

            static DigitValue getFor(char digit) {
                DigitValue[] values = values();
                for (DigitValue digitValue : values) {
                    if (digitValue.digit == digit) {
                        return digitValue;
                    }
                }
                throw new IllegalArgumentException(digit
                        + " is not valid part of a roman number");
            }

        }

        // member variable neede because we cannot return more than one value
        private static int result;  // static because you refused to create an actual object.

        public static void main(String[] args) {
            System.out.println("Enter roman number from I to MMMCMXCIX (1 to 3999), q to quit: ");
            Scanner in = new Scanner(System.in);

            boolean done = false;
            while (!done
                    && in.hasNext()) {
                String number = in.next();
                if (number.equals("q")) {
                    done = true;
                } else {
                    result = 0;
                    char[] array = number.toCharArray();

                    for (int i = number.length()
                            - 1; i >= 0; i--) {
                        DigitValue currentDigit = DigitValue.getFor(array[i]);
                        DigitValue digitBefore = i > 0 ? DigitValue.getFor(array[i- 1]) : DigitValue.INVALID);

                        switch (currentDigit) {
                            case DIGIT_I:
                                result += 1;
                                break;
                            case DIGIT_X:
                                i = caculateFor(currentDigit, digitBefore, DigitValue.DIGIT_I, i);
                                break;
                            case DIGIT_C:
                                i = caculateFor(currentDigit, digitBefore, DigitValue.DIGIT_X, i);
                                break;
                            case DIGIT_M:
                                i = caculateFor(currentDigit, digitBefore, DigitValue.DIGIT_C, i);
                                break;
                            case DIGIT_V:
                                i = caculateFor(currentDigit, digitBefore, DigitValue.DIGIT_I, i);
                                break;
                            case DIGIT_L:
                                i = caculateFor(currentDigit, digitBefore, DigitValue.DIGIT_X, i);
                                break;
                            case DIGIT_D:
                                i = caculateFor(currentDigit, digitBefore, DigitValue.DIGIT_C, i);
                                break;
                            default:
                                System.out.println("Not correct roman number");
                                break;
                        }
                    }
                    System.out.println("Corresponding decimal number is: "
                            + result);
                }
            }
            in.close();
        }

        private static int caculateFor(DigitValue currentDigitValue,
                DigitValue digitBefore,
                DigitValue reducingprevousDigit,
                int loopIndex) {
            result += currentDigitValue.value;
            if (digitBefore == reducingprevousDigit) {
                result -= reducingprevousDigit.value;
                loopIndex--;
            }
            return loopIndex;
        }
    }


There are two things I don't understand about the code in the post.

Are you really committed to using LIL (list-of-lists) format? The documentation is very clear that LIL is not suitable for computing matrix products, for example here:

  To perform manipulations such as multiplication or inversion, first convert the matrix to either CSC or CSR format.

and here:

  Disadvantages of the LIL format [...] slow matrix vector products (consider CSR or CSC).

I find that using CSR instead of LIL for matrix and vector gives an immediate 20× speedup.

Even if you have a good reason for using the LIL format in some parts of your code, you should still convert to CSR before computing the product, as suggested in the documentation.
Given that matrix is dense, why does the code represent it using a sparse matrix? This is bound to incur some overhead that could be avoided by using an ordinary np.matrix.

I find that switching matrix from CSR to np.matrix gives a further 1.5× speedup.


You can let CSharpCodeProvider format Type names:

public static string FormatTypeName(this Type type)
{
    using (var c = new CSharpCodeProvider()) {
        var r = new CodeTypeReference(type);
        return c.GetTypeOutput(r);
    }
}


Here are some things that may help you improve your code:

Avoid memory leaks

The first_letters_only_capitalized function allocates memory (or tries to, see next suggestion) and returns a pointer to that memory, but it is never freed by the calling function.  Instead of using strcpy into a fixed size string, you could instead use the return value directly:

char *user_initials = first_letters_only_capitalized(user_name);
if (user_initials != NULL) {
    puts(user_initials);
}
free(user_initials);

Check for failed memory allocation

Whenever a program allocates memory explicitly, as with using malloc or calloc, it should check to make sure that the allocation succeeded before using the resulting pointer.  When malloc fails, it returns NULL, so you could modify your program like this:

char *capitals = malloc(sizeof(char) * NAME_LEN);
if (capitals == NULL) {
    return capitals;
}

Use const appropriately

One of the functions in your program is declared like this:

const char * first_letters_only_capitalized(char words[NAME_LEN])

But I think it should be this instead:

char * first_letters_only_capitalized(const char words[NAME_LEN])

The reason is that the first signature says that that words might be altered but that the returned pointer may not be.  That seems backwards from the real situation which is that words is not altered by the program (and therefore should be declared const) but that the return value may be used by the caller in any way, including by using free.

Use consistent formatting

Using consistent formatting helps readers of your code understand it without distraction.  This code is mostly well formatted, but the opening brace of the first_letters_only_capitalized is on the same line, which is unlike all the other functions in the program.

Reconsider the sense of boolean functions

The only time is_termininating_char is used, its return value is negated.  That suggests the function sense should be inverted:

bool is_not_terminating_char(char ch)
{
    return ch != '\n' && ch != '\0';
}

Allow mixed case input

As the program stands, if the user enters "John Smith" the program returns "JOSM" which is rather odd.  Instead, alter the program to allow for mixed case input.  It may also be interesting to consider other cases such as hyphenated last names and last names such as "von Trapp" in which part of the name is never capitalized.

Trim leading space

The program currently does not trim non-alphabetic leading characters including spaces, so an input of "  #!%!* Al Alpha" yields an output of "  #!%!* ALAL".

Use standard functions where appropriate

Instead of writing your own, it would make more sense to me to use standard function isalpha rather than writing your own is_letter function.

Consider using pointers

Using pointers in your first_letters_only_capitalized function would make it more idiomatic C in my opinion.  Your first_letters_only_capitalized function might  look like this.

char * first_letters_only_capitalized(const char words[NAME_LEN])
{
    char *capitals = malloc(sizeof(char) * NAME_LEN);
    if (capitals == NULL) {
        return capitals;
    }
    char *init = capitals;

    for(const char *ch = words; is_not_terminating_char(*ch); ++ch)
    {
        if (isalpha(*ch)) {
            *init++ = toupper(*ch);
        }
        while (isalpha(*ch)) {
            ++ch;
        }
    }
    *init++ = '\0';

    return capitals;
}

Avoid overly long names

In writing this review, I typed first_letters_only_capitalized nine times.  It's exhausting!  Show some mercy to other programmers and use shorter names, although using a very long name for a function whose purpose is to shorten names might be amusing irony to some.


Bash script to temporarily run a shell without certain group memberships

It's not an error to ask for help

When -h is passed, the help() function shouldn't exit with non-zero status, because it's done what was asked for.

Conversely, when we pass no arguments, we should exit with non-zero, and we should write the message to the standard error stream.

I'd write that as

help() {
    local tab=$'\t'
    cat <<END
$0 - run without groups
Runs a shell as if you weren't in certain supplementary groups.
Good for pretending that you're not a support user.
Usage example:
${tab}$0 [(-h|--help)] [group ...]
Options:
${tab}-h or --help: Displays this information.
END
}

And then use it as

# Just use the command directly instead of testing $?
if ! ARGS=$(getopt -o "h" -l "help" -n "rwog" -- "$@");
then
    help >&2
    exit 1
fi

and

    case "$1" in
        -h|--help)
            help
            exit 0
            ;;

Elsewhere in the code, diagnostic messages are printed to standard output; these should all be redirected to &2.

Checking more exit statuses

We depend on tools such as xargs and sort that might not be present.  Consider letting Bash check some statuses, but make sure you know which commands this will not check:

set -e

Also consider getting Bash to check that you're not using unset variables:

set -u

You'll want to use expansions such as ${foo:-} when you need to avoid this checking.

Quote your variable expansions

Just because you've checked that this is being run by root (perhaps overkill - is it sufficient to be any user that can run capsh?), doesn't mean that they can't do something unexpected.  So write "$@", not $@:

for group in "$@"; do

Don't compare a group against a user

if [[ "$group" == "$SUDO_USER" ]]; then

Did you mean "$SUDO_GID" there?  Also, there's little point using both [[...]] and quotes - I'd stick to the portable [...] here.

If you did mean to compare against the user name (e.g. you know your configuration always creates a per-user group sharing the same name), then it's a good idea to add a comment documenting that assumption, as it might not be valid on another system you copy this to.

No need to grep and sed in a pipeline

Sed is perfectly capable of selecting lines:

dropped_capabilities=$(capsh --print | sed -n -e 's/Bounding set =//gp')

Take care with $PATH

Even though your site's sudo policy should constrain PATH, it may be a good idea to set a specific PATH at the start of the script and/or use fully-qualified pathnames for executables.


Find out how many laptops Molly can buy based on available money, array of quantities and array of costs

My understanding of the problem:

You are provided three values:

A budget(the amount of funds you can spend)
A List of Vendor Batch Sizes
A List of Vendor Batch Prices

Promises/Assumptions: the items 2 & 3(the lists) correspond such that for Vendor i, the vendors batch size and price can be found at List.get(i)

NOTE: Your code has a hard-coded assumption that the two lists (budgetQuantities and budgetCosts) are the same size, or at least you never check that this is true or otherwise enforce this requirement.

Goal: determine the maximum affordable quantity based on Vendor and budget information.

There seems to be some superfluous code going on here, so I will try to address that first

Inner Class MaxQuantity

There really isn't any reason to use this. It has only one use: to interact with the internal int value. As both the class and value are public, I can access all the way through: shoppingBudget.MaxQuantity.value. This is generally considered bad. As the class is in all cases just an int, it can be replaced with an internal variable, private int maxQuantity

suggesting removal

The permute function

As mentioned in my comment, this function seems entirely pointless as the problem does not involve permutations; The information is linear in nature, as there is no "mix and match" (i.e. permutation) of Vendor Information (budgetQuantities and budgetCosts)

suggesting removal

Update
I appreciate your use of recursion in your permute function, but its a tad confusing. The second set of swapping seems pointless, as by the time you reach it you are simply propagating back up the recursion tree, swapping indeces that we no longer use.

I looked for similar permutation implementations and found this well designed permutation util, which I used for comparison testing of your permutation method.

IntStream
There really isn't a need to create an int[] for indices like this. I see it is mostly used in the permute() function, which I have suggested removing, so I will likewise suggest removing this. With a linear solution, it is much easier to create a single int index and increment it as we iterate through the lists, rather than creating an int for every position from 0 to budgetQuantities,size()-1 (the increment approach is also less computationally expensive, especially where memory is concerned)

Update I had to use this in my rework, definitely shouldn't remove

maxQuantity.value = Integer.MIN_VALUE;

Integer.MIN_VALUE is usually a good initial value for a maximum. However, this is not the true minimum of the problem. The absolute minimum items you can purchase is 0, so it makes more sense to initialize your globalMaximum to 0: private int globalMaximum=0;

UPDATED

findSolution is NOT broken

There is a hole in the logic of your findSolution method. You seem to have written your code with the intent that this method will be called many times, and each result will be compared with the global max (based on your use of maxQuantity.value = Math.max(maxQuantity.value, possibleMax); in permute)

However, this method runs across all vendors. Because of this, your int remaining and counter should be inside your for loop, with an int localMaximumToReturn where counter is currently.

To explain further: your current findSolution forEach loop represents each Possible Interaction between Molly and one Vendor, so both the money available and the total number of computers she can buy per transaction are independent. However, in the above code, each loop is interacting with the same funds, which will introduce severe error.

Example: I ran in debug with breakpoints inside the findSolution method, outside the forEach loop, with the following information:

moneyAvailable: 50
budgetQuantities: {20,19}
budgetCosts: {24,20}

Stepping through, the first loop correctly computes that howManyToBut is 2, meaning she can buy 40 computers for 48 dollars. Then you set remaining to 2 with remaining -= 48

This means for the next loop, we get a cost of 20, which is now greater than our remaining 2 so the second cost/quantity maximum is never checked

We have technically hit each index, so we leave the loop and return the counter 40. While this IS the correct answer, we got here by false means. If you switch the order of items in your lists for the first assert, you should see a return of 38, which will break your assertEqual

It is at this point I see the point of permute in that it was scrambling your orders. Since your findSolution would only ever succeed at checking the first index, permute scrambles your orders so that each item gets a shot at being first, so each possible results is compared with the globalMax. While this works, it is incredibly backward, and buggy I highly recommend fixing this bug in findSolution, and remove the no longer needed permute()

With superfluous code removed you should end up with something similar to:

public class ShoppingBudget {
    int globalMax;

    public int budgetShopping(int budget, List<Integer> batchSizes, List<Integer> batchCosts) {
        List<Integer> indeces = new ArrayList<>();
        IntStream.range(0, batchSizes.size()).forEach((num) -> indeces.add(num));
        Collection<List<Integer>> permutations = new Permutations<Integer>().permute(indeces);
        permutations.forEach(
                (permutation) -> checkPermutationMaximum(permutation, budget, batchSizes, batchCosts)
        );
        return globalMax;
    }

    private void checkPermutationMaximum(List<Integer> indeces, int budget, List<Integer> batchSizes, List<Integer> batchCosts) {
        int localMax = 0;
        int remainingCash = budget;

        int i = 0;
        int sz = indeces.size();
        while (i < sz && remainingCash > 0) {
            int currentVendor = indeces.get(i);
            int currentCost = batchCosts.get(currentVendor);
            if (remainingCash >= currentCost) {
                int cashToCostRatio = remainingCash / currentCost;
                remainingCash -= currentCost * cashToCostRatio;
                localMax += cashToCostRatio * batchSizes.get(currentVendor);
            }
            i++;
        }

        if (localMax > globalMax) globalMax = localMax;

    }
}

The above passes all of your assertEqual tests as well as debug scrutiny

Comments on Update

Rather than trying to create the next unvisited permutation at run time (which is your above approach) I adapted a utility to return a Collection of Lists, where each List is a possible permutation of the input. Then I compute and check the maximum for each permutation


When making a collection of routines to handle a type, strongly advise to create a create and destroy function.   Rather then the below, consider some initialization function.

// Replace this code
Node *head = (Node *)malloc(sizeof(Node));
head->next = head;

// with this
Node *new_list(void ) {
  Node *head = malloc(sizeof *head);
  if (head) {
    head->next = head;
  }
  return head;
}
...
Node *head = new_list();

The names on the functions benefit by having the leading text indicate the grouping.   Avoid function delete() - too generic.

void clist_insert_beg(Node *current, int data);
void clist_delete(Node *current, int data);
void clist_print(Node *current);
int clist_find(Node *current, int data);

Consider 4 operations: Add_Before_First(), Remove_First(), Append(), Remove_End().   A circular list means it is relatively easy (O(1)) to do something at both ends of the list.   This code's delete_from_list() is nothing more that a typical linked list would do and take O(n) time.  Sadly even the insert_beg_of_list() also takes O(n) time.  Recommend to re-work this code so at least 1 of 2 "head" functions and at least 1 of the "tail" functions can operate in O(1) time  (no while loops).
Having a circular list with only a single pointer is do-able and perform 3 of the above 4 in O(1) time.  Consider a list that points to the tail.  No need for a head pointer as tail->next is the head.
Recommend a simpler to code and maintain allocation style.  The cast is not needed and the sizeof works even is the type of *(current->next) changes.

// current->next = (Node*)malloc(sizeof(Node));
current->next = malloc(sizeof *(current->next));

Though posted as 1 file, better to post as a circular_list.c, circular_list.h, main_sample_usage.c files to clearly identify that which is public and private.
I have doubts delete_from_list() works when the last element is deleted.  I think that is because of the overall design.  IMO, when a list contains no data, it should consume minimal space.  IOW, a NULL pointer is an empty list.  When a list type is used heavily, there are often many empty lists.  So an empty list of a pointer to a node pointing to itself seems wasteful.
Functions that do not modify the list should use const.

// int find_in_a_list(Node *current, int data) {
int find_in_a_list(const Node *current, int data) {

// void print_list(Node *current) {
void print_list(const Node *current) {

Hoping to find functions like

unsigned count_list(const Node *current);
bool empty_list(const Node *current);

Minor Use int main(void) {


Count numbers with atleast one common factor, excluding one

You write:

  A common issue I am having is that my code runs on my machine, and in their test environment, but my code ultimately exceeds their time limits upon submission. I was wondering if anyone had any general advice on making my code more efficient so I could continue to make use of the practice problems.

Here's that general advice: measure your code before you submit it! These kind of programming challenges normally give bounds on the size of the possible inputs, for example here it says:

  Constraints: \$1≤T≤100000\$, \$1≤N≤1000000\$

So in the worst case there would be 100,000 test cases, each of which has a number that might be as large as 1,000,000. So you need to ensure that your code runs quickly enough when run against a test case of this size.

Creating a test case is easy, for example you could write:

import random
T = 100000
N = 1000000
with open('worst-case.txt', 'w') as f:
    print(T, file=f)
    for _ in range(T):
        print(random.randrange(1, N + 1), file=f)

And then run your code using worst-case.txt as the input and see how long it takes. If the time limit is 5 seconds on the challenge site, then you probably want to make sure your code runs a bit quicker than that on your computer, in case the challenge site is running on a slower computer.

When you try this you'll find that the code in the post takes so long that you would be waiting a very long time for it to finish! I find that with \$T\$ reduced to 10, the code in the post takes about 3 seconds. So, extrapolating to the worst case, it would seem that when \$T = 100000\$, the code in the post would take 30,000 seconds, or about 8 hours.

Why does it take so long? Well, for every number \$n\$ in the input, it calls myfun. And then myfun constructs a list pos of all the numbers between 1 and \$n\$. But remember that \$n\$ might be as large as 1,000,000, which means that pos might have 1,000,000 elements, and a new list pos gets created for each number in the input. But there might be as many as 100,000 numbers in the input, so the line

pos.append(i)

might need to be executed as many as 100,000,000,000 times!

In this case you need to think clearly about all the steps involved in your algorithm. Try working through your algorithm step-by-step on a piece of paper. Can you spot any steps that seem useless? Can you spot any places where you needlessly compute the same thing many times?


Implementation of Non-Generic Stack in Java

Thanks for sharing your code,

Avoid Wild Imports

You import

import java.util.*;

but the only thing you use from the util package is Scanner,
so why not just

import java.util.Scanner;

Now it's obvious to anyone reading what you'll be using from util.

Counting Starts at 0

stackarray = new int[size+1];

in your constructor, If I make a stack of size 10, I'm actually making one of size 11!

You're also accommodating for your +1 size in your constructor with

if(top == stackarray.length - 1){
   ...
}

if you just initialised your array as new int[size];

then this could look like

if(top == stackarray.length){
   ...
}

At the moment you're offsetting in 2 places, when in fact you don't need to do this anywhere! This is making the code more difficult for other people to follow.

In your display method

for (int i = 1; i<=top ; i++){
    ...
}

you can just start this at i = 0, starting at 1 is very unnatural.

this should be re-written like

for (int i = 0; i < top ; i++){
     ...
}

Unusual Behaviour

right now, if I pop() an empty stack, it will return 0. This would be extremely unusual behaviour for an empty data structure. It wouldn't really be empty anymore would it?

  int pop(){
    int lastElement = 0;
    if(top == 0){
      System.out.println("Stack is Underflow");
    }
    else{
      lastElement = stackarray[top];
      top--;
    }
    return lastElement;
  }  // Pop Method

instead of printing "Stack is Underflow", why not throw a new EmptyStackException(msg). That's what it's for after all.

In your push method, you print a message if the stack is full. Again I would suggest throwing an appropriate exception here, or even better, you could resize the array to accommodate the new element. (This would be great practice for making an ArrayList implementation.)

What's Missing?

Your stack is missing an isEmpty() or empty() method, this should just return true/false for if the stack is empty or not. This is extremely simple to implement so you shouldn't have any problems with this!

Your stack is missing a peek() method, this should show the next element, without removing it.

Why Stop There?

Some other methods you might like to add for practice could be,

public boolean contains(int element) // if the lement is present in the stack

public int numberOf(int element) // occurrences of a given element

public int smallest() // the smallest element in the stack

public int largest()

public int totalSum()

public int average()

Hopefully this review was useful for you, keep it up!


Time complexity

  It has \$O(n^2)\$ complexity.

It actually has \$O(n^3)\$ complexity.  As @Cadoiz noted, isPalindrome isn't \$O(1)\$ but \$O(n)\$.

Note that Manacher's algorithm isn't \$O(n)\$ but \$O(n^2)\$.  The outer for loop and the inner while loop both are \$O(n)\$.  Together that makes them \$O(n^2)\$.  In practice, it will do better than that, as the worst case is when every character is the same.  You could also write this as \$O(m\cdot n)\$, where \$m\$ is the length of the longest palindrome substring.  It's only linear if you neglect \$m\$, which is itself \$O(n)\$ in the worst case.

Manacher's is linear in space, but your version can be constant in space (if you don't make extra substrings).

Unnecessary code

        for (int i = 0; i + palindromeSize <= str.length(); i++) {
            int substr = i + palindromeSize;
            String test;
            if (substr > str.length()) {
                test = str.substring(i);
            } else {
                test = str.substring(i, substr);
            }
            if (isPalindrome(test)) {
                return test;
            }

But substr can never be greater than the length of the string, as you you check for that in the for loop test.  So you can just say

         for (int i = 0; i + palindromeSize <= str.length(); i++) {
            int substr = i + palindromeSize;
            String test = str.substring(i, substr);

            if (isPalindrome(test)) {
                return test;
            }

Naming

I would generally expect something named substr to be a String, not an int.  I would call this end.  And to match, I'd change i to start.

I would call test something like candidate (it's not a test; it's the the thing to be tested), but I don't actually think that you need it.  Consider what happens if you use Cadoiz's suggestion instead and avoid taking the substring.

         for (int start = 0, end = palindromeSize - 1; end < str.length(); start++, end++) {
            if (isPalindrome(str, start, end)) {
                return str.substring(start, end + 1);
            }
         }

Although I wouldn't be surprised if the compiler optimizes out the duplicate strings anyway.

I also changed the parameters slightly.  Since we don't take the substring until we are ready to return, we don't need end to match substring.  This saves us a bunch of small math operations in isPalindrome.

Work with the right data structure

Rather than work with the String, I'd probably work with the underlying character array.

    public static boolean isPalindrome(char[] characters, int start, int end) {
        for (int i = start, j = end; i < j; i++, j--) {
            if (characters[i] != characters[j]) {
                return false;
            }
        }

        return true;
    }

We lose the possibility of trimming the string, but you weren't using that.  It would be more efficient to do that work just once on the original string anyway.

As in your original, I assume that start and end will be reasonable values.  E.g. that end will be greater than or equal to start, and both will be in range for the array.  That's not hard

        if (start > end || start < 0 || end >= characters.length) {
            throw new IllegalArgumentException();
        }

but you don't have any exception handling anyway.  Also note that the last two of those cases will throw more specific exceptions if you let them go through.

    public static String findLargestPalindrome(String str) {
        char [] characters = str.toCharArray();

        // start with the whole string and work down to single characters
        for (int palindromeWidth = str.length() - 1; palindromeWidth >= 0; palindromeWidth--) {
            for (int start = 0, end = palindromeWidth; end < str.length(); start++, end++) {
                if (isPalindrome(characters, start, end)) {
                    return str.substring(start, end + 1);
                }
            }
        }

        return null;
    }

This version calls isPalindrome with the character array and the starting and ending indexes.

I'm renamed palindromeSize.  Note that I defined it slightly differently than you did.  Hopefully the name palindromeWidth is less confusing.  Perhaps a name like distance might be clearer.


UPenn CIS 194 Homework 2: Log file parsing

parseMessage

The main problem here is that you are calling unwords on the result of words ..., and this doesn't preserve the original whitespace.

For instance, the last case should just be:

case words x of
   ...
   _   -> Unknown x   -- use the original message text

and you have a similar problem with unwords m.

Unfortunately, to preserve whitespace in these cases I don't think you will be able to use the words function here.

It is customary to have parens around the list patterns, e.g.:

parseMessage x = case words x of
                      ("E":s:t:m) ->  LogMessage (Error (read s::Int)) (read t::Int) (unwords m)

Even though they are not needed, they aid in reading the code.

Also, aligning the -> in the case patterns helps with readability.

The type signatures on your read calls are not needed due to Haskell's type inference.

insert

You should be getting this warning from ghc and ghci:

LogAnalysis.hs:19:1: Warning:
    Pattern match(es) are non-exhaustive
    In an equation for ‘insert’:
        Patterns not matched:
            (LogMessage _ _ _) (Node (Node _ _ _) (Unknown _) _)
            (LogMessage _ _ _) (Node Leaf (Unknown _) _)

This means that your code doesn't cover all of the possible cases.

Append to your question an updated version of insert which doesn't produce any warnings, and then I might have some further comments about it.

(Please append to your question instead of modifying it so it doesn't invalidate any existing comments.)

Let me know if you are not seeing this warning from ghc / ghci so we can figure out what's going on with your environment.

filterEmpty

I don't think the logic is right here. What if you have this message:

LogMessage (Error 62) 23 ""

Shouldn't the empty message be included in the message list?


Method for returning valid URLs from a sitemap URL

Just a couple of thougths...

if (string.IsNullOrWhiteSpace(sitemapText))
  yield break;

This is a very unusual handling of null/empty argument values and should be documented. A more meaniningful name like GetSitemapUrlsOrDefault would also help. Without it the expected way is to throw an ArgumentException.

foreach (Match m in urlRegex.Matches(sitemapText))
  urls.Add(CleanUriString(m.Value));

foreach (var url in urls)
{
  var cleanedUriString = CleanUriString(url);

  if (Uri.IsWellFormedUriString(cleanedUriString, UriKind.RelativeOrAbsolute))
      yield return new Uri(cleanedUriString);
}

You don't need all this. Instead you can build a nice query that does everything in one go and in a single run:

return
    urlRegex
        .Matches(sitemapText)
        .Cast<Match>()
        .Select(m => CleanUriString(m.Value))
        .Where(cleanedUriString => Uri.IsWellFormedUriString(cleanedUriString, UriKind.RelativeOrAbsolute))
        .Select(cleanedUriString => new Uri(cleanedUriString));

or alternatively:

return
    from m in urlRegex.Matches(sitemapText).Cast<Match>()
    let cleanedUriString = CleanUriString(m.Value)
    where Uri.IsWellFormedUriString(cleanedUriString, UriKind.RelativeOrAbsolute)
    select new Uri(cleanedUriString);

You don't need the .ToCharArray(); on the legalCharacters string. A string is already a char-array.

Oh, and of course the WebClient needs to be disposed. Wrapping it with a using would be good.