How can this LINQ query using SqlFunctions.Datediff and LINQKit's PredicateBuilder be improved I have this query built using the above, but it feels like it could be improved to make it more concise:

  private IQueryable<Lead> _queryLeadsByHeat(int? ownerUserId, bool warmLeads)
        {
            var predicate = PredicateBuilder.False<Lead>();

            predicate = predicate.Or(x => x.LeadPool.DecreaseByUnit == (int) DecreaseUnitTime.Day
                                           &&
                                           (
                                               (x.LastHeatValue - SqlFunctions.DateDiff("day", !x.LastContactDate.HasValue
                                                                          ? x.InitialContactDate
                                                                          : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) > 0 && warmLeads ||

                                                (x.LastHeatValue - SqlFunctions.DateDiff("day", !x.LastContactDate.HasValue
                                                                          ? x.InitialContactDate
                                                                          : x.LastContactDate.Value, DateTime.Today)*
                                                x.LeadPool.DecreaseLeadBy) <= 0 && !warmLeads
                                            )
                                       );

            predicate = predicate.Or(x => x.LeadPool.DecreaseByUnit == (int)DecreaseUnitTime.Week
                                       &&
                                       (
                                           (x.LastHeatValue - SqlFunctions.DateDiff("week", !x.LastContactDate.HasValue
                                                                      ? x.InitialContactDate
                                                                      : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) > 0 && warmLeads ||

                                            (x.LastHeatValue - SqlFunctions.DateDiff("week", !x.LastContactDate.HasValue
                                                                      ? x.InitialContactDate
                                                                      : x.LastContactDate.Value, DateTime.Today) *
                                            x.LeadPool.DecreaseLeadBy) <= 0 && !warmLeads
                                        )
                                   );

            predicate = predicate.Or(x => x.LeadPool.DecreaseByUnit == (int)DecreaseUnitTime.Month
                                       &&
                                       (
                                           (x.LastHeatValue - SqlFunctions.DateDiff("month", !x.LastContactDate.HasValue
                                                                      ? x.InitialContactDate
                                                                      : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) > 0 && warmLeads ||

                                            (x.LastHeatValue - SqlFunctions.DateDiff("month", !x.LastContactDate.HasValue
                                                                      ? x.InitialContactDate
                                                                      : x.LastContactDate.Value, DateTime.Today) *
                                            x.LeadPool.DecreaseLeadBy) <= 0 && !warmLeads
                                        )
                                   );

            var query = _activeLeads(ownerUserId)
                        .AsExpandable().Where(predicate);

            return query;
        }

Any ideas on how to improve this?

First of all.  Is _queryLeadsByHeat supposed to represent a method?  If so I would steer away from using underscore in it's method name unless that's your naming convention in which case I guess your stuck with it.  Underscore is traditionally mainly reserved for fields (if at all as there are large debates for this practice).

I don't have Visual studio in front of me so not sure if this will even compile (or is even possible) but my initial thought would be to try and consolidate the Predicates into one method.

Expression<Func<T, bool>> GetHeatCondition(DecreaseUnitTime period)
{
    string periodAsString = period.ToString();

    return predicate.Or(x => x.LeadPool.DecreaseByUnit == (int)period
                               &&
                               (
                                   (x.LastHeatValue - SqlFunctions.DateDiff(periodAsString, !x.LastContactDate.HasValue
                                                              ? x.InitialContactDate
                                                              : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) > 0 && warmLeads ||

                                    (x.LastHeatValue - SqlFunctions.DateDiff(periodAsString, !x.LastContactDate.HasValue
                                                              ? x.InitialContactDate
                                                              : x.LastContactDate.Value, DateTime.Today) *
                                    x.LeadPool.DecreaseLeadBy) <= 0 && !warmLeads
                                )
                           );
}

private IQueryable<Lead> QueryLeadsByHeat(int? ownerUserId, bool warmLeads)
{
    var predicate = PredicateBuilder.False<Lead>();
    predicate = predicate.Or(GetHeatCondition<Lead>(DecreaseUnitTime.Day));
    predicate = predicate.Or(GetHeatCondition<Lead>(DecreaseUnitTime.Month));
    predicate = predicate.Or(GetHeatCondition<Lead>(DecreaseUnitTime.Year));

    var query = _activeLeads(ownerUserId)
                        .AsExpandable().Where(predicate);

            return query;
}

I'm pretty sure that Linq query could be better optimized.  Have to think some more on that one...


Change return program I did an application that returns you quarters, dimes, nickels and pennies after you give the cost of the product and the money you gave. Can this be done any better? This seems like kind of messed up, and it got some repeated code parts.

Console.Write("Cost of the product -> ");
decimal costProduct = decimal.Parse(Console.ReadLine());

Console.Write("Money given -> ");
decimal moneyGiven = decimal.Parse(Console.ReadLine());

decimal change = moneyGiven - costProduct;

decimal quarters = 0, dimes = 0, nickels = 0, pennies = 0;

while(change >= 0.25m)
{
    quarters = Math.Truncate((change / 0.25m));
    change = change % 0.25m;
}

while(change >= 0.10m)
{
    dimes = Math.Truncate((change / 0.10m));
    change = change % 0.10m;
}

while (change >= 0.05m)
{
    nickels = Math.Truncate((change / 0.05m));
    change = change % 0.05m;
}

while (change >= 0.01m)
{
    pennies = Math.Truncate((change / 0.01m));
    change = change % 0.01m;
}

Console.WriteLine("{0} quarters, {1} dimes, {2} nickels, {3} pennies", quarters,
    dimes, nickels, pennies);

Your code and both other answers are good. However, I see a gap in the assumption here.

What if the list of available coins changes? This could be culture related (e.g. the Euro uses a €0.20 coin instead of the dollar's $0.25).
A similar issue could be encountered if you start factoring in the availability of change in your register (you can't give three quarters if you only have two)

To be fair, the second bullet point is not part of your current program. But if we solve the first bullet point, we have pretty much solved the second bullet point too (it requires minimal extra effort).

I'm not going to implement the second bullet point, but adding this feature should be relatively easy in my reworked example.

So far, the coin values (and the coin types) have been hard-coded:

Your code:

while(change >= 0.25m)

Danny's code:

decimal quarters = GetNumberOfCoins(ref change, 0.25m);

Denis' code:

private const decimal _quarterValue = 0.25m;

All of them share the same traits: coin values are hardcoded, and so is the list of available coins.

Even though the values themselves are easily changed, changing the available coins (e.g. quarters are decommissioned, or a new coin value is created) creates a bigger workload, because you have to change the calls.

Realistically, the available coins don't change all that often (it would be insanity to try and change this on a federal level).
However, as I mentioned before, if your program needs to be able to handle both Euros and US dollars, then the available coins does change.

So let's improve this.

public class CoinType
{
    public decimal Value { get; set; } //e.g. 0.25
    public string Name { get; set; }   //e.g. "quarter"
}

Note that you can add other properties here:

char CurrencySymbol = '$'
int AmountOfCoinsAvailable = 100

But for the sake of simplicity, we'll only use the value and a name for printing.

Both you and the answerers have already identified that a generalized method should be created to check coin values. I'll not elaborate on the same, because it would just repeat the other answers.

Let's assume the following method exists:

private int CalculateMaxCoins(CoinType coin, decimal remainingAmount);

The return value is the amount of coins that you can use. E.g. 0.80 can fit 3 quarters, so 3 is the return value.

Now, we need to create a list of coins. Note that I'm making it a list instead of a bunch of separate properties, so that the list of available coins can easily be changed.

List<CoinType> availableCoins_USD = new List<CoinType>()
{
    new CoinType() { Value = 0.25m, Name = "quarter" },
    new CoinType() { Value = 0.10m, Name = "dime" },
    new CoinType() { Value = 0.05m, Name = "nickel" },
    new CoinType() { Value = 0.01m, Name = "penny" }
};

This allow us to easily change it to EUR:

List<CoinType> availableCoins_EUR = new List<CoinType>()
{
    new CoinType() { Value = 2, Name = "€2" },
    new CoinType() { Value = 1, Name = "€1" },
    new CoinType() { Value = 0.5m, Name = "50 cent" },
    new CoinType() { Value = 0.2m, Name = "20 cent" },
    new CoinType() { Value = 0.10m, Name = "10 cent" },
    new CoinType() { Value = 0.05m, Name = "5 cent" },
    new CoinType() { Value = 0.02m, Name = "2 cent" },
    new CoinType() { Value = 0.01m, Name = "1 cent" }
};

All the subsequent code will work regardless of the list of coins (so long as the list is comprehensive). So let's assume we've encapsulated this is a method:

private List<CoinType> GetCoinsForLocalCurrency();

We've defined how to get the coins, we've assumed that the calculation (of how many coins of a given type should be used already exists) (cfr the other answers)

All that remains is the logic inbetween these two:

private static void PrintListOfChange(decimal totalChange)
{
    //Get the coins and order them by value (descending)
    var coinTypes = GetCoinsForLocalCurrency()
                    .OrderByDescending(x => x.Value)
                    .ToList();

    //This is where we construct our result
    Dictionary<CoinType, int> neededChange = new Dictionary<CoinType, int>();

    //Placeholder value for calculations
    decimal remainingChange = totalChange;

    foreach(var coinType in coinTypes)
    {
        int coinAmount = CalculateMaxCoins(coinType, remainingChange);

        //Do nothing if the result was 0
        if(coinAmount > 0)
        {
            //Add the results
            neededChange.Add(coinType, coinAmount);

            //See how much money is left to calculate
            remainingChange = remainingChange - (coinAmount * coinType.Value);

            //Minor performance gain:
            //  Stop processing if there is no money left to calculate.
            if (remainingChange == 0) break;
        }
    }

    //All that's left to do is print the values.

    string summaryOfChange = String.Join(
                                    " , ",
                                    neededChange.Select(x => $"{x.Key.Name} x{x.Value}") //e.g. "quarter x3"
                                );

    string fullmessage = $"{totalChange} in change equals: {summaryOfChange}";

    Console.WriteLine(fullmessage);
}

Ignoring the availability of a specific coin type, I think this is the most generalized approach. It requires a method to get the correct list of coins, but it works for any comprehensive list of coins that you provide.

I kept it a brief for the sake of example. There are extra features you could add:

1. What if the full total wasn't calculated in change?

e.g. you were trying to find change for $1.06 but you have no pennies in your list.

After the foreach, you can do:

if(remainingChange > 0)
{
    Console.WriteLine($"{remainingChange} cannot be given in change!");
}

2. There are no currency symbols.

This likely ties into how you define the "local" currency. It's nothing but an extra character to prepend to all values when printing the list.

3. There is no support for plural nouns.

E.g. if you want to be able to print things like 3 quarters (plural) but also 1 quarter (singular).

You would have to define two separate Name properties for a CoinType:

public string Name_Singular { get; set; }
public string Name_Plural { get; set; }

You might be tempted to add an "s" instead, but this falls apart in some cases:

Penny / Pennies
Most foreign currencies do not have a "given name" that is easily pluralized by adding an "s". Note the names I gave to the Euro coins, we lack a real name for the coin and simply list its value instead.


Create a LINQ Killer Sudoku Cage Solver When playing Killer Sudoku I find myself repeatedly writing stuff like this:

12/3
921
831
741
732
651
642
543

and then crossing out the combinations that include say 9, 7, and 6

IE I need a list of any 3 digits between 1 and 9 that add up to 12, excluding 9, 7, and 6 because they are already in the house.

So I wrote a Linq query to run in LinqPad that does this. However its pretty specific. Here is the implementation for 3 numbers:

var num=3;
var target=12;
var exceptions=new List<int>{9,7,6};

var List1 = new List<int>{1,2,3,4,5,6,7,8,9};
var List2 = new List<int>{1,2,3,4,5,6,7,8,9};
var List3 = new List<int>{1,2,3,4,5,6,7,8,9};

// Make a Cartesian join of the three lists
// Filter out the stuff that we want
// Sort the result from highest to lowest
var combo = (from l1 in List1
        from l2 in List2
        from l3 in List3        // Cartesian product
        where l1 > l2 && l2 > l3    // exclude duplicates
        && l1 + l2 + l3 == target   // add up to the target
        && !exceptions.Contains(l1) // exclude exceptions
        && !exceptions.Contains(l2)
        && !exceptions.Contains(l3)
        select new List<int>{l1, l2, l3})
        .OrderByDescending (c =>c[0] )
        .ThenByDescending (d => d[1])
        .ThenByDescending (e => e[2]);

Console.WriteLine(string.Format("{0}/{1}", target, num));
foreach(var item in combo){
for (var i=0; i< num;i++){
    Console.Write(item[i]);
}
Console.WriteLine();
}
Console.Write("excluding");
foreach(var i in exceptions){
    Console.Write(string.Format(" {0} ",i));
}

I have found it pretty useful but is there a better and more general way of implementing this?

Naming

Use camelCase for local variable names. And, use a meaningful name if possible.

//var List1 = new List<int>{1,2,3,4,5,6,7,8,9};
var validNumbers = new List<int>{1,2,3,4,5,6,7,8,9};

Use pluralized noun for variable of collection type.

//var combo = ... /*combo contains all possible combinations, not just one*/
var combos

Code

You don't need to enumerate the numbers 1 to 9. A Enumerable.Range will do the job.
The chain of !exceptions.Contains(x) is rather inefficient and redundant. You can avoid them by removing the exceptions from the start with IEnumerable.Except.
You can reuse the same list in your LINQ.
You can reuse the same name for your lambdas given they are not within the same parentheses.  (Not really a big problem)

Result :

var validNumbers = Enumerable.Range(1, 9).Except(exceptions);
var combos = (from a in validNumbers
              from b in validNumbers
              from b in validNumbers       // Cartesian product
              where a > b && b > c &&      // exclude duplicates
                    a + b + c == target    // add up to the target
              select new List<int>{ a, b , c})
             .OrderByDescending(x => x[0])
             .ThenByDescending(x => x[1])
             .ThenByDescending(x => x[2]);

In the last 2 blocks of the code, Console.Write was repeatedly called within the for loop. You can join them together with String.Join before printing it to the console.

Results :

foreach(var item in combos)
    Console.WriteLine(string.Join("", item));

Console.Write("excluding " + string.Join(" ", exceptions));

Final Code

This can be directly copied to LinqPad and ran.

void Main()
{
    string buffer;
    int target, elementCount;

    //get target
    Console.WriteLine(">> Target is ..?");

    while(!int.TryParse(buffer = Console.ReadLine(), out target))
        Console.WriteLine("\tInvalid input : {0}", buffer);
    Console.WriteLine(target);

    //get elementCount
    Console.WriteLine(">> Number of elements is ..?");

    while(!int.TryParse(buffer = Console.ReadLine(), out elementCount) ||
          1 > elementCount || elementCount > 6)
        Console.WriteLine("\tInvalid input : {0}", buffer);
    Console.WriteLine(elementCount);
    Console.WriteLine(/*Empty Line*/);

    //get exceptions
    var validNumbers = Enumerable.Range(1, 9);
    IEnumerable<int?> exceptions;
    Console.WriteLine(">> Exceptions are ..? (separated with comma like : 1,2,3)");

    while(!TryParseExceptions(buffer = Console.ReadLine(), out exceptions))
        Console.WriteLine("\tInvalid input : {0}", buffer);
    Console.WriteLine(string.Join(" ", exceptions.OrderBy(x => x)));

    Console.WriteLine(/*Empty Line*/);
    CalculateCombinations(target, elementCount, exceptions.Select(e => e.Value).Distinct());
}

int? ToNullableInt(string value)
{
    int number;
    return int.TryParse(value.Trim(), out number) ? (int?)number : null;
}
bool TryParseExceptions(string value, out IEnumerable<int?> exceptions)
{
    //const int MinValue = 1, MaxValue = 9;
    exceptions = value == ""
        ? Enumerable.Empty<int?>()
        : value.Split(',').Select(ToNullableInt);

    return exceptions.All(e => e.HasValue && (1 <= e.Value && e.Value <= 9)); //less verbose but magical...
    //return exceptions.All(e => e.HasValue && (MinValue <= e.Value && e.Value <= MaxValue));
}

// Define other methods and classes here
void CalculateCombinations(int target, int elementCount, IEnumerable<int> exceptions)
{
    var validNumbers = Enumerable.Range(1, 9).Except(exceptions);

    // Make a Cartesian join of the three lists
    // Filter out the stuff that we want
    // Sort the result from highest to lowest
    var combos = validNumbers.CartesianProduct(elementCount)     // Cartesian product
                            .Where(x => x.GreaterThanNext() &&   // exclude duplicates
                                        x.Sum(y => y) == target) // add up to the target
                            .OrderByDescending(x => x.First());  // sort from the 1st number to...

    for(int i = 1; i < elementCount; i++)
    {
                    ///i would be incremented when the ienumerable unfolds
        var index = i;
        combos = combos.ThenByDescending(x => x.ElementAt(index));   // ... the [n]th
    }

    Console.WriteLine(string.Format("{0}/{1}", target, elementCount));

    foreach(var item in combos)
        Console.WriteLine(string.Join("", item));

    Console.Write("excluding : " + string.Join(" ", exceptions.OrderBy(x => x)));
}

//credit : http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/
//slightly altered to reuse the same sequence

public static class Extensions
{
    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<T> sequence, int repeat)
    {
        IEnumerable<IEnumerable<T>> result =  new[] { Enumerable.Empty<T>() };

        for(int i = 0; i < repeat; i++)
        {
            // don't close over the loop variable (fixed in C# 5 BTW)
            var s = sequence;
            // recursive case: use SelectMany to build
            // the new product out of the old one
            result = from seq in result
                    from item in s
                    select seq.Concat(new[] {item});
        }

        return result;
    }

    public static bool GreaterThanNext(this IEnumerable<int> sequence)
    {
        if (sequence.Count() < 2) return true;

        var previous = int.MaxValue;
        foreach(var item in sequence)
            if(previous <= item)
                return false;
            else previous = item;

        return true;
    }
}

Example of result :

>> Target is ..?
25
>> Number of elements is ..?
4

>> Exceptions are ..? (separated with comma like : 1,2,3)
1

25/4
9862
9853
9763
9754
8764
excluding : 1


Converting between backend object and object suitable for JSON I wrote this method that does the job and passes the assertion tests for a large java backend project but I'm not all happy with the way it reads, perhaps you can tell me how to refactor and/or improve this method?

public Set<ProductOfferingJsonDto> getJsonProductOfferings() {
    Set<ProductOfferingJsonDto> set = new HashSet<ProductOfferingJsonDto>();
    ProductOfferingJsonDto pjson = null;
    Iterator iter = productOfferings.iterator();
    while(iter.hasNext()){
        ProductOfferingDto pdto = (ProductOfferingDto) iter.next();
        if(pdto instanceof BundledProductOfferingDto) {
            Set<ProductOfferingDto> tmp = ((BundledProductOfferingDto) pdto).getProductOfferings();
            Iterator piter = tmp.iterator();
            Set<ProductOfferingJsonDto> tmpset = new HashSet<ProductOfferingJsonDto>();
            while(piter.hasNext()){
                SimpleProductOfferingDto piterdto = (SimpleProductOfferingDto) piter.next();
                tmpset.add(new SimpleProductOfferingJsonDto(piterdto.getId(), piterdto.getName(), piterdto.getDescription(), piterdto.getStatus(),
                        piterdto.getBrand(), piterdto.getValidFor(),
                        piterdto.getProductSpecification(),
                        piterdto.getDescriptorId(), piterdto.getTags(), piterdto.getProductOfferingPrice()));
   }
            BundledProductOfferingDto bpod = (BundledProductOfferingDto) pdto;
            pjson = new BundledProductOfferingJsonDto(bpod.getId(), bpod.getName(), bpod.getDescription(), bpod.getStatus(),
                    bpod.getBrand(), bpod.getValidFor(),
                    tmpset,
                    bpod.getDescriptorId(), bpod.getTags(), bpod.getProductOfferingPrice());
        }
      if(pjson != null) {
        set.add((ProductOfferingJsonDto) pjson);
      }
    }
    return set;
}

I would move the construction of the JSON objects into factory methods like this:

public class BundledProductOfferingJsonDto
{
    ....
    public static BundledProductOfferingJsonDto fromDto(BundledProductOfferingDto dto, Set<ProductOfferingJsonDto> productOfferings)
    {
        return new BundledProductOfferingJsonDto(dto.getId(), dto.getName(), dto.getDescription(), dto.getStatus(),
                dto.getBrand(), dto.getValidFor(),
                productOfferings,
                dto.getDescriptorId(), dto.getTags(), dto.getProductOfferingPrice());
    }
}

Similar for SimpleProductOfferingJsonDto

Also, is there a reason why your are using the while loops with the iterators instead of for example for (ProductOfferingDto piter : tmp)?

The method could then read something like this:

public Set<ProductOfferingJsonDto> getJsonProductOfferings() {
    Set<ProductOfferingJsonDto> set = new HashSet<ProductOfferingJsonDto>();
    ProductOfferingJsonDto pjson = null;
    for (ProductOfferingDto pdto : productOfferings) {
        if (pdto instanceof BundledProductOfferingDto) {
            Set<ProductOfferingDto> tmp = ((BundledProductOfferingDto) pdto).getProductOfferings();
            Set<ProductOfferingJsonDto> tmpset = new HashSet<ProductOfferingJsonDto>();
            for (ProductOfferingDto piter : tmp) {
                SimpleProductOfferingDto piterdto = (SimpleProductOfferingDto)piter;
                tmpset.add(SimpleProductOfferingJsonDto.fromDto(piterdto));
            }
            BundledProductOfferingDto bpod = (BundledProductOfferingDto) pdto;
            BundledProductOfferingJsonDto pjson = BundledProductOfferingJsonDto.fromDto(bpod, tmpset));
            set.add(pjson);
        }
    }
    return set;
}


Query registry for installed software Hoping someone can help me out with the two aspects of my script that I think is causing the most performance hindrance. Recreating the Array $Result and using the Get-ItemProperty on each and every key to get the required information. Is there a better way to accomplish this task?

Function Get-SoftwareList {
    <#
    #>
    Param()

    New-Variable -Force -ErrorAction SilentlyContinue -Name Result   -Value @()
    New-Variable -Force -ErrorAction SilentlyContinue -Name Function -Value @{}
    $Function.Exclusions = (
        "Security Update for Windows",
        "Security Update for Microsoft",
        "Update for Windows",
        "Update for Microsoft",
        "Hotfix for Windows",
        "Update for Skype",
        "Security Update for Skype"
    )
    If([IntPtr]::Size -eq 8){
        $Function.OSArch='64-bit'
    } Else{
        $Function.OSArch='32-bit'
    }

    $Function.Registry = Get-Childitem -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
    IF ($Function.OSArch -EQ "64-bit") {
        $Function.Registry += Get-ChildItem -Path "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
    }

    ForEach ($Key in $Function.Registry) {
        $Key = Get-ItemProperty -Path Registry::$Key
        IF ($Key.DisplayName.length -NE 0) {
            ForEach ($Exclusion in $Function.Exclusions) {
                If ($Key.DisplayName.StartsWith($Exclusion) -EQ $True) {
                    $Skip = $True
                    Break
                } Else {
                    $Skip = $False
                }
            }
            IF ($Skip -EQ $False) {
                $Result += New-Object PSObject -Property @{
                    DisplayName     = $Key.DisplayName
                    Version         = $Key.DisplayVersion
                    UninstallString = $Key.UninstallString
                    Publisher       = $Key.Publisher
                    #ModifyPath      = $Key.ModifyPath
                    InstallDate     = $Key.InstallDate
                }
            }
        }
    }
    Return $Result
}

Finding a very quick/reliable solution was actually significantly harder than I was expecting but this is the best I can come up with. It lists about ~130 applications in about 22ms on my computer.

    Function Get-InstalledSoftware {
    Param (
        [Array]$Properties = @('DisplayName','DisplayVersion')
    )
    $Keys = "Software\Microsoft\Windows\CurrentVersion\Uninstall","SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
    $Result = New-Object -TypeName 'System.Collections.ArrayList'
    $BaseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$ENV:ComputerName)
    ForEach($Key in $Keys) {
        $RegKey = $BaseKey.OpenSubkey($key)
        If($RegKey -ne $null) {
            ForEach($subName in $RegKey.getsubkeynames()) {
                foreach($sub in $RegKey.opensubkey($subName)) {
                    [string]$Name = $sub.getvalue("displayname")
                    If ($Name.trim().Length -gt 0) {
                        $HashProperty = @{}
                        ForEach ($CurrentProperty in $Properties) {
                            $HashProperty.$CurrentProperty = $sub.GetValue($CurrentProperty)
                        }#End-ForEach
                        $Result.add([psCustomObject]$HashProperty)
                    }#End-IF
                }#End-ForEach
            }#End-Foreach
        }#End-IF
    }#End-ForEach
    $Result
}

The new script is not only significantly more flexible, but also significantly faster than previous solutions.

Measure-Command {
    for($i = 0; $i -lt 100; $i++) {
        Get-InstalledSoftware99 -Properties DisplayName,UninstallString,DisplayVersion
    }
}

Measure-Command {
    for($i = 0; $i -lt 100; $i++) {
        Get-SoftwareList
    }
}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 925
Ticks             : 9259570
TotalDays         : 1.07170949074074E-05
TotalHours        : 0.000257210277777778
TotalMinutes      : 0.0154326166666667
TotalSeconds      : 0.925957
TotalMilliseconds : 925.957

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 14
Milliseconds      : 695
Ticks             : 146959970
TotalDays         : 0.00017009255787037
TotalHours        : 0.00408222138888889
TotalMinutes      : 0.244933283333333
TotalSeconds      : 14.695997
TotalMilliseconds : 14695.997


Sometimes-sticky HTML element I am working on a sticky element that on certain point when the user scrolls down it turns into a relative element so it's not a sticky element anymore, only when the user scrolls to the top and passes over an specific element it turns again into a fixed/sticky element.

function Sticky($el){
    this.$el = $el;
    this.$stickyEl = this.$el.find('.sticky-bar-behavior');
    this.$noSticky = this.$el.find('.no-sticky');
    this.$whenSticky = this.$el.find('.when-sticky');
    this.shareStickyFooter();
    return this;
}

// this function is because I need check where is the scroll in order to
// see if the element should be fixed or relative
Sticky.prototype.toggleStickyOnInit = function($windowHeight, $windowPosition){
    var THIS = this;
    if(!($windowHeight >= $windowPosition)) {
        THIS.$el.addClass('position-relative');
        $('.when-sticky').show();
        $('.no-sticky').show();
    }
    return THIS;
}

Sticky.prototype.shareStickyFooter = function(){
    var THIS = this;
    var $windowHeight = $window.height();
    var $windowPosition = $('.sticky-bar-behavior').position().top;
    var $scrollTop = $(this).scrollTop();
    $window.on('scroll', function() {
        // THIS.toggleStickyOnInit($windowHeight, $windowPosition);
        if ($(this).scrollTop() + $windowHeight >= $windowPosition + 300) {
            requestAnimationFrame(function(){
                THIS.$el.removeClass('position-fixed');
                THIS.$el.addClass('position-relative');
                THIS.$noSticky.show();
                THIS.$whenSticky.hide();
            });
        } else if ($windowPosition >= $(this).scrollTop()) {
            requestAnimationFrame(function(){
                THIS.$el.removeClass('position-relative');
                THIS.$el.addClass('position-fixed');
                THIS.$noSticky.hide();
                THIS.$whenSticky.show();
            });
        }
    })

    return THIS;
};

At this point what I feel as if I am repeating some code.
Is there a better way to do is?

Since this functionality is heavily dependent on jQuery, you might consider making this into a jQuery plug-in rather than javascript (
Consider putting hard-coded class names and other configuration values (i.e. 300 value for window position comparison) into configuration to make this class more re-usable.
Don't use $ prefix on variables ($windowHeight,$windowPosition, etc.) that don't represent jQuery collections if you are attempting to adhere to a coding standard that prefixes jQuery collection-holding variables in this manner.
I don't know that either of the functions make sense in a static/prototype context, as each of the functions deals with the "state" of an individual control or set of control bound to the object.  This state should likely not be held on the prototype. You are actually calling the shareStickyFooter() function as one would an object constructor.  Is toggleStickyOnInit() even used? If not, it should be removed.
shareStickyFooter() is an oddly named function.  It looks to me like this function is simply defining scroll event handler. It doesn't "share" anything. attachScrollBehavior()?
Where is $window defined? If you are explicitly going to add a dependency to some global variable (which I assume is defined as $(window)), then you might consider passing that dependency in rather than just blindly relying on this being defined and available to this scope. I personally don't see great value in putting this in variable here at all.
I am not quite sure that the two different states that the control can seemingly be in are appropriately modeled.  Why do you have both sticky and non-sticky DOM elements shown in initialized state when it seems the intent is to only have one showing at a time?  Why does your scroll event handler have 3 possible outcomes (sticky/not sticky/?) vs. just two (sticky/not sticky)?
This code var $scrollTop = $(this).scrollTop(); seems ambiguous.  What do you expect this to be in this context?  I would think $(window).scrollTop() would be less ambiguous here.
Consider using $.toggle() and/or $.toggleClass() to consolidate code and pairing this with only doing toggle action when you cross the toggle "boundary". This will minimize re-rendering the DOM every single time a scroll happens. this of course means you would need to store some sort of variable on the current "state" of the component (sticky vs. non-sticky). This along with your other variables on positional information of the involved elements should likely exist on the object itself vs. object prototype.  This probably means only having a single class which provides incremental behavior for stickyness (i.e. change position) - one class to toggle on and off rather than changing between two classes.
Do you really need public visibility on all of your properties?

Why do this:

this.$el = $el;
this.$stickyEl = this.$el.find('.sticky-bar-behavior');
this.$noSticky = this.$el.find('.no-sticky');
this.$whenSticky = this.$el.find('.when-sticky');
this.shareStickyFooter();
return this;

Rather than this?

var $stickyEl = $el.find('.sticky-bar-behavior');
var $noSticky = $el.find('.no-sticky');
var $whenSticky = $el.find('.when-sticky');
init();
return this;

Would the class benefit at all from validation that various jQuery collections are valid (i.e. not empty)?  There is, of course, code size overhead for adding this, but it is something you might consider if you need to this class to be reusable in wider context.

Putting some of these thoughts together might yield code structure more like this:

function Sticky($el, config){
    // private variables
    var $stickyEl,
        $sticky,
        $noSticky,
        ...;

    // maybe we want public visibility to positioning or state information
    this.state = 'uninitialized';
    this.scrollTop;
    ...

    // constructor
    function init() {
        // not shown - perhaps validate passed collection $el and throw error if invalid
        // merge default and passed config values
        config = $.extend(this.defaultConfig, config);

        // populate your instance variables, also possibly validate
        $sticky = $el.find(config.stickyClass);
        ...

        // attach your scroll event handler
        $(window).on('scroll', onScroll);

        // perhaps some initial setup here like putting elements
        // into non-sticky state
        $el.toggleClass(config.stickyActiveClass, false);
        $sticky.toggle(false);
        $noSticky.toggle(true);
        this.state = 'nosticky';
    }

    // onScroll callback
    function onScroll() {
         var newState = 'nosticky';
         // not shown - calculate positional information
         if (/* sticky condition */) {
             newState = 'sticky';
         }
         // toggle state if needed
         if (this.state !== newState) {
             requestAnimationFrame(function(){
                 $el.toggleClass(config.stickyActiveClass);
                 $sticky.toggle();
                 $noSticky.toggle();
             });
             this.state = newState;
         }
    }

    // call constructor
    init();
    return this;
}

// set default configuration on prototype
Sticky.prototype.defaultConfig = {
    stickyActiveClass: 'sticky-active',
    ...
};


Testing whether a given string has unique characters Here is my code which tests whether a given string has unique characters. The function is_unique which does a linear search for each character in the string is \$O(n^2)\$ (if I am right). Is there any more efficient way of doing the same with more efficient DS that takes less time (or space)?

I know with some library functions it can be done more easily, such as len(set(strr)) == len(strr)

def is_unique(strr):
    """Without using any library functions"""
    def _contains(string, char):
        for c in string:
            if c == char: return True
        return False

    for index in range(len(strr)):
        if _contains(strr[:index], strr[index]): return False
    return True

def main():
    for string in ['abc', 'abcc', 'aabc']:
        print is_unique(string)

if __name__ == '__main__':
    main()

Edit 1 (Adds constraints)

Don't change the original string and memory used should be \$O(1)\$ hence sorting the string may not be the valid solution.

You can do it in linear time via frequency counting. Make an array that is indexable by characters and initialise it with 0. Run over the string, incrementing the frequency for each character until that results in a value greater than 1 or the string is exhausted. Done.

EXTENDED EXPLANATION

Here is the algorithm expressed in pseudo code, which makes it easy to assess its complexity:

var seen: array [char] of boolean

seen = false

for each c in string_to_be_tested
   if seen[c]
      return false    // string is not free duplicates
   seen[c] = true

return true           // no character occurs more than once

That is the algorithm as such. CodeYogi has already posted a short and succinct pythonic approximation of it (first as a post scriptum, later it was moved into the question body):

len(set(strr)) == len(strr)

This compares the cardinality of the set of characters contained in the string to its length.

The set contains each character at most once, regardless how often it was added. This means that the cardinality of the set can only be equal to the length of the string if each of the characters occurred exactly once. This is not an algorithm as such, it is a functional expression whose algorithmic complexity is more difficult to assess than that of the simpler - if more verbose - imperative pseudo code.

When I wrote the first paragraph of the answer I was thinking along the lines of its most natural/efficient expression, which is in terms of the operation BTS ('bit test and set', or _bittestandset() as a C intrinsic). Here is a rendering of the algorithm in C, for the usual null-terminated strings:

// allocation and zeroing of the bitmap elided - too ugly and not relevant

bts(bitmap, 0);  // pretend we've seen the terminator, so that we drop out at the end

while (!bts(bitmap, *s++))
   ;

return s[-1] == '\0';   // arrived at the end - unique, no duplicate characters

However, the BTS operation tends to be available only in assembly languages and C/C++; hence the description of the algorithm with an array of integer counts, which is much more widely available and which allows a compact approximation of the 'test and set' as 'increment and test':

if (++counts[string[i]] > 1)
   return false

That array is a (partial) frequency count, of course. It is possible to do it exactly like this in python, but that would do neither the algorithm nor the language any justice; it would be ugly and inefficient.


Transitions from one element to another I am implementing an automated help function in my code. It is simply a few bubbles that pop up with some text in them. I use d3 to select one bubble, display it for a short time, and then select another bubble and display that one. It works, but I don't like the shape the code is taking. Am I approaching this correctly?

d3.select("#targetYear-bubble")
    .transition().duration(2000)
    .style("opacity", 1)
    .transition().duration(2000)
        .style("opacity", 0)
        .each("end", function()
        {
            d3.select("#navTree-bubble").transition().duration(2000)
                .style("opacity", 1)
                .transition().duration(2000)
                .style("opacity", 0);
        })
        ;

This code displays 2 pop-up bubbles. It's manageable for now, but if I had a complex screen with 7 or 8 (or more) bubbles, this code would be much too complex.

Can someone make a suggestion for a better implementation of this?

Yes, if you chain with each then its has to be a recursive structure like that.

I like the mediator pattern for this...

var mediator = d3.dispatch('phase1', 'phase2'),

 bubbles = d3.selectAll(".bubbles")
   .style("opacity", 0.5);

 mediator.on('phase1', function(then) {

  d3.select(".bubble1")
  .transition().duration(2000)
    .style("opacity", 1)
    .transition().duration(2000)
   .style("opacity", 0)
  .each('end.phase1', function () { mediator[then]() })

 });

 mediator.on('phase2', function() {

  d3.select(".bubble2")
  .transition().duration(2000)
    .style("opacity", 1)
    .transition().duration(2000)
   .style("opacity", 0);

 });

 mediator.phase1('phase2');

bubble1

bubble2

It's much easier to automate


Retrieve Internet explorer proxy settings from the registry I just re-wrote a library to easily retrieve the proxy settings of Internet Explorer (self answered SO question: https://stackoverflow.com/q/41764614/3207406).

Git repository

GoDoc (with an example)

package ieproxy

import (
    "os"
    "strings"
    "sync"

    "golang.org/x/sys/windows/registry"
)

// StaticProxyConf containes the Windows configuration for static proxy
type StaticProxyConf struct {
    // Is the proxy active?
    Active bool
    // Proxy address for each scheme (http, https)
    // "" (empty string) is the fallback proxy
    Protocols map[string]string
    // Addresses not to be browsed via the proxy (comma-separated, like linux)
    NoProxy string
}

// AutomaticProxyConf contains the Windows configuration for automatic proxy
type AutomaticProxyConf struct {
    URL string // url of the .pac file
}

// WindowsProxyConf gathers the Windows configuration for proxy
type WindowsProxyConf struct {
    Static    StaticProxyConf    // static configuration
    Automatic AutomaticProxyConf // automatic configuration
}

type regeditValues struct {
    ProxyServer   string
    ProxyOverride string
    ProxyEnable   uint64
    AutoConfigURL string
}

var once sync.Once
var windowsProxyConf WindowsProxyConf

// GetConf retrieves the proxy configuration from the Windows Regedit
func getConf() WindowsProxyConf {
    once.Do(parseRegedit)
    return windowsProxyConf
}

// OverrideEnvWithStaticProxy writes new values to the
// http_proxy, https_proxy and no_proxy environment variables.
// The values are taken from the Windows Regedit (should be called in init() function)
func overrideEnvWithStaticProxy() {
    conf := getConf()
    if conf.Static.Active {
        for _, scheme := range []string{"http", "https"} {
            url, ok := conf.Static.Protocols[scheme]
            if !ok {
                url, ok = conf.Static.Protocols[""] // fallback conf
            }
            if ok {
                os.Setenv(scheme+"_proxy", url)
            }
        }
        if conf.Static.NoProxy != "" {
            os.Setenv("no_proxy", conf.Static.NoProxy)
        }
    }
}

func parseRegedit() {
    regedit, _ := readRegedit()

    protocol := make(map[string]string)
    for _, s := range strings.Split(regedit.ProxyServer, ";") {
        if s == "" {
            continue
        }
        pair := strings.SplitN(s, "=", 2)
        if len(pair) > 1 {
            protocol[pair[0]] = pair[1]
        } else {
            protocol[""] = pair[0]
        }
    }

    windowsProxyConf.Static = StaticProxyConf{
        Active:    regedit.ProxyEnable > 0,
        Protocols: protocol,
        NoProxy:   strings.Replace(regedit.ProxyOverride, ";", ",", -1), // to match linux style
    }
    windowsProxyConf.Automatic = AutomaticProxyConf{
        URL: regedit.AutoConfigURL,
    }
}

func readRegedit() (values regeditValues, err error) {
    k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.QUERY_VALUE)
    if err != nil {
        return
    }
    defer k.Close()

    values.ProxyServer, _, err = k.GetStringValue("ProxyServer")
    if err != nil && err != registry.ErrNotExist {
        return
    }
    values.ProxyOverride, _, err = k.GetStringValue("ProxyOverride")
    if err != nil && err != registry.ErrNotExist {
        return
    }

    values.ProxyEnable, _, err = k.GetIntegerValue("ProxyEnable")
    if err != nil && err != registry.ErrNotExist {
        return
    }

    values.AutoConfigURL, _, err = k.GetStringValue("AutoConfigURL")
    if err != nil && err != registry.ErrNotExist {
        return
    }
    err = nil
    return
}

I'm interested to know if the "go-style" can be improved and any other suggestions!

As is, the (my) code is really hard to test (needs actual registry modifications or env variable edition).

To ease the testing, one could change some functions:

func overrideEnvWithStaticProxy(conf ProxyConf, setenv envSetter) {
    ...
}
type envSetter func(string, string) error

func parseRegedit(regedit regeditValues) ProxyConf {
   ...
}

With this change overrideEnvWithStaticProxy and parseRegedit become self contained and can be easily tested!

This incurs a minor rewrite of getConf (which does only some plumbing):

func getConf() ProxyConf {
    once.Do(writeConf)
    return windowsProxyConf
}

func writeConf() {
    regedit, _ := readRegedit()
    windowsProxyConf = parseRegedit(regedit)
}


Calculate food company sales for the year I am working on a Python project where a food processing company is trying to calculate its total sales for the year. Python has to read from a text file where its divided into for categories split by commas.

The first category is the Type of product, which can be cereal, chocolate candy etc produced by the company.

The second category is the brand of the said product, for example, Kaptain Krunch for cereal or Coco Jam for chocolate. The third category is the sales for the last fiscal year (2014) and the last category is sales for this fiscal year(2015). Note that only sales for fiscal year 2015 are to be calculated. The 2014 has no use in this program but it is there.

Here is how the text file looks like, called product.txt:

  Cereal,Magic Balls,2200,2344

  Cereal,Kaptain Krunch,3300,3123

  Cereal,Coco Bongo,1800,2100

  Cereal,Sugar Munch,4355,6500

  Cereal,Oats n Barley,3299,5400

  Sugar Candy,Pop Rocks,546,982

  Sugar Candy,Lollipop,1233,1544

  Sugar Candy,Gingerbud,2344,2211

  Sugar Candy,Respur,1245,2211

  Chocolate,Coco Jam,3322,4300

  Chocolate,Larkspur,1600,2200

  Chocolate,Mighty Milk,1234,2235

  Chocolate,Almond Berry,998,1233

  Condiments,Peanut Butter,3500,3902

  Condiments,Hot Sauce,1234,1560

  Condiments,Jelly,346,544

  Condiments,Spread,2334,5644

What we are looking to do is to add the sales for Fiscal year 2015 by products and then the total sales for everything in 2015.

The output should look something like this in the written text file:

  Total sales for cereal in 2015 : {Insert total number here}

  Total sales for Sugar Candy in 2015 : {Insert total number here}

  Total sales for Chocolate in 2015 : {Insert total number here}

  Total sales for Condiments in 2015 : {Insert total number here}

  Total sales for the company in 2015: {Insert total for all the
  products sold in 2015}

Along with that, it should also print the grand total on the Python run screen in the IDE along with the text file:

  Total sales for the company in 2015: {Insert total for all the
  products sold in 2015}

Can I expand the program without using collections? Can I also expand the main function?

import collections

PRODUCT_FILE = "products.txt"
REPORT_FILE = "report.txt"

def main():
    # Easy way to get a dictionary where lookup defaults to 0
    categorycounts = collections.defaultdict(int)

    #open the files using with statements to ensure they're closed properly
    # without the need for an explicit call to close, even on exceptions
    with open(PRODUCT_FILE, newline='') as productfile,\
         open(REPORT_FILE, "w") as reportfile:
        rows = (line.rstrip().split(',')
        for line in productfile if line.rstrip())

        # Sum sales by product type letting csv parse
        # Filter removes empty rows for us; assume all other rows complete
        for category, brand, sales_lastyear, sales_thisyear in rows:
            categorycounts[category] += int(sales_thisyear)

        # Print categories in sorted order with their total sales
        for category, sales in sorted(categorycounts.items()):
            print('Total sales for', category, 'in 2015:', sales, file=reportfile)

        print('-'*80, file=reportfile) # Separator line between categories and total

        # Sum and print total sales to both file and screen
        totalsales = sum(categorycounts.values())
        print("Total sales for the company in 2015:", totalsales, file=reportfile)
        print("Total sales for the company in 2015:", totalsales)

if __name__ == '__main__':
    main()

Your code looks good, I have some minor suggestions:

Separate getting the data and outputting it

I would prefer reading something like this:

for product_info in product_informations(productfile):
    # Handle out-put of product_info

To separate concerns more clearly.

Use _ to signify un-used values

for category, brand, sales_lastyear, sales_thisyear in rows:
    categorycounts[category] += int(sales_thisyear)

The values brand and sales_lastyear are not used, so you do not need to give them a name:

for category, _, _, sales_thisyear in rows:
    categorycounts[category] += int(sales_thisyear)

Be explicit with file.write

If you want to write to a file, print will work just fine, but I suggest being the most explicit and using file.write.

This also helps separation of concerns because it forces formatting to be handled separately. (See str.format in the next paragraph)

Do not repeat yourself

    print("Total sales for the company in 2015:", totalsales, file=reportfile)
    print("Total sales for the company in 2015:", totalsales)

Only the output destination changes.

You can either save the message in a variable:

sales_info = "Total sales for the company in 2015:{}".format(totalsales)

reportfile.write(sales_info)
print(sales_info)

Or use a loop:

for destination in (sys.stdout, reportfile):
    print("Total sales for the company in 2015:{}".format(totalsales), file=destination)

.format is also preferred over str + str and print(x, y) for its extensibility and readibility.

Indent in generator expressions

It is weird to see a for at the start of a line as part of a generator comprehension, because it looks like a loop statement, some indenting will clarify that it is part of a generator comprehension:

rows = (line.rstrip().split(',')
            for line in productfile if line.rstrip())


Refactor a sequence of functions I have an http library in Ruby with a Response class, I have broken it down into smaller methods to avoid having a big intialize method, but then I end up with this:

 def initialize(res)
    @res = res
    @headers = Hash.new

    if res.empty?
      raise InvalidHttpResponse
    end

    split_data
    parse_headers
    set_size
    check_encoding
    set_code
  end

I don't feel well about calling function after function like that, any suggestions on how to improve this? Full code is at github.

Looking through your whole module it's apparent you've only had experience with imperative programming (it's full of side-effects, variable re-bounds, in-place updates, ...). I've already written on the topic (see this and this) so I won't expand here about the goodness of functional programming.

I'd write:

def initialize(response_string)
  @code = parse_code(response_string)
  raw_headers, @body = parse_data(response_string)
  @headers = parse_headers(raw_headers)
end

You get the idea, create parsing methods (or class methods, actually they won't need instance variables, they are pure functions) with inputs (arguments) and outputs that get assigned/bound to instance variables just once (not incidentally, that makes those methods easier to test).

On the other hand, there are already good network libraries for Ruby, what's the point of re-implementing them?

[EDIT] You asked for further advice. Ok, let's get a couple of methods of Response and refactor them:

def parse_data(raw_data)
  all_headers, body = raw_data.split("\r\n\r\n", 2)
  raise InvalidHttpResponse unless body && raw_data.start_with?("HTTP")
  raw_headers = all_headers.split("\r").drop(1)
  [raw_headers, body]
end

def decode_data(body)
  # You can use condition ? value1 : value2 for compactness
  data = if headers["Transfer-Encoding"] == "chunked"
    decode_chunked(body)
  else
    body
  end

  if headers["Content-Encoding"] == "gzip" && body.length > 0
    Zlib::GzipReader.new(StringIO.new(data)).read
  else
    data
  end
end

Ideas behind the refactor:

Put a space after a comma (more on style).
Don't reuse variables names (different values must have different names).
Don't update variables in-place.
Don't write explicit return.
Use if conditionals as expressions.
Use || && for boolean logic.
Put parentheses on calls (except on DSL code).


Implementing HTTP Strict-Transport-Security via MVC action filter HTTP Strict Transport Security (HSTS) is an opt-in security enhancement that is specified by a web application through the use of a special response header. Once a supported browser receives this header that browser will prevent any communications from being sent over HTTP to the specified domain and will instead send all communications over HTTPS.

Currently, there is no built in support for HSTS in MVC. So I decided to create an filter attribute that I can use as part of my application. There are a few questions about the code I have written which are:

I have used an action filter for granularity, but would a module/handler been better? If so, why?
Should the default of the attribute be to include sub domains, or exclude them (currently it excludes them)
The default timeout for the header is 300 seconds. This is a randomly picked arbitrary value. Is this value too much/too little?

The attribute is designed to compliment the RequireHttpsAttribute

    using System;
    using System.Globalization;
    using System.Web.Mvc;

    public class HSTSAttribute : ActionFilterAttribute
    {
            private const string HeaderName = "Strict-Transport-Security";
            private readonly string _headerValue;
            private readonly bool _includeSubDomains;

    public HSTSAttribute(bool includeSubDomains = false)
        : this(300, includeSubDomains)
    {
    }

    public HSTSAttribute(TimeSpan duration, bool includeSubDomains = false)
        : this(duration == null ? 300 : duration.Seconds, includeSubDomains)
    {
    }

    public HSTSAttribute(int duration, bool includeSubDomains = false)
    {
        if (duration <= 0)
        {
            throw new ArgumentException();
        }

        var includeSubDomainsSuffix = includeSubDomains ? String.Empty : "; includeSubDomains";
        _headerValue = String.Format("max-age={0}{1}", duration.ToString(CultureInfo.InvariantCulture)
                                , includeSubDomainsSuffix);
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        // HSTS headers should be sent via HTTPS responses only : http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14#section-7.2
        // They should also not be duplicated
        if (filterContext.HttpContext.Request.IsSecureConnection
                && filterContext.HttpContext.Response.Headers[HeaderName] == null)
        {
            filterContext.HttpContext.Response.AddHeader(HeaderName, _headerValue);
        }

        base.OnResultExecuted(filterContext);
    }
}

I would suggest setting the message on ArgumentException to your parameter name

e.g.

throw new ArgumentException("'duration' must be greater than 0");


C++ console progress display I just figured out how to do a building menu with a progression feature in c++ console application.

What this code does:

It simply offers you a choice to build a building and then prints
the progression like: 1% - 9% erasing and printing one number at a time (Which is the kind of the core feature that I struggled a lot with).

then prints "Building done".

I would like to have some thoughts and comments on how to:

Make this code simpler in any way .
Did someone else make the same feature and how did you implement it?
General thoughts on the code
How would you structure it?

std::string building;

std::cout << "-CONSTRUCTION MENU-" << std::endl << std::endl;

std::cout << "1. Barrack" << std::endl << std::endl;

std::cout << "Build: ";

std::cin >> building;

if (building == "1" || building == "Barrack" || building == "barrack")
{
    std::string sentence[10] = { "1%", "2%","3%", "4%", "5%", "6%", "7%", "8%", "9%" };

    for (int index = 0; sentence[index] != sentence[9]; index++)
    {
        std::cout << sentence[index] << std::flush;
        std::cout << "\b\b";
        Sleep(150);

        if (index == 8)
        {
            system("cls");
            std::cout << "Building done" << std::endl;
            system("pause");
            break;
        }
    }
}

There are several things you can do to improve this code.

First of all the code above isn't a valid C++ code. To run it you need to add:

#include <string>
#include <iostream>
#include <Windows.h>

int main()
{
    ... // your code posted above
}

Please next time you ask a question post the full code.

Then your Menu:

std::cout << "-CONSTRUCTION MENU-" << std::endl << std::endl;

std::cout << "1. Barrack" << std::endl << std::endl;

std::cout << "Build: ";

Consider writing it like this:

std::cout << "-CONSTRUCTION MENU-\n\n"
<< "1. Barrack\n\n"
<< "Build: ";

\n should be used instead of std::endl. The reason is std::endl
not only gives you a new line, it also does an expensive buffer
flushing operation which is rarely necessary.
No need to call std::cout several times after each other. Statements
can be chained.

Then your Percentage display:

std::string sentence[10] = { "1%", "2%","3%", "4%", "5%", "6%", "7%", "8%", "9%" };

for (int index = 0; sentence[index] != sentence[9]; index++)
{
    ...// statements inside
}

Several things are wrong here:

You are using a plain C array to hold the sentence variables. This is
very bad because a C array does not know about its size. Instead you
use the magic number '9' to finish iterating over the strings.
Please study the default C++ containers std::array or
std::vector. In this case I would go for array since you don't want
to add more values at run time.
The size is wrong. You declared space for 10 elements but only put
in 9.
sentence is a very bad name. You don't store sentences. Consider
using percentages instead.

Now we can write this instead:

std::array<std::string, 9> percentages = { "1%", "2%","3%", "4%", "5%", "6%", "7%", "8%", "9%" };

for (const auto& sentence : sentences)
{
    ...// statements inside
}

So the world is OK now? Not at all. You shouldn't use an array for numbers in the first place. Consider building the numbers in a loop instead:

for (int i = 1; i <= 9; ++i) {
    std::cout << std::to_string(i) << '%' << "\b\b";
    Sleep(150);
}

I removed the std::flush here since I don't see its purpose.

As a side hint it is a good practice to use ++i instead of i++. If you use objects later instead of ints you save an expensive copy.

Now we come to another dark chapter of your snippet. Your program is mixed with non-portable statements:

Sleep(150);

Consider using std facilities here:

#include <chrono>
#include <thread>

...

std::this_thread::sleep_for(std::chrono::milliseconds(150));

The big advantage here is that this is portable now.

The next candidate is:

system("pause");

Since you just want the program to wait with a message at the end you can do this:

std::cout << "Press any key...";
std::cin.get();

The last statement we get to is this:

system("cls");

No easy answer here. The fact is that the standard does not provide a portable solution here. You could wrap the statement in a function and make it portable for different platforms like this:

void clear_screen()
{
#if defined _WIN32
    std::system("cls");
#elif defined __unix__
    std::system("clear");
#elif defined (__APPLE__)
    std::system("clear");
#endif
}

We should also replace the

#include <windows.h>

with

#include <cstdlib>

So now also on Linux / MAC the clear should work.

As a last word. A function should only do one thing. You should separate the program in well defined parts. Here is my reworked solution with all the improvements already mentioned, dividing the program into parts:

#include <array>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <string>
#include <thread>

void clear_screen()
{
#if defined _WIN32
    std::system("cls");
#elif defined (__unix__)
    std::system("clear");
#elif defined (__APPLE__)
    std::system("clear");
#endif
}

std::string get_user_choice()
{
    std::string choice;
    std::cout << "-CONSTRUCTION MENU-\n\n"
        << "1. Barrack\n\n"
        << "Build: ";
    std::cin >> choice;
    return choice;
}

void print_progress(int start, int end)
{
    for (auto i = start; i <= end; ++i) {
        std::cout << std::to_string(i) << '%' << "\b\b";
        std::this_thread::sleep_for(std::chrono::milliseconds(150));
    }
}

void print_building_completed()
{
    clear_screen();
    std::cout << "Building done\n";
    std::cout << "Press any key...";
    std::cin.get();
}

int main()
{
    auto building = get_user_choice();
    if (building == "1" || building == "Barrack" || building == "barrack"){
        print_progress(0, 100);
        print_building_completed();
    }
}


Algorithm optimization on date calculation I need to calculate the calendar week of a given date. Constraints:

It should be properly calculated based on ISO 8601 if week starts on
Monday
It should calculate based on US standards if the week starts on
Sunday
It should be compact and fast, as the routine gets called very often
It should work even if the year start is not January (Fiscal Year starts on October for instance)

That's what I have currently:

Date.prototype.getWeek = function() { // ISO Week

    this.firstDay = 4;  // ISO 8601: Week with the first thursday which contains the 4th of January
    this.thursday = 4;  // 0 = Sunday OR Monday (if WeekStart = "M")

    if ( this.weekStart != 'M' )
    {
        this.firstDay = 1;  // switch to US norm: Week with the 1st of January
        this.thursday = 0;
    }

    // finding the date of the "thursday" in this week
    var donnerstag = function(datum, that) {
        var Do = new Date(datum.getFullYear(), datum.getMonth(),
                   datum.getDate() - datum.getDay() + that.thursday, 0, 0, 0);
        return Do;
    };

    // copy date, hourly times set to 0
    var Datum = new Date(this.getFullYear(),this.getMonth(),this.getDate(), 0, 0, 0);

    var DoDat = donnerstag(Datum, this);        // the date of the first week
    var kwjahr = DoDat.getFullYear();           // the year of that date

    // diff from there to this date
    var DoKW1 = donnerstag(new Date(kwjahr, this.FYStart, this.firstDay), this);
    //console.log(DoDat + " - " + DoKW1);

    // calculate the week
    var kw = Math.floor(1.5+(DoDat.getTime()-DoKW1.getTime())/86400000/7)

    // adjust overflow
    if ( kw < 1 )
        kw = 52 + kw;

    return kw;
};

Is there any more compact algorithm or can this be optimized in terms of performance?

In my experience, Moment.js is somewhat too heavy for this simple task. Did some profiling not too long ago and the library does too much movement for this task. Maybe it's for robustness/scalability/compatibility purposes, but nevertheless, still heavy.

Straight to the point, check out this blog post which demonstrates his method of getting the ISO week. It appends an additional getWeek method to the native Date object. I have used this in one of my projects as substitute for Moment.js's ISO week function.

Date.prototype.getWeek = function () {
    // Create a copy of this date object
    var target  = new Date(this.valueOf());

    // ISO week date weeks start on monday so correct the day number
    var dayNr   = (this.getDay() + 6) % 7;

    // ISO 8601 states that week 1 is the week with the first thursday of that year.
    // Set the target date to the thursday in the target week
    target.setDate(target.getDate() - dayNr + 3);

    // Store the millisecond value of the target date
    var firstThursday = target.valueOf();

    // Set the target to the first thursday of the year
    // First set the target to january first
    target.setMonth(0, 1);
    // Not a thursday? Correct the date to the next thursday
    if (target.getDay() != 4) target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);

    // The weeknumber is the number of weeks between the
    // first thursday of the year and the thursday in the target week
    return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000
}

As for your code:

I suggest putting it in plain English as much as you can. Readability will be an issue for reviewers who prefer verbose, purposeful naming.
Compared to the proposed code I have put up, your version creates way more Date objects (3 at my count). This could be a significant bottleneck if you are calling this function over a set of tabulated data. This is going to eat memory and CPU time.
"Cloning" a Date is as simple as var clone  = new Date(original.valueOf());. No need to individually call months, dates, etc. to setup the clone.


Interleave two sorted arrays To learn Rust, I tried to write a function that takes two sorted arrays of integers and interleaves them into one longer sorted array.

Is this approach ok? Have I made any mistakes?

fn main() {
    let a = [1, 3, 4, 4];
    let b = [0, 2, 5, 6];
    println!("{:?}", merge(&a, &b));
}

fn merge(list_a : &[i32; 4], list_b : &[i32; 4]) -> [i32; 8] {
    let mut merged_list: [i32; 8] = [0; 8];

    let mut idx = 0;
    let mut idx_b = 0;
    for a in list_a.iter() {
        while idx_b < list_b.len() && list_b[idx_b] < *a {
            merged_list[idx] = list_b[idx_b];
            idx_b +=1;
            idx += 1;
        }
        merged_list[idx] = *a;
        idx += 1;
    }

    for b in list_b[idx_b..].iter() {
        merged_list[idx] = *b;
        idx += 1;
    }
    println!("{:?}", merged_list);
    merged_list
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_merge() {
        let a = [1, 3, 3, 7];
        let b = [0, 4, 6, 8];
        assert_eq!(merge(&a, &b), [0, 1, 3, 3, 4, 6, 7, 8]);
    }
}

I can't see any obvious glaring bugs, but I can make a few suggestions to improve your initial baby steps, namely

Varying length arrays

Take your learning a step further and make the functions take arrays of varying lengths and see if your implementation still works. From the looks of it, it should still work without being heavily modified.

Generic array

I am not too familiar with Rust, but if it supports generics, then why don't you make the function generic so that it can take any two arrays of the same data type and merge them.

Conclusion

That is all. The code didn't really have a lot of ways things can go wrong because of the fixed size of the arrays. But you did a good job with the merge function which is what I think you were going for in the first place. See if you can implement the two suggestions above, then create another post


Hacker Rank: Array left rotation This code is to solve the Hacker Rank problem array left rotation.

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].

Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.

public static int[] rotLeft(int[] a, int d)
    {
        for (int intI = 0; intI < d; intI++)
        {
            int temp = 0;
            temp = a[0];
            for (int intK = 0; intK < a.Length; intK++)
            {
                a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
            }
        }
        return a;
    }
    static void Main(string[] args)
    {
        string[] nd = Console.ReadLine().Split(' ');
        int n = Convert.ToInt32(nd[0]);
        int d = Convert.ToInt32(nd[1]);
        int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
        int[] result = rotLeft(a, d);
        Console.WriteLine(string.Join(" ", result));
    }

This program works fine, but it takes too long with some examples. How can I improve it?

About naming:

intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.

A first simple optimization is that you can avoid the check if intK has reached the end:

  a.Length - 1 == intK ?

Instead you can just iterate up to a.Length - 1 and then append temp at the end:

public static int[] rotLeft(int[] a, int d)
{
  for (int intI = 0; intI < d; intI++)
  {
    int temp = a[0];

    for (int intK = 0; intK < a.Length - 1; intK++)
    {
      a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
    }

    a[a.Length - 1] = temp;
  }

  return a;
}

Next step is to consider the math:

a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK

and in the same way:

a.Length - (a.Length - (intK + 1)) = intK + 1

So you could write:

public static int[] rotLeft(int[] a, int d)
{
  for (int intI = 0; intI < d; intI++)
  {
    int temp = a[0];

    for (int intK = 0; intK < a.Length - 1; intK++)
    {
      a[intK] = a[intK + 1];
    }

    a[a.Length - 1] = temp;
  }

  return a;
}

But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:

public static int[] rotLeft(int[] a, int d)
{
  int[] temp = new int[d];

  for (int i = 0; i < d; i++)
    temp[i] = a[i];

  for (int i = d; i < a.Length; i++)
  {
    a[i - d] = a[i];
  }

  for (int i = 0; i < d; i++)
    a[a.Length - d + i] = temp[i];

  return a;
}

Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":

public static int[] rotLeft(int[] a, int d)
{
  int[] result = new int[a.Length];

  for (int i = d; i < a.Length; i++)
  {
    result[i - d] = a[i];
  }

  for (int j = 0; j < d; j++)
  {
    result[a.Length - d + j] = a[j];
  }

  return result;
}

If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.


Finding the sub-array with maximum sum - my slow approach I decided to give the maximum sub-array sum problem an interesting go, however I will assure you that it doesn't perform well, and that I would never put this in production.

I'd like a review on this, if possible, it would be cool to see the running time, I'm sure it's upper bounded by at most \$O(n^3)\$, but it may actually be less:

public class FindMaximumSubArraySumProblem extends Problem<int[]> {
    private static final int[][] DATA = {
        {-1},
        {1},
        {-5, 1, -3, 7, -1, 2, 1, -4, 6},
        {-5, 1, -3, 7, -1, 2, 1, -6, 5},
        {-5, 6, -3, -2, 7, -5, 2, 1, -7, 6},
        {-5, -2, -1, -4, -7},
        {4, 1, 1, 4, -4, 10, -4, 10, 3, -3, -9, -8, 2, -6, -6, -5, -1, -7, 7, 8},
        {4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1 },
//        buildRandom(1000, -10, 100),
//        buildRandom(10000, -10, 100),
//        buildRandom(10000, -1, 10000)
    };

    private static int[] buildRandom(int size, int min, int max) {
        return new Random().ints(size, min, max).toArray();
    }

    public FindMaximumSubArraySumProblem() {
        super("Find Maximum Sub-array Problem", 1000, 10000);
    }

    @Override
    public String getResult() {
        return Arrays.toString(execute());
    }

    @Override
    public int[] execute() {
        return Arrays.stream(DATA).mapToInt(this::computeMaxSum).toArray();
    }

    private int computeMaxSum(final int[] array) {
        return IntStream.range(0, array.length)
                .map(i -> IntStream.range(i, array.length)
                        .map(j -> Arrays.stream(array)
                                .skip(i)
                                .limit(j - i + 1)
                                .sum()
                        )
                        .max()
                        .orElse(0)
                )
                .max()
                .orElse(0);
    }
}

The method to look at is computeMaxSum:

private int computeMaxSum(final int[] array) {
    return IntStream.range(0, array.length)
            .map(i -> IntStream.range(i, array.length)
                    .map(j -> Arrays.stream(array)
                            .skip(i)
                            .limit(j - i + 1)
                            .sum()
                    )
                    .max()
                    .orElse(0)
            )
            .max()
            .orElse(0);
}

Results are:

Find Maximum Sub-array Problem => [-1, 1, 11, 9, 8, -1, 25, 28] (hot 0,09256ms - cold 0,132ms (total 1028,825ms))

You code :

private static int[] buildRandom(int size, int min, int max) {
    return new Random().ints(size, min, max).toArray();
}

I think that doing new Random several times, will reduce the "randomness" of the output. You can read that Stack Overflow question for more information. The idea is to remove the new Random() and use the same instance to produce several output. I would suggest to have an instance of Random in your class FindMaximumSubArraySumProblem but then does it make sense to have it ? Not really. So this method look kind of odd in your class. You could move it in his own helper class where it would make more sense, and then extract an instance of Random to increase randomness.


Reorganizing app.js to put related initialization steps together This is my app.js:

'use strict';
global.config = require('./config/environment/config');
global.i18n = require('./config/locales/config');

var express = require('express');
var app = express();

app.locals = global.config;

var passport = require('passport');
var session = require('express-session');
var load = require('express-load');
var flash = require('express-flash');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

app.set('views', path.join(__dirname, 'views'))
    .set('view engine', global.config.site.html.engine)
    .set('port', process.env.PORT || 3000)
    .set('env', process.env.NODE_ENV || 'development')
    .set('ip', process.env.IP || "0.0.0.0")

app.use(favicon(__dirname + '/assets/favicon.ico'))
    .use(logger('dev'))
    .use(bodyParser.json())
    .use(bodyParser.urlencoded({ extended: false }))
    .use(flash())
    .use(cookieParser())
    .use(express.static(path.join(__dirname, 'assets')))
    .use(session({ secret: 'keyboard cat' }))
    .use(passport.initialize())
    .use(passport.session());

var middlewares = require('./middlewares/config')(app);

load('models')
    .then('controllers')
    .then('routes')
    .into(app);

var prototypes = require('./helpers/prototypes');

mongoose.connect('mongodb://' + global.config.db.credentials + '@' + global.config.db.url + '/' + global.config.db.name, function(req, res) {
    console.log('db ok');
});

module.exports = app;

One aspect that annoys me is that I would prefer to have all the require() calls together.  However, if I move middlewares and prototypes before app.set(), the code will break.  Is there a better way to organize this code?

You can always move the require() call for middlewares up. You're not doing anything with the returned value from calling it on app.

var middlewares = require('./middlewares/config');

app.set(.....)

app.use(.....)

middlewares(app)

I'm assuming prototypes does some hacks with the global namespace. If so, then there's not much you can do about it. That's not really good practice though.


Convert list of parameters to a string that can be invoked My PowerShell scripting skills are pretty poor, but I've managed to hobble together got this script:

function Create-Process() {
    param([string] $fileName, [string] $arguments)

    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.FileName = $fileName
    $pinfo.Arguments = $arguments

    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo

    return $p
}

function Pack {
    param(
        [string] $nuspec,

        [string] $OutputDirectory,

        [string] $BasePath,

        [ValidateSet("normal", "quiet", "detailed", IgnoreCase = $true)]
        [string] $Verbosity,

        [switch] $Symbols
    )
    # format parameters for NuGet.exe
    If ($BasePath) {
        $basePathParam = "-BasePath ""$BasePath"""
    }
    If ($OutputDirectory) {
        $outputDirParam = "-OutputDirectory ""$BasePath"""
    }
    If ($Verbosity) {
        $verbosityParam = "-Verbosity $Verbosity"
    }
    If ($Symbols) {
        $symbolsParam = "-Symbols"
    }

    Write-Log "Creating package..." -ForegroundColor Green
    $packageTask = Create-Process .\NuGet.exe ("pack $nuspec $basePathParam $outputDirParam $verbosityParam $symbolsParam")
    $packageTask.Start() | Out-Null
    $packageTask.WaitForExit()

    $output = ($packageTask.StandardOutput.ReadToEnd() -Split '[\r\n]') |? {$_}
    $error = (($packageTask.StandardError.ReadToEnd() -Split '[\r\n]') |? {$_})
    Write-Log $output
    Write-Log $error Error

    $global:ExitCode = $packageTask.ExitCode
}

So that I can call it elsewhere like this:

Pack .\Package.nuspec -BasePath $TargetDir -OutputDirectory $TargetDir -Verbosity Detailed

How can I clean up the process for formatting the arguments string? It seems pretty ugly at the moment, and if I have to add any more parameters, it's just going to get uglier. Is there an easy way to convert a list of parameters to a string that's suitable for invoking another function?

Note: Simply passing in the parameters as a single string (e.g. Pack .\Package.nuspec "-Verbosity Detailed") doesn't really solve my issue, it just moves it back one step. I'd like to create the string within Pack itself.

Here's what I've been able to come up with so far. It could probably be improved further.

function Pack {
    param(
        [Parameter(Mandatory=$true)]
        [string] $nuspec,

        [string] $OutputDirectory,

        [string] $BasePath,

        [ValidateSet("normal", "quiet", "detailed", IgnoreCase = $true)]
        [string] $Verbosity,

        [switch] $Symbols
    )

    # these parameters are passed as name - value pairs
    $named = @('OutputDirectory', 'BasePath', 'Verbosity')

    # these parameters are passed as switches
    $keyed = @('Symbols')

    $p = $PSBoundParameters
    Write-Log "Creating package..." -ForegroundColor Green
    $output = Invoke-Command {
            .\NuGet.exe "pack" $nuspec ($p.Keys | foreach {
                If ($named -contains $_) { "-$_", $p[$_] }
                ElseIf ($keyed -contains $_) { "-$_" }
            })
        } -ErrorVariable error

    Write-Log $output
    Write-Log $error Error
    Write-Log " "

    $global:ExitCode = $LastExitCode
}


Is this the way of truncating the fractional part of a BigDecimal when its scale is zero in Java? I need to remove the fractional part of a BigDecimal value when its scale has a value of zero. For example,

BigDecimal value = new BigDecimal("12.00").setScale(2, RoundingMode.HALF_UP);

It would assign 12.00. I want it to assign only 12 to value in such cases.

BigDecimal value = new BigDecimal("12.000000").setScale(2, RoundingMode.HALF_UP);

should assign 12,

BigDecimal value = new BigDecimal("12.0001").setScale(2, RoundingMode.HALF_UP);

should assign 12.

BigDecimal value = new BigDecimal("12.0051").setScale(2, RoundingMode.HALF_UP);

should assign12.01

BigDecimal value = new BigDecimal("12.99").setScale(2, RoundingMode.HALF_UP);

should assign 12.99.

BigDecimal value = new BigDecimal("12.999").setScale(2, RoundingMode.HALF_UP);

should assign13

BigDecimal value = new BigDecimal("12.3456").setScale(2, RoundingMode.HALF_UP);

should assign 12.35 and alike.

I have this question on StackOverflow.

For this to be so, I'm doing the following.

String text="123.008";
BigDecimal bigDecimal=new BigDecimal(text);

if(bigDecimal.scale()>2)
{
    bigDecimal=new BigDecimal(text).setScale(2, RoundingMode.HALF_UP);
}

if(bigDecimal.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO)==0)
{
    bigDecimal=new BigDecimal(text).setScale(0, BigDecimal.ROUND_HALF_UP);
}

System.out.println("bigDecimal = "+bigDecimal);

It's just as an example. Is there a better way to do this?

Is there a better way to do this?

Yes, stripTrailingZeros().

To check your tests:

public static void main(final String[] args) {
    check(truncate("12.000000"), "12");
    check(truncate("12.0001"), "12");
    check(truncate("12.0051"), "12.01");
    check(truncate("12.99"), "12.99");
    check(truncate("12.999"), "13");
    check(truncate("12.3456"), "12.35");
    System.out.println("if we see this message without exceptions, everything is ok");
}

private static BigDecimal truncate(final String text) {
    BigDecimal bigDecimal = new BigDecimal(text);
    if (bigDecimal.scale() > 2)
        bigDecimal = new BigDecimal(text).setScale(2, RoundingMode.HALF_UP);
    return bigDecimal.stripTrailingZeros();
}

private static void check(final BigDecimal bigDecimal, final String string) {
    if (!bigDecimal.toString().equals(string))
        throw new IllegalStateException("not equal: " + bigDecimal + " and " + string);

}

output:

  if we see this message without exceptions, everything is ok


Don't include root directory in HTML tree I've written a function to create an HTML tree from JSON.

async function traverseTree (list, node) {
  const li = document.createElement('li')
  if (node.kids) {
    const
      ul = document.createElement('ul'),
      span = document.createElement('span')
    span.innerText = node.name
    li.appendChild(span)
    li.appendChild(ul)
    list.appendChild(li)
    for (const kid of node.kids) {
      traverse(ul, kid)
    }
    return list
  }
  li.innerText = node.name
  list.appendChild(li)
  return list
}

;(async function(){
  const
    tree = await readJson('./tree.json'),
    list = document.createElement('ul'),
    output = await traverseTree(list, tree)
  console.log(output)
})()

The issue is that I don't want to display the root node in the HTML tree since it is already displayed elsewhere, therefore I modified the code to exclude it.

async function traverseTree (list, node, isNotRoot) { // additional parameter
  const li = document.createElement('li')
  if (node.kids) {
    let ul = list                                     // now let
    if (isNotRoot) {                                  // additional conditional
      const span = document.createElement('span')
      ul = document.createElement('ul')               // additional assignment of value
      span.innerText = node.name
      li.appendChild(span)
      li.appendChild(ul)
      list.appendChild(li)
    }
    for (const kid of node.kids) {
      traverseTree(ul, kid, true)                     // additional argument
    }
    return list
  }
  li.innerText = node.name
  list.appendChild(li)
  return list
}

I'm wondering if there is a better, cleaner way to go about this?

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

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

function renderTree(json) {

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

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

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

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

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

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


Python username and password program Can the following code be simplified? I think that the program that I have created is very excessive and quite slow. The program runs fine, but I would like to understand if this could actually be programmed better.

I have commented on every line of the code. Any kind of feedback on the program will be great, as I have only been programming for a couple of weeks now.

# Python 3.4.3. Using MacOS (Version 10.12.5)
# Username and Password...
# The programs purpose: A user must enter the correct username and password for a site called FaceSnap...
# The correct username is elmo and the correct password is blue.

userName = input("Hello! Welcome to FaceSnap! \n\nUsername: ") #Ask's the User for Username input
password = input("Password: ") # Ask's the user for their password

count = 0 # Create a variable, to ensure the user has limited attempts at entering their correct username and password
count += 1 # The user has already had one attempt above, therefore count has been incremented by 1 already.

while userName == userName and password == password: # The Input will always lead to this while loop, so we can see if their username and password is wrong or correct.

    if count == 3: # Counter, to make sure the user only gets a limited number (3)of attempts
        print("\nThree Username and Password Attempts used. Goodbye") # Lets the user know they have reached their limit
        break # Leave the Loop and the whole program

    elif userName == 'elmo' and password == 'blue': # The userName and password is equal to 'elmo' and 'blue', which is correct, they can enter FaceSnap!
        print("Welcome! ") # Welcomes the User, the username and password is correct
        break # Leave the loop and the whole program as the username and passowrd is correct

    elif userName != 'elmo' and password != 'blue': # The userName and password is NOT equal to 'elmo' and 'blue', the user cannot enter FaceSnap
        print("Your Username and Password is wrong!") # Lets the user know that the Username and password entered is wrong.
        userName = input("\n\nUsername: ") # Requests the user to have another attempt at entering their correct username
        password = input("Password: ") # Requests the user to have another attempt at entering their correct password
        count += 1 # Increments the count by 1
        continue # Continue, as the user hasn't managed to get their username and password correct yet

    elif userName == 'elmo' and password != 'blue': # The userName is equal to 'elmo', but password is NOT equal to 'blue', the user cannot enter FaceSnap
        print("Your Password is wrong!") # Lets the user know that their password is wrong
        userName = input("\n\nUsername: ") # Requests the user to have another attempt at entering their correct username
        password = input("Password: ") # Requests the user to have another attempt at entering their correct password
        count += 1 # increments the count by 1
        continue # Continue, as the user hasn't managed to get their username and password correct yet

    elif userName != 'elmo' and password == 'blue': # The userName is NOT equal to 'elmo', however password is equal to 'blue', the user cannot enter FaceSnap
        print("Your Username is wrong!") # Lets the user know that their username is wrong
        userName = input("\n\nUsername: ") # Requests the user to have another attempt at entering their correct username
        password = input("Password: ") # Requests the user to have another attempt at entering their correct password
        count += 1 # Increments the count by 1
        continue # Continue, as the user hasn't managed to get their username and password correct yet

A few points:

You can simplify the if loop by using the else condition.
Getting input should be at the beginning of the while loop, because it makes more logical sense to put it there. It's what happens every time you restart.
You can use the simple condition of True for your while loop.
You don't need the continue keyword, as it is at the end of your loop.

count = 0
while True:
    userName = input("Hello! Welcome to FaceSnap! \n\nUsername: ")
    password = input("Password: ")
    count += 1
    if count == 3:
        #tells user bye
        break #exit
    else:
        if userName == 'elmo' and password == 'blue':
            #let them in
            break #they are in, exit loop
        else:
            #tell them it is wrong and have them retry, stay in loop


Optimize calculation of distances between pairs of points I was trying to solve a challenge. The execution time should not exceed 5s, but for some value my code took longer. I want to know if I can optimize my code for performance.

public class Solution {
    int n;long k;int count=0;
    public static void main(String[] args) {
        new Solution().readInput();

}
public void readInput(){
    try {
        BufferedReader k=new BufferedReader(new InputStreamReader(new FileInputStream("/home/tittanium/NetBeansProjects/HackerRank/src/input.txt")));
        parseNK(k.readLine());
        readAndParse(k.readLine());
        System.out.println(count);
    } catch (IOException ex) {
        Logger.getLogger(Solution.class.getName()).log(Level.SEVERE, null, ex);
    }

}
int cities[];
public void readAndParse(String line){
    int i1=0;
    cities=new int[n];
    StringTokenizer st = new StringTokenizer(line," ");

    while (st.hasMoreElements()) {
         cities[i1]=Integer.parseInt(st.nextToken());
         i1++;
    }
    for(int i=0;i<n;i++){
        final int x=i;
            new Runnable() {
                @Override
                public void run() {
                    for(int j=x;j<n;j++){
                        final int a=cities[x];
                        final int b=cities[j];
                        count = (a>b ? a-b : b-a) == k ? count+1 : count;
                    }
                }
            }.run();
        }
}

public void parseNK(String line){
    n= Integer.parseInt(line.split(" ")[0]);
    k= Integer.parseInt(line.split(" ")[1]);
}

}

This question is trying to solve a problem.  I want to know if any changes can be made to make the program run faster.
This is what I am trying to complete. challenge

What exactly your code does? It is not obvious, maybe you should name your variables better. Specially count = (a>b ? a-b : b-a) == k ? count+1 : count;
What a anb b is? count of what?

Instead of splitting line twice. Split it once and reuse the array. It also reduce count of space literal used.

String[] splittedLine = line.split(" ");
n= Integer.parseInt(splittedLine[0]);
    k= Integer.parseInt(splittedLine[1]);

And you are trying to use thread but you are not starting any. You are just wraping your implementation in Runnable object. See http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html for Thread useage examples.
Maybe you dont need threads at all, but i cant tell without knowing what exactly you are trying to solve. Running many threads may result into slower code because of switching from one thread to another and their creating take some time.


Loading attributes of cars and orders from JSON I am creating an application that deals with cars and orders.

A order contains a car and other information (BUYER, OWNER, ...), which constructs an orderObject.

A car has around 80 different attributes (TYP_WHEEL, TYP_DOOR, QUANTITY_WHEELS, ...) for the different car-parts.

I get the car-attributes and their values from a JSON string and put them into a map named allCarAttributes.

The JSON has this structure:

result:
    data[]:
        characteristics_0[]: …
            …
        characteristics_1[]: …
            …
            …
            …
        characteristics_N[]: …

Each characteristics-array contains some attributes:

"result": {
    "data": [
        {
            "characteristics": [
                {
                    "description": "Car ceiling color",
                    "id": "COL_CAR_CEILING",
                    "value": "F8",
                    "valueDescription": "F8 - White"
                },
                {
                    "description": "Color Car Finishes",
                    "id": "COL_CAR_ACCESSORIES",
                    "value": "T",
                    "valueDescription": "ST- Stainless Steel"
                },
                {
                    "description": "Car flooring color",
                    "id": "COL_CAR_FLOORING",
                    "value": "RD10",
                    "valueDescription": "RD10, grey"
                },
                (...)

Then I go through this map and based on the attribute name I set the respective value in the orderObject.

My problem:
Since the methods to set the values in the orderObject each have different names, I am not able to find a more efficient way than using a switch-case with 80 cases.

for (Map.Entry<String, String> attribute : allCarAttributes.entrySet()) {

        switch (attribute.getKey()) {
        case "TYP_DOOR":
            orderObject.setDoor(attribute.getValue());
            break;
        case "TYP_WHEEL":
            orderObject.setWheelType(attribute.getValue());
            break;
        case "QANTITY_WHEELS":
            orderObject.setWheelNumber(attribute.getValue());
            break;

        (...)

        default:
            break;
        }
    }

The orderObject-class simply has several fields and setters/getters for them:

private String car_width;
private String car_depth;
private String car_height;
private String car_weight;
(...)

public String getCar_width() {
    return car_width;
}

public void setCar_width(String car_width) {
    this.car_width = car_width;
}

How can I get rid of this huge switch-case?

Should I get rid of it at all? The switch-case works fine as it is, it is just very long and ugly.

This is the typical problem the relational community (relational databases) answers with OR-Mappings. As we do not have a relational datastructure more an object structure the mapping impedance is less but it remains.

But as we have to do a mapping it is not the question IF but the question WHERE the mapping is neccessary. Finally you have ALWAYS a big switch-case-statement. It may not be obvious and maybe it is not done all by yourself but there is no way around. You cannot escape the mapping but you can get help with it.

A pragmatic way would be to use the "org.json" API, Here is the Maven dependency:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>1.5-20090211</version>
</dependency>

With this library your mapping will be a little be easier. You can parse the json string:

JSONObject carInfoAsJsonObject = new JSONObject(jsonString);

Then you can wrapp this JSONObject into your own object and have the getters returning their values directly from the JSONObject:

class OrderObject {
    public String getCar_width() {
        return carInfoAsJsonObject.getString("CAR_WIDTH");
    }
}

Here you do not have a switch-case have you? Of course you have. But it is hidden in the structure we chose and not formulated with the JAVA language element "switch-case".

Another way is to let a library make the mapping decision. A good library is "Jackson". Here is the Maven dependency:

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

The Jackson way is "mapping by name"-convention. Your keys must be named like the attributes of your JAVA Object that should follow the bean convention.

The central clas is the ObjectMapper you have to instantiate:

ObjectMapper mapper = new ObjectMapper();

Then you may have the OrderObject attribute names synchronized:

class OrderObject {
    private String CAR_WIDTH;
    // getter and setter
}

After that you can instantiate an object of the type OrderObject:

OrderObject orderObject = objectMapper.readValue(carInfoAsJsonString, OrderObject.class);