texts:
I am solving the "Point where max intervals overlap" problem on geeks for geeks, https://www.geeksforgeeks.org/find-the-point-where-maximum-intervals-overlap/.
Following the solution in the article, I used two lists to store start and end times of the intervals. This is my solution in Python:

def maxIntervalOverlap(intervals):

    # break intervals into two lists
    first = lambda x: x[0]
    end = lambda x: x[1]

    enter = list(map(first, intervals))
    exit = list(map(end, intervals))

    # sort lists
    enter.sort()
    exit.sort()

    i = 1
    j = 0
    time = enter[0]

    n = len(enter)

    max_guests = 1
    guests_in = 1

    # process events in sorted order
    while i < n and j < n:

        # next event is arrival, increment count of guests
        if enter[i] <= exit[j]:

            guests_in += 1

            if guests_in > max_guests:
                max_guests = guests_in
                time = enter[i]

            i += 1

        else:
            guests_in -= 1
            j += 1

    print(f"Point where maximum number of intervals overlap is {time}")

and below is a test case

intervals = [[1, 4], [2, 5], [10, 12], [5, 9], [5, 12]]
maxIntervalOverlap(intervals)

How can I solve this problem without having to create the two extra lists ?


texts: Best way to handle repetitive error code or return value

texts:
I have a wrapper which interacts with a third party component. In Each function i am performing the operation if it the component is initialized.

I have other function to check the errorCode and component initialization check.

Is this right way to do this? I am not happy with the readability of this code. Help me improving this code.

Thanks in advance.

Void Operation1 (parameter someInput)
{
    int errorCode= 0;
    if (Initialized)
    {
        errorCode = ThirdPartyComponent.Operation1(someInput);
    }

     CheckErrorCodeAndShowError ("Operation1 with someInput failed", returnValue);
}

Void Operation2 (parameter someInput)
{
    int errorCode= 0;
    if (Initialized)
    {
        errorCode = ThirdPartyComponent.Operation2(someInput);
    }

    CheckErrorCodeAndShowError ("Operation2 with someInput failed", returnValue);
}

Void CheckErrorCodeAndShowError (String errorMessage, int errorCode)
{
   if (!Initialized)
   {
       //Show not initialized error
   }

   if (errorCode == -1)
   {
      //Show Operation failed error (errorMessage)
   }
   else if (errorCode == 0)
   {
      //Show operation success message etc
   }
   //other error code check
}


texts: Deep copy linked list with a random pointer

texts:
I had this as an interview question through phone through an online text editor.

  The input is a linked list and in addition to a next pointer there is
  a random pointer that can point to any node in the list. Create a deep
  copy of the linked list and return the head of the new copy.

This my code below, which does the above Can some one review the code provide some feed back. Also is 28 mins too much for this code for a phone interview? I took my time but still made a few mistakes which has been fixed here already.

public class Node {
 public int val;
 public Node next;

 public Node random;

 public Node(int val) {
  this.val = val;
  next = null;
  random = null;
 }
}

class CopyUtil {

 Node deepCopy(Node head) {
  if (head == null) return head;
  Dictionary < Node, Node > nodePool = new Dictionary < Node, Node > ();
  Node current = head;
  Node newHead = new Node(head.val);

  nodePool.Add(current, newHead);

  newHead.random = getNode(nodePool, head.random);

  Node returnHead = newHead;

  while (current.next != null) {
   newHead.next = getNode(nodePool, current.next);
   newHead.next.random = getNode(nodePool, current.next.random);

   current = current.next;
   newHead = newHead.next;
  }

  return returnHead;

 }

 Node getNode(Dictionary < Node, Node > nodePool, Node current) {
  Node ret = null;
  if (current==null) return ret;
  if (nodePool.ContainsKey(current))
   ret = nodePool[current];
  else {
   ret = new Node(current.val);
   nodePool.Add(current, ret);
  }
  return ret;
 }
}

Mistakes:

1) Had a return type for constructor.
2) Had private (unspecified protection levels) Node values.
3) I was working with newHead.random instead of newHead.next.random
inside loop.
4) Missed new keyword in one of initialization of
Dictionary.
5) Missed null check when I moved to code to a util function.

Tips:

1) The editor was in plain text and 1/2/4 were stupid and silly mistakes which should have been caught if I patiently reviewed the code.
2) Practice on a plain notepad editor.
3) Have a headphone. Its important to collect your thoughts without worrying about dropping your phone.
4) Silly mistakes creeped in when I moved some code lines into a function and was doing some copy/paste. Be careful when you refactor your code during interviews.
5) Think your are submitting your code to codereview in stackexchange. lol.


texts:
I'm trying to solve the Reve's puzzle (a variant of the Tower of Hanoi puzzle with four pegs). This is what I've come up with so far:

def solve(disk, source, temppeg1, temppeg2, destination):
    if disk == 1:
        print((source, destination))
    elif disk == 2:
        print((source, temppeg1))
        print((source, destination))
        print((temppeg1, destination))
    else:
        solve(disk - 2, source, temppeg2, destination, temppeg1)
        print((source, temppeg2))
        print((source, destination))
        print((temppeg2, destination))
        solve(disk - 2,  temppeg1, source, temppeg2, destination)

>>> solve(16, 'a', 'b', 'c', 'd')
('a', 'c')
... 763 lines deleted ...
('a', 'd')

While this works fine, I was wondering if there's a better solution (more optimal) than what I have so far. Currently with what I have, I can solve 16 disk in 765 moves.


texts: Pretty print with unit and physical suffix

texts:
I have a solution for pretty printing physical values with the correct suffix (kilo, mega etc.).

I'd like to discuss my solution with you.

# -*- coding: utf-8 -*-

import math
def eng_format(x, unit=''):
    e =(math.floor(math.log10(x))//3)*3
    sL = ['f', 'p', 'n', 'u', 'm', '', 'k', 'M', 'G']

    idx = int(e/3) + sL.index('')

    if idx<0 or idx>=len(sL):
        s = '*10^%d '%e
    else:
        s = sL[idx]

    nx = x * 10**(-e)
    return '%.2f%s%s'%(nx, s, unit)

if __name__ == '__main__':
    print eng_format(0.002, 'V')
    print eng_format(0.000003221, 'A')
    print eng_format(30589, 'A')
    print eng_format(60000000, 'W')

Screen output:

2.00mV
3.22uA
30.59kA
60.00MW


texts:
I recently attempted a coding problem, but my solution was not well received during the interview (modified slightly to reduce Google-ability).

  Suppose a child has several Lego blocks, and wants to build a toy from them. Every piece has a size, and when two pieces are combined a new piece is created whose size is the sum of the attached blocks. The time it takes to combine two blocks is equal to the size of the individual blocks

  Find the sequence of combinations that takes the least amount of time to combine all of the Legos

Here is an example:

  Given the following blocks: 5, 2, 8 the child could combine them in the following methods:

5 + 8 = 13  --> Kid spent 13 units of time
13 + 2 = 15 --> Kid spent 15 units of time
Total time spent: 13 + 15 = 28

  Another combination would be:

2 + 5 = 7
7 + 8 = 15
Total time spent: 22

I came up with the following algorithm to find the shortest time required to combine all of the blocks:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class AssemblyTime {

  int shortestAssemblyTime(List<Integer> lego) {
    Collections.sort(lego);

    int counter = lego.size() - 1;
    int sum = lego.get(0) * (lego.size() - 1);

    for (int i = 1; i < lego.size(); i++) {
      sum += lego.get(i) * counter;
      counter--;
    }

    return sum;
  }

  public static void main(String[] args) {
    int i = new AssemblyTime().shortestAssemblyTime(Arrays.asList(5, 2, 8, 4));
    assert i == 36;
  }
}

The test cases are not available to me, however my solution timed out on 6 of the 10 (it passed the other 4).

The idea of my algorithm is as follows. Given my test case in code, the process is something like this:

2 + 4
2 + 4 + 5
2 + 4 + 5 + 8

So the last element is added once, the last-1 is added twice until elements at index 0 and 1, which are both added list.length - 1 times.

How can I improve the performance for this algorithm? Is there any other data structure I can use?


texts:
I have a class that loads locales from a database. I'm not sure if locale is the right word. It's basically loading texts for a game, generic sayings like alerts and error messages.

I'm also not sure if it should be called WhateverHandler or WhateverController, maybe even WhateverManager. I tend to get really OCD about my code, so some advice would be nice.

public class LocaleHandler
{
    private static readonly ILogger Logger = new ConsoleLogger(typeof(LanguageLocale));

    private readonly ConcurrentDictionary<string, string> _localeKeyValue;

    public LocaleHandler()
    {
        using (var dbConnection = PlusEnvironment.GetDatabaseManager().Connection)
        {
            _localeKeyValue = FetchLocale(dbConnection);
        }

        Logger.Trace($"Fetched {_localeKeyValue.Count} language locales from the database.");
    }

    private static ConcurrentDictionary<string, string> FetchLocale(DatabaseConnection dbConnection)
    {
        dbConnection.SetQuery("SELECT * FROM `server_locale`");

        using (var reader = dbConnection.ExecuteReader())
        {
            if (!reader.HasRows)
            {
                return new ConcurrentDictionary<string, string>();
            }

            var locale = new ConcurrentDictionary<string, string>();

            while (reader.Read())
            {
                locale.TryAdd(reader.GetString("key"), reader.GetString("value"));
            }

            return locale;
        }
    }

    public bool TryGetLocale(string key, out string value)
    {
        return _localeKeyValue.TryGetValue(key, out value);
    }
}


texts: Python sum of multiples of some numbers in a range

texts:
I saw the Project Euler challenges online and I decided to code out a few. The first challenge involved finding the sum of multiples. So I decided to have my code be able to find the sum of multiples for any given range, and for any amount of natural numbers.

My code allows a user to input as many natural numbers as they want and then set the range of multiples that user wants to sum and then sum those multiples.

I just wanted any input on if there's a more efficient way of doing this.

def main():
    # Initialize variables
    multiples = []
    sums = []
    i = 0
    integers = 1

    # Detemines the number of multiples from user
    while True:
        try:
            num_mul = int ( input ( 'How many multiples are you using in total?: ' ) )
            break
        except ValueError as e:
            print ( e )

    # Takes multples and store in list
    while True:
        try:
            for y in range ( num_mul ):
                multiples.append ( int ( input ( 'Please input your No.{} integer here: '.format(integers) ) ) )
                integers = integers + 1
            break
        except ValueError as e:
            print ( 'Integer Values ONLY' , e )

    # determine the start and stop of the range from user
    while True:
        try:
            start = int ( input ( 'Start of range: ' ) )
            stop = int ( input ( 'End of range: ' ) ) + 1
            break
        except ValueError as e:
            print ( e )

    # Figures out the multiples of the numbers given between the start and end range
    while i < len ( multiples ):

        for k in range (start, stop ):
            if (k % multiples[i]) == 0:
                sums.append(k)
            else:
                continue

        i = i + 1  # increments through the list values by 1

    x = sum(set(sums))  # Gets rid of duplicated values and sums the list of values

    print ( 'Your SUM total is {}.'.format ( x ) )

if __name__ == "__main__": main ( )


texts: Get all objects which contains any given array of Enums

texts:
What this does?:

Interactions is an Enum whereas Interactable is an interface (not @Functional Interface). Every Interactable has a list of Interactions that it can do. The below code snippet, filters out all the objects that contains any of the provided Interactions. It does not check for all Interactions, so if any of the given Interactions found, it adds the object in interactableList. Once done iterative over the List, sends it back to the caller for further processing.

public List<Interactable> getObjectsByInteractions (final Interactions[] interactions) {
    final List<Interactable> interactableList = new ArrayList<>();
    for (Interactable object : objects) {
        List<Interactions> objectInteractions = object.getInteractions();
        for (Interactions interactions1 : interactions) {
            if (objectInteractions.contains(interactions1)) {
                interactableList.add(object);
                break;
            }
        }
    }
    return interactableList;
}

Concern:

Right now, I am using pre Java 8 code style to achieve the results. Since, it's the time of Java 8, I would request the reviewers to suggest Java 8 style.


texts: Extension method replacing elements from an IEnumerable collection

texts:
Today I needed a method to replace all 'x' values in a said collection. Since there is no such method by default in .NET I wrote my own:

[Pure]
public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T oldValue, T newValue)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    List<T> newValues = new List<T>();
    using (var enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            newValues.Add(enumerator.Current.Equals(oldValue) ? newValue : enumerator.Current);
        }
    }
    return newValues;
}

It's pretty short and does the job right in a reasonable amount of time.

I also tested few other solutions:

[Pure]
public static IEnumerable<T> Replace1<T>(this IEnumerable<T> source, T oldValue, T newValue)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    using (var enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            yield return enumerator.Current.Equals(oldValue) ? newValue : enumerator.Current;
        }
    }
}

[Pure]
public static IEnumerable<T> Replace2<T>(this IEnumerable<T> source, T oldValue, T newValue)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    List<T> newValues = new List<T>(source);
    for (int i = 0; i < newValues.Count; i++)
    {
        if (newValues[i].Equals(oldValue))
        {
            newValues[i] = newValue;
        }
    }
    return newValues;
}

But they are all slower than the former. The only advantage is in the function which utilizes iterator because it's a bit shorter but it's actually the slowest out of the three.

Here are my benchmark results for each method running 1 million times:

Replace

Slowest: 207ms

Average: 177.8ms

Fastest: 161ms

Replace 1

Slowest: 353ms

Average: 293.9ms

Fastest: 253ms

Replace 2

Slowest: 344ms

Average: 276.4ms

Fastest: 252ms

Feel free to comment on anything you feel like can be improved.

Here are some of my questions:

Are there any flaws in my function?
Are there any improvements that can be made?
Why didn't Microsoft include this in the .NET framework?


texts: Node function to walk through file system and make sure it has a matching db record

texts:
I have an app that uses the file system a lot to store generated files (zip files and scss/css fil).    When a user generates a file, the metadata and other information is stored in the db for later retrieval and action in another part of the app.   Through testing or error, I realized the DB and file system could become out of sync, so I created a function to walk through the db and match each record to a directory, and then the other way around (walk through the file system and match it to the db.

I use both fs-plus (fs) and fs-extra (fse) to achieve the recursive search and removal of directories.

The code seems fragile and confusing, any feedback would be appreciated.

walkStyles: function() {
  // First let's lookup styles and make sure there is a directory for them.  If not, delete it from the db.
  Style.find({system: false}, function(err, result) {
    if (err) {
      console.log(err);
      return null;
    }
    if (!result) {
      console.log('No styles found in db');
      return null;
    }
    _.forEach(result, function(style)  {
    // make sure I can access the style fil.
      fs.access('./content/userstyles/' + style._id + '/style.css', function(err) {
        if (err && err.code === 'ENOENT') {
          //Can't find the style file, i need to delete it
          Style.remove({_id: style._id}, function(err, result) {
            if (err) {
              console.log('Error removing style from the db');
            }
              if (result) {
                console.log('Out of sync style pruned');
              }
            });
          }
        });
        console.log('Matched style from DB to disk.   No action.');
    });
  });
  // let's walk the other way and make sure all styles found on disk have a match in the db at the folder level.
  fsp.traverseTree('./content/userstyles',  // walk through the content directory
     function(file) {
    console.log('File: ' + file);
    },
  function(dir) {
    let _id = dir.replace('content\\userstyles\\', '');  // on dir, trim to just the id.  this can be matched to the DB _id field.
    console.log(_id);
    Style.find({_id: _id}, function(err, result) {
      if (err) {
        console.log(err);
      }
      if (result) {  // found the style
        console.log('Style synced from disk to db.  No action.');
      }
      if (!result) {  // didn't find the style.
        console.log('Style found on disk, but not in the db.   Removing from disk.');
        fs.remove('./content/userstyles/' + _id, function(err) {
          if (err) {
            console.log(err);
          }
        });
      }
    });
  },
    function() {
  console.log('done checking styles.');
});
}


texts: Angular pipe to suppress sensitive information

texts:
I have created an Angular pipe to suppress the sensitive information like credit cards, bank account, ABA numbers etc.

This is working fine but I would like to know if this is the best possible way to implement the logic.

Here is the Typescript code for pipe logic.

export class SuppressInfoPipe implements PipeTransform {

  transform(valueToSupress: string, unSuppressedCount?: number): string {

    let suppressedOutput = '';

    const valueToRemainUnsuppressed =
    valueToSupress.substring(valueToSupress.length - unSuppressedCount, valueToSupress.length);

    let astariskLength = valueToSupress.length - unSuppressedCount;

    for ( let i = 0; i < astariskLength; i++) {
     suppressedOutput = suppressedOutput.concat('*');
    }
    suppressedOutput = suppressedOutput.concat(valueToRemainUnsuppressed);

    return suppressedOutput;
  }

}

it takes the string input and the number of character they will no be hidden and then return the suppressed output.

Comments and suggestions are welcomed.


texts: Process multiple request from different threads in batches on one processing thread

texts:
So I have a system that uses multiple threads to process data. These data could be processed individually but it would be better to process them in batches.

Lets assume we have a class Data, a class OtherData and a class Processor which implements Function<List<Data>, List<OtherData>>.

To process objects of type Data from multiple threads I designed two classes System and Evaluator.

public class System {
    private final Evaluator evalThread;
    private final Object sync = new Object();
    private Function<List<Data>, List<OtherData>> processor;
    private Map<Object, Data> inputMap;
    private Map<Object, CompletableFuture<OtherData>> futureMap;
    private List<Object> idList;

    public System() {
        processor = new Processor();
        inputMap = new HashMap<>();
        futureMap = new HashMap<>();
        idList = new LinkedList<>();

        evalThread = new Evaluator(processor, inputMap, futureMap, idList, sync);
        Thread thread = new Thread(evalThread, "EvalThread");
        thread.start();
    }

    public CompletableFuture<OtherData> process(Data data) {
        Object id = new Object();

        final CompletableFuture<OtherData> completableFuture = new CompletableFuture<>();

        synchronized (sync) {
            inputMap.put(id, data);
            futureMap.put(id, completableFuture);
            idList.add(id);

            if (idList.size() >= 32) {
                sync.notifyAll();
            }
        }

        return completableFuture;
    }
}

public class Evaluator implements Runnable {
    private final Function<List<Data>, List<OtherData>> processor;
    private final Map<Object, Data> inputMap;
    private final Map<Object, CompletableFuture<OtherData>> futureMap;
    private final List<Object> idList;
    private final Object sync;

    private AtomicBoolean keepRunning = new AtomicBoolean(true);

    public Evaluator(Function<List<Data>, List<OtherData>> processor, Map<Object, Data> inputMap, Map<Object,
                      CompletableFuture<OtherData>> futureMap, List<Object> idList, Object sync) {
        this.processor = processor;
        this.inputMap = inputMap;
        this.futureMap = futureMap;
        this.idList = idList;
        this.sync = sync;
    }

    @Override
    public void run() {
        synchronized (sync) {
            while(keepRunning.get()) {
                if (idList.size() > 0) {
                    List<Data> input = new LinkedList<>();

                    for (int i = 0; i < idList.size(); i++) {
                        input.add(inputMap.get(idList.get(i)));
                    }

                    List<OtherData> output = processor.apply(input);

                    for (int i = 0; i < idList.size(); i++) {
                        futureMap.get(idList.get(i)).complete(output.get(i));
                    }

                    idList.clear();
                    inputMap.clear();
                    futureMap.clear();
                }

                try {
                    sync.wait(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

My idea was that any one can call process with singular data but the data will (if there are enough) be processed together with other Data objects.

Any suggestions for improvements or are there systems in the Java-framework that would fit this task better?
Do you might see problems according to deadlocks, etc.?


texts: RadixSort implementation design and performance

texts:
Credits for the original implementation I based my code on:
Quora - What is the most efficient way to sort a million 32-bit integers?

Implementation

// RadixSort - works for values up to unsigned_int_max (32-bit)
template<typename Iter>
void radix_sort(Iter __first, Iter __last){
    typedef typename iterator_traits<Iter>::value_type value_type;
    vector<value_type> out(__last - __first);

    // calculate most-significant-digit (256-base)
    value_type __mx = *max_element(__first, __last); //O(n)
    int __msb = 0;
    do {
        __msb += 8;
        __mx = __mx >> 8;
    } while(__mx);

    Iter __i, __j, __s;
    bool __swapped = false;
    for (int __shift = 0; __shift < __msb; __shift += 8) {

        // cycle input/auxiliar vectors
        if (__swapped) {
            __i = out.begin();
            __j = out.end();
            __s = __first;
        }
        else {
            __i = __first;
            __j = __last;
            __s = out.begin();
        }

        // counting_sort
        size_t count[0x100] = {};
        for (Iter __p = __i; __p != __j; __p++)
            count[(*__p >> __shift) & 0xFF]++;

        // prefix-sum
        size_t __m, __q = 0;
        for (int i = 0; i < 0x100; i++) {
            __m = count[i];
            count[i] = __q;
            __q += __m;
        }

        // filling result
        Iter __v;
        for (Iter __p = __i; __p != __j; __p++) {
            __v = __s + count[(*__p >> __shift) & 0xFF]++;
            *__v = *__p;
        }
        __swapped = !__swapped;
    }

    // if ended on auxiliar vector, copy to input vector
    if (__swapped) copy(out.begin(), out.end(), __first); //O(n)
}

Discussion

In order to implement a more general algorithm than the one used as reference, I tried to refactor the code using template and iterators. This is the main difference between my code and the original.

I can't simply swap references when using iterators, so I approached this problem by cycling the iterators used in each counting-sort loop. Doing so prevents the need to copy the output array on every loop.

Another different aspect of my code is that I find max-element and calculate the most-significant-digit on base-256. I use this information to determine how many counting-sort loops are necessary, instead of hardcoding 32 (unsigned_max) and always running the loop 4-times even if all values are less than 255. This actually adds unnecessary overhead if 4-loops are necessary, but it should increase execution time otherwise.

The temporary container used is a vector<value_type> and this is something I'm not quite sure about, I feel like this is a point where I could improve my code. I'd like to hear opinions about it.

Questions

What are possible improvements that can be made to my implementation?
How would you re-factor the iterator cycle I used? (I hate it)
Which container should I use for the temp-array?
Should I use std::copy or std::move to move the data from the temp-array to the input container?

Relevant Information

I decided to run some benchmarks to test if calculating the maximum-digit makes a huge difference. element_values defines the range of values each element can have. The maximum-digit only affects the number of loops if element_values can be represented with 24-bits or less.  Here are the results for n = 1E7:

     element_values < 256 (8-bits):
          radix_sort_msd - Average time:   51.59 ms
          radix_sort_32  - Average time:  109.03 ms

     element_values < UINT_MAX(32-bits):
          radix_sort_msd - Average time:  107.38 ms
          radix_sort_32  - Average time:   89.75 ms

While radix_sort_msd works really well when element_values is small, it really just depends on the dataset. Therefore implementing is a matter of preference.


texts:
Because C# .NET does not come with a MultiDictionary, I implemented one based on this StackOverflow answer.

The MultiDictionary should be able to hold multiple values for one key and remove the key, if no value is assigned to the key anymore.

I wanted to implement nearly all methods, which the standard Dictionary provides:

void Add(TKey key, TValue value);
bool Remove(TKey key);
void Clear();
bool ContainsKey(TKey key);
bool TryGetValue(TKey key, out TValue value);

To use the MultiDictionary properly some signatures needed to be changed. This is my implementation:

public class MultiDictionary<TKey, TValue>
{
    private readonly Dictionary<TKey, List<TValue>> _Data = new Dictionary<TKey, List<TValue>>();

    public Dictionary<TKey, List<TValue>>.ValueCollection Values => _Data.Values;
    public Dictionary<TKey, List<TValue>>.KeyCollection Keys => _Data.Keys;
    public void Add(TKey key, TValue value) { this[key].Add(value); }
    public bool Remove(TKey key, TValue value) { return this[key].Remove(value); }
    public void Clear() { _Data.Clear(); }
    public bool ContainsKey(TKey key) { return _Data.ContainsKey(key); }
    public bool TryGetValue(TKey key, out List<TValue> value) { return _Data.TryGetValue(key, out value); }

    private struct Entry : IEnumerable<TValue>
    {
        private readonly MultiDictionary<TKey, TValue> _Dictionary;
        private TKey Key { get; }

        internal void Add(TValue value)
        {
            if (!_Dictionary._Data.TryGetValue(Key, out var list))
                list = new List<TValue>();
            list.Add(value);
            _Dictionary._Data[Key] = list;
        }

        internal bool Remove(TValue value)
        {
            if (!_Dictionary._Data.TryGetValue(Key, out var list))
                return false;
            var result = list.Remove(value);
            if (list.Count == 0)
                _Dictionary._Data.Remove(Key);
            return result;
        }

        internal Entry(MultiDictionary<TKey, TValue> dictionary, TKey key)
        {
            _Dictionary = dictionary;
            Key        = key;
        }

        public IEnumerator<TValue> GetEnumerator()
        {
            return !_Dictionary._Data.TryGetValue(Key, out var list) ? Enumerable.Empty<TValue>().GetEnumerator() : list.GetEnumerator();
        }
        IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
    }

    private Entry this[TKey key] => new Entry(this, key);
}

I wanted to know, if this implementation is valid (working as I expect) and if you have improvements regarding coding style, safety and so on.

Thanks in Advance!


texts: Converting an SVG polygon path from relative to absolute coordinates

texts:
This question was moved from StackOverflow as suggested by some users.

I developed a function that aims to (should) provide a simple and effective method to transform a polygon <path> from relative to absolute. The purpose of this function is to replace similar SnapSVG function from my code, since I'm not processing any other type of path commands.

I need suggestions on how improve the code. Here's the thingy:

// simple pathToAbsolute for polygons
// returns an array with ABSOLUTE points of the polygon path
var pathToAbsolute = function(p) {
  var np = p.match(/(m[^l]*|l[^(l|z)]*)/gi), // we extract the segments string from path string
      l = np.length, s, c, r, x = 0, y = 0;

  for (var i = 0; i<l; i++){ // here we start processing each segment string
    np[i] = np[i].trim(); // we trim the segment string
    c = np[i][0].trim(); r = new RegExp(c); // the path command
    np[i] = np[i].replace(/(^|[^,])\s*-/g, '$1,-') // fix the x,y 186.101-87.287 to -186.101,-87.287 separation
                 .replace(/[\s+\,|\s|\,]/g,'|') // replace any spacing and comma with another separator
                 .replace(r,'') // remove the path command from string
                 .split('|'); // split by new separator

    np[i][0] === '' && np[i].shift(); // I need a way to avoid this

    np[i][0] = parseFloat(np[i][0]); // make sure we do math with numbers
    np[i][1] = parseFloat(np[i][1]);

    if (i === 0) { x+=np[i][0]; y +=np[i][1]; } // for M, we only need it's values

    if (i>0){ // for other segments
      x= !!np[i-1] ? np[i-1][0] : np[0][0]; // if we have a previous point
      y= !!np[i-1] ? np[i-1][1] : np[0][1]; // let's grab its x,y values for relative points

      np[i][0] = c === 'l' ? np[i][0] + x : np[i][0]; // here we fix the value of any
      np[i][1] = c === 'l' ? np[i][1] + y : np[i][1]; // relative point
    }
  }
  return np; // in the end we return the newPoints array
}

// testing the function
var star = document.getElementById('star'), svg = star.parentNode,
    starPoints = pathToAbsolute(star.getAttribute('d'));

var newStar = document.createElementNS('http://www.w3.org/2000/svg','path');
newStar.setAttribute('d', 'M'+starPoints.join('L')+'z');
newStar.setAttribute('fill','green');
newStar.setAttribute('transform','translate(30,30)');
svg.appendChild(newStar);
<div style="width:200px">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" >

   <path id="star"
         fill="#eee"
         d="M301.113,12.011l99.25,179.996l201.864,38.778L461.706,380.808 l25.508,203.958l-186.101-87.287L115.01,584.766l25.507-203.958L0,230.785l201.86-38.778L301.113,12.011z"
    ></path>

  </svg>
</div>

As you can see, the function works pretty much as expected, but in the comments I've put some points of concerns where I'm not sure it's accurate or generally applicable.

My most concern is the way to calculate the new values for relative points now becoming absolute. Also I need a way to avoid shifting via np[0].shift() any segment that is not properly processed before. Perhaps I can improve some RegExp, just I'm not completely sure.

So I am open to any other improvement suggestion you may have, so please jump in.

I need something that should work IE9+, Chrome 4+, Safari 5+, regardless of the fact that pathSegList or pathDataAPI is supported or not, just like the original functions from SnapSVG. No polyfills are acceptable.

Your suggested improved function must return same thingy: the array with absolute points, probably supporting H and V path commands. The array format is required for other functions that process the array for other uses.


texts: How is OOP achieved with configuration files in PHP?

texts:
Someone asked if their singleton is good for OOP:

Using a singleton class to get and set program wide settings.

However, the answer just provides tweaks to his existing code - but the question wasn't entirely answered. What is the best practice to use for configuration files so that it doesn't become spaghetti code?

All apps need configuration settings so that it saves time and it looks neat.

I currently use something similar to what was proposed but not a singleton.  However, I have a long array that feeds into different constructors. I feel that this is improper or maybe it is.

namespace App;

class Config
{
    protected static $config = array();

    public static function get($name, $default = null)
    {
        return isset(self::$config[$name]) ? self::$config[$name] : $default;
    }
    public static function add($parameters = array())
    {
        self::$config = array_merge(self::$config, $parameters);
    }
}
App\Config::add(
    array(
        'database' => array(
            'default' => array(
                'driver'    => 'mysql',
                'host'      => '127.0.0.1',
                'username'  => 'user',
                'password'  => '',
                'database'  => 'database',
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci'
            ),
            'tracking' => array(
                'driver'    => 'mysql',
                'host'      => '192.168.0.1',
                'username'  => 'tracking',
                'password'  => '123456',
                'database'  => 'tracking',
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci'
            ),
            'data' => array(
                'driver'    => 'mysql',
                'host'      => '192.168.0.11',
                'username'  => 'data',
                'password'  => 'abcder',
                'database'  => 'data_info',
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci'
            )
        ),

        'pheanstalk' => array(
            'default' => array(
                'host'       => 'localhost',
                'port'       => 11400,
                'queue_name' => 'queue'
            )
        ),
        'app_worker' => array(
            'log_files_path'      => ROOT.'/logs',
            'file_size_limit'     => 542880, //5MB
            'file_name_extension' => 'w_log',
        ),
        'memcache' => array(
            'default' => array(
                array(
                    'host'  => 'localhost',
                    'port'  => '11211'
                ),
                array(
                    'host'  => 'localhost',
                    'port'  => '11211'
                ),
                array(
                    'host'  => 'localhost',
                    'port'  => '11211'
                )
            )
        )
    )
);

Then in my main program:

$db_config = App\Config::get('database');

Now it's ok for me to add extra configuration needs for different object I might create and etc and I can load up a controller or piece of code to fetch it from.  However, I feel that this configuration file that adds all these settings will be terribly long in the long wrong.

I would like to know if there something better, and what. I tried to use inheritance or DI but my configuration file is still long.


texts:
I want to improve this program so I want you to criticize the code, and tell me what else can I do, and where can I find information about what I have to do.

TODO:

Fix wget timeout
The code should always check the returned value from any of the malloc family of functions to assure to memory allocation was successful
the code needs to check the returned value from fopen() to assure the operation was successful
The wget command can fail, so the wget line should route stderrto a file, then after system(cmd) should open/read that file to assure the wget was successful
The main() function will not compile cleanly because the declaration (as it should) indicates are int returned value, but no return (someint) line exists in the execution paths
In the download() function, what is the magic number '151' about? Better to #define that number, with a descriptive name and a comment
Eegarding the makefile:

cc := /usr/lib/gcc
Globbing all the compiles and the link into a single line is not a good nor flexible plan. Suggest breaking out into a compile rule from one .c to one .o and then using the list of .o files on a separate rule that performs the link.
The 'all' and 'clean' do not produce a file with those names. It suggests adding the line: .PHONY: all clean

#include <stdio.h>
#include <stdlib.h> // for using system calls
#include <stdbool.h>
#include <string.h> // for strlen

char  postBegin[] = "forum-post-body-content", postEnd[] = "p-comment-notes", img[] = "img src=";
int length1 = 23, length2 = 15, length3 = 8;
int pos1 = 0, pos2 = 0, pos3 = 0;

void downloadAndOpen (FILE **fp, int i, char *file);
bool search (char needle[], int length, char c, int *pos);
void download (FILE* *fp);

int main ()
{
    bool inPost = false;
    FILE *fp;
    int c;
    char file[20];

    for ( int i = 22; i <= 151; i++ )
    {
        downloadAndOpen (&fp, i, file);
        while ( (c = getc (fp)) != EOF ) {
            if ( search (postBegin, length1, c, &pos1) )
                inPost = true;
            if (inPost) {
                if ( search (postEnd, length2, c, &pos2) )
                    inPost = false;
                if ( search (img, length3, c, &pos3) )
                    download (&fp);
            }
        }
        fclose (fp);
        remove (file);
    }
}

void downloadAndOpen (FILE **fp, int i, char *file)
{
    char cmd[200]={0};
    // download web page
    sprintf (cmd, "wget -q -O page%d.txt 'http://www.mtgsalvation.com/forums/creativity/artwork/340782-official-digital-rendering-thread?page=%d'", i, i);
    system (cmd);

    // open text file
    sprintf (file, "page%d.txt", i);
    *fp = fopen (file, "r");
}

bool search (char needle[], int length, char c, int *pos)
{
    if (needle[*pos] == c)
    {
        if (*pos == length - 1)
        {
            return true;
            *pos = -1;
        }
        (*pos)++;
    }
    else
    {
        if(*pos > 0)
        *pos = 0;
    }
    return false;
}

void download (FILE **fp)
{
    char url[300], cmd[300];
    static int imageNumber = 496; // The image number where I left last time
    int pos = 0, c, j;
    bool found = false;

    while (!found)
    {
        if ( (c = getc (*fp)) == EOF ) {
            printf ("Image not found\n");
            return;
        }
        printf ("%c", (char) c);
        url[pos] = (char) c;
        if ( url[pos-1] == '\"' && url[pos] == '\"' )
            break;
        if ( url[pos-1] == '\"' && url[pos] == '>' )
        {
            printf ("\n");
            found = true;
        }
        ++pos;
    }
    pos -= 2;
    char url2[pos];
    for ( j = 1; j < pos; j++ )
    {
        url2[j - 1] = url[j];
    }
    url2[j - 1] = '\0';
    //http://joequery.me/code/snprintf-c/
    // wget -q for quiet -nc, --no-clobber   skip downloads that would download to existing files (no sobreescribir)
    snprintf(cmd, 300, "wget -q -nc --timeout=10 -O /home/arturo/Dropbox/Digital_Renders/%d \'%s\'", imageNumber++, url2);
    system(cmd);
    pos = 0;
}


texts:
I have some data, which I've faked using:

def fake_disrete_data():
    in_li = []
    sample_points = 24 * 4

    for day, bias in zip((11, 12, 13), (.5, .7, 1.)):
        day_time = datetime(2016, 6, day, 0, 0, 0)
        for x in range(int(sample_points)):

            in_li.append((day_time + timedelta(minutes=15*x),
                          int(x / 4),
                          bias))

    return pd.DataFrame(in_li, columns=("time", "mag_sig", "bias")).set_index("time")

fake_disc = fake_disrete_data()

I can pivot each column individually using and then concatenate them using:

cols = list(fake_disc.columns.values)
dfs = []
for col in cols:
    dfs.append(pd.pivot_table(fake_disc,
                              index=fake_disc.index.date,
                              columns=fake_disc.index.hour,
                              values=col,
                              aggfunc=np.mean))

all_df = pd.concat(dfs, axis=1, keys=cols)

But is there a better way to do this?

I'm trying to follow the answers seen in Pandas pivot table for multiple columns at once and How to pivot multilabel table in pandas, but I'm having a difficult time translating their methods to the DateTimeIndex case.


texts: Exercise - count binary-tree nodes with 1 leaf and 1 internal node as children

texts:
I'm currently working through "Algorithms in java" by Robert Sedgewick (3rd edition, german version) on my own and am trying to solve one of the exercises there.

The exercise

  Write a program that counts the amount of nodes in a binary tree, that
  have an external and an internal node as children.

In the following picture, the ones with the red dot are the ones I think I have to count.

For simplification in the further text I dubbed these nodes "wanted nodes" and the method that determines if a node is a "wanted node" thus isWantedNode(). The solution to this is fairly straightforward if done recursively, but I can't find the most elegant one.

Requests

How can the recursion be simplified to avoid invoking methods unnecessarily in the first place?

I currently want to focus on doing this recursively before I jump into changing this into an iterative solution, for learning purposes on my part.

I'm certain that the recursion can be simplified, I just don't see how. The key here is to check for child-nodes being leafs or internal nodes while avoiding NullPointerExceptions when you're checking if a node is a "wanted node". My current approach is dealing with the NullPointerExceptions instead of avoiding invoking methods for null objects in the first place which I don't think is the best way to go about this.

The Code

static class TreeNode {
        TreeNode left;
        TreeNode right;

        TreeNode(TreeNode l, TreeNode r) {
            this.left = l;
            this.right = r;
        }
    }

/* Count wanted nodes */
private static int strangeCount(TreeNode h) {
    if (h == null) {
        return 0;
    }
    int result = strangeCount(h.left) + strangeCount(h.right);
    return (isWantedNode(h)) ? result + 1 : result;
}

/* Check if n is wanted node */
private static boolean isWantedNode(TreeNode n) {
    return (isLeaf(n.left) && isInternal(n.right) || (isInternal(n.left) && isLeaf(n.right)));
}

/* Check if n is leaf */
private static boolean isLeaf(TreeNode n) {
    return (n == null) ? false : (n.left == null && n.right == null);
}

/* Check if n is internal node */
private static boolean isInternal(TreeNode n) {
    return (n == null) ? false : (n.left != null || n.right != null);
}


texts:
I have implemented a calculation of Pi in Python, just for the lulz.
But now I wonder if I could improve this more. Could you help me out? I do not program a lot in Python.

from time import time
from decimal import *

def faculty(m):
    k=m
    n=1
    while(n<m):
        k=k*n
        n+=1
    if(k>0):
        return k
    else:
        return 1

def ramanujan(b, n):
    return b+Decimal(faculty(4*n)*(1103+26390*n))/Decimal((faculty(n)**4)*396**(4*n))

def chudnovsky(b, n):
    return b+(((-1)**n)*(faculty(6*n))*(13591409+(545140134*n)))/(faculty(Decimal(3)*n)*(faculty(n)**3)*640320**(3*n+(Decimal(3)/Decimal(2))))

def calc(x, a, func):
    b=Decimal(0)
    n=Decimal(0)
    while(n<x):
        b = func(b, n)
        n=n+1
    return ((a*b)**(-1))

def calcrama():
    return calc(20, Decimal((2*Decimal(2).sqrt())/9801), ramanujan)

def calcchud():
    return calc(20, 12, chudnovsky)

def save(name, func):
    fobj = open(name, "w")
    t = time()
    pi = func()
    t = time() - t
    fobj.write("Time: "+str(t)+"\nPi: "+str(pi))
    fobj.close()

getcontext().prec = 1000

save("rama.txt", calcrama)
save("chud.txt", calcchud)


texts: Assigning width and height to specify image dimension using jQuery

texts:
After testing my site against GTMetrix, I get warnings on not specifying image dimensions. I am working on a WordPress site. Here is my solution:

My first solution was:

    // Specify image dimensions
    $('img').each(function() {
        var findImgWidth = $(this).width();
        var findImgHeight = $(this).height();

        $(this).attr('width', findImgWidth);
        $(this).attr('height', findImgHeight);
    });

Output: This method does fix the "Specify Image Dimensions" but it also removed some of my images on the website.

The second solution is:

// Make sure img have been loaded
$().ready(function() {
    imageSize();
});
// Assign width/height to img
function imageSize() {
    // Specify image dimensions
    $('img').each(function() {
        var findImgWidth = $(this).width();
        var findImgHeight = $(this).height();

        $(this).attr('width', findImgWidth);
        $(this).attr('height', findImgHeight);
    });
}

Output: This solution seems to work. My images does not disappear, but I would like someone to help me go over the code to see if it's an efficient way to write.


texts:
I have this little piece of code which determines the base URL of PHP:

$root = $_SERVER["SERVER_NAME"];
if(basename(__FILE__) !== trim($_SERVER["PHP_SELF"], "/\\")) {
    $root .= "/" . basename(__DIR__);
}

This is working for me, but are there other solutions for this "problem," or are there any cases where this would fail?


texts:
I am very interested in the Monte Carlo AI.

I tried my best, still, this AI plays very badly.

This code "works" in the meaning that it does not crash, but the quality of play is extremely low.

Have I completly misunderstood the Monte Carlo AI or is there just a nasty bug in my code preventing it from playing correctly?

Can you understand every detail of code?

Creating an AI is quite complex a task so I would like to have the better style possible in order to keep the code understandable by everyone.

"""
TITLE: Monte Carlo AI that plays the 21 game
AUTHOR: Caridorc Tergilti
LICENSE: Creative Commons 3.0
CURRENT_STATE: The AI is currently very weak, I have no clue why.

General explanation:
This game is very,very easy, an AI can be disigned in
much simpler ways than this.

I designed a Monte Carlo AI because I want to learn about Monte Carlo AI-s
(You can find out more about Monte Carlo here:
https://en.wikipedia.org/wiki/Monte_Carlo_method)
and I want to discover if such an AI can actually be powerful in a game.

(Yes, there are many articles and papers on the internet that say that
Monte Carlo AI works but I want to prove it myself).

This programme is also Creative Commons so I hope that many people will enjoy
reading this programme to understand Monte Carlo AI better.

I will now explain my understanding of Monte Carlo AI.

1) The computer, knowing the rules, must decide what move is better.
2) FOREACH move the computer is going to simulate the move.
3) It will than play a big number of random games starting from the position after he made
the move.
4) Each move will be awarded a score equals to: wins / total_games.
5) The move with the highest score will be played.
"""

import random

WELCOME = """
21 game.
The total starts at 0.
Each player can chose 1, 2, or 3,
the number is than added to the total.
If when a player adds his number,
he makes the total equals or more than 21, he loses.
"""
DEPTH = 1000

def play_random_game(state):
    """
    This function plays a random game starting
    from a state.
    The opponent moves first.
    Returns 1 if you win,
    0 if you lose
    """
    if state >= 21:
        return 0 # You previously played a move that made you lose
    while 1:
        state += random.randint(0,3) # Opponent
        if state >= 21:
            return 1   # YOU WIN
        state += random.randint(0,3)
        if state >= 21:
            return 0   # YOU LOSE

def play_n_games(state,number):
    """
    Plays a certain number of random games,
    all starting from the state.
    Return the wins/total ratio.
    """
    outcomes = []
    for _ in range(number):
        outcomes.append(play_random_game(state))
    return sum(outcomes) / len(outcomes)

def AI(total):
    """
    This artificial intelligence uses Monte Carlo
    to make the best move.
    """
    list_of_outcomes = []
    possible_moves = [1,2,3]
    for move in possible_moves:
        list_of_outcomes.append(play_n_games(total,DEPTH))

    # Chose the move with the better score
    if max(list_of_outcomes) == list_of_outcomes[0]:
        return 1
    elif max(list_of_outcomes) == list_of_outcomes[1]:
        return 2
    elif max(list_of_outcomes) == list_of_outcomes[2]:
        return 3

def interface():
    """
    Allows the user to play the game
    against the AI.
    """
    total = 0
    print(WELCOME)
    while 1:
        user_number = int(input("Enter your number: "))
        assert (user_number in [1,2,3]),"Each player can chose 1, 2, or 3"
        total += user_number
        print("The total is " + str(total))
        print()
        if total >= 21:
            print("You lost")
            break
        total += AI(total)
        print("After the AI added a number")
        print("The total is " + str(total))
        print()
        if total >= 21:
            print("You won")
            break

if __name__ == "__main__":
    interface()


texts: Ruby: Remove middle node from Linked List

texts:
Currently, I'm going over the CTCI, I'm working on the problem removing the middle node. I'm using Ruby to go over these problems. I have the following solution.

 def remove_middle_node
    node = @head
    count = 1

    while(node = node.next )
      count += 1
    end
    # reset node to point to head
    node = @head
    middle = (count / 2)
    count = 1

    while(node = node.next)

      if(count == (middle - 1))
        node.next = node.next.next
        return
      end
      count += 1
    end
  end

Instead of having a previos_node I subtract one from the middle. In this case when traversing the Linked List, when I get to the (middle - 1), meaning the previous node before the middle node in the linked list. I delete the middle node and set it to next.

I would like to get feedback on this implementation. In my understanding, this is O(n) and time complexity is also O(n). Although I warn you, this Big O notation still a bit unclear to me so time and space complexity might be wrong.

Here is the full Linked List class.

https://github.com/theasteve/ds_and_algos/blob/master/linked_list.rb
 here is the test I used.

# TEST
list = LinkedList.new

list.append(1)
list.append(2)
list.append(8)
list.append(3)
list.append(7)
list.append(0)
list.append(4)

list.display
puts '-----------------------------------'
list.remove_middle_node
list.display


texts: Program to calculate a student's test average

texts:
I made a very simple program where you input a students grades (edit the code with the set method?) and the program will output the average. Each test has a different weight associated with it.

The problems I think I have right now are:

I am not properly utilizing my methods. The getters and setters are probably done wrong.
Should I make testScore1 its own class since a test can have a test score, test worth % (weight)?
Is it good coding practice to use code separators to separate code for easier viewing?

Main question

Should the declaring of a students name and grades be inside the student class or was I correct in setting them in the main method? (I think that a student's info (name and grades) should be kept inside the Student class and that the main method should be using get methods to access them rather than setting them. Is my thinking correct?)

The basis of what I am trying to achieve is the first comment in my code.

Pastebin link for application class
Pastebin link for Student class

application class

/*
 * --- Student Grade Book Application ---
 * Keep track of students (with a student class that has their name,     average, and scores) in a class and their grades.
 * Assign their scores on tests and assignments to the students and figure     out their average and grade for the class.
 * For added complexity put the students on a bell curve.
 */

// I think this will require multidimensional arrays
public class application {

public static void main(String[] args) {

    Student student1 = new Student();

    student1.setName("Bob"); // Should the name of the student be declared here with a setName?
    student1.setTestScore1(80);
    student1.setTestScore2(60);
    student1.setFinalExamScore(90);

    student1.calculateEntireAverage();
    System.out.println(student1.calculateEntireAverage() + "%");

}
}

Student class

public class Student{
private String name;
private double average;
private double testScore1; // worth 25% (should I make testScore1 it's own     class since a test can have a test score, test worth %)
private double testScore2; // worth 25%
private double finalExamScore; // worth 50%

// Getter for name
public String getName() {
    return name;
}

// Setter for name
public void setName(String name) {
    this.name = name;
}

// ----------------------------------------------------
// Getter for testScore1
public double getTestScore1() {
    return testScore1;
}

// Setter for testScore1
public void setTestScore1(double testScore1) {
    this.testScore1 = testScore1;
}

// Getter for testScore2
public double getTestScore2() {
    return testScore2;
}

// Setter for testScore2
public void setTestScore2(double testScore2) {
    this.testScore2 = testScore2;
}

// ----------------------------------------------------
// Getter for finalExamScore
public double getFinalExamScore() {
    return finalExamScore;
}

// Setter for finalExamScore
public void setFinalExamScore(double finalExamScore) {
    this.finalExamScore = finalExamScore;
}

// ----------------------------------------------------
// Getter for average
public double getAverage() {
    return average;
}

// I think this is essentially a setter for average
public double calculateEntireAverage() {
    average = (testScore1*0.25 + testScore2*0.25 + finalExamScore*0.5);
    // am I just supposed to use a getter / setter for the average instead of making a method like this?
    return average;
}
}


texts: Get application credentials from linked array obtained from Cloud Foundry API

texts:
I am new to Java and I use the following code to retrieve parameters
from a linked hash map from the Cloud Foundry API. My question is if there is a better way to do it in Java?

public HashMap<String, String> getUserData(String Url, String org, String space, String app) throws MalformedURLException {
        URL endpoint = new URL(Url);
        CloudFoundryOperations ops = sm.getCurrentUserCfClient(endpoint, org, space);

        GetApplicationEnvironmentsRequest request = GetApplicationEnvironmentsRequest.builder()
                .name(app)
                .build();

        ApplicationEnvironments environments = ops.applications()
                .getEnvironments(request)
                .block();

Map<String, Object> mapSystemProvided =  environments.getSystemProvided();

    LinkedHashMap<String, Object> SERVICES = (LinkedHashMap<String, Object>) mapSystemProvided.get("SERVICES");
    ArrayList<Object> apps = (ArrayList<Object>) SERVICES.get("apps");
    LinkedHashMap<String, Object> appsList = (LinkedHashMap<String, Object>) apps.get(0);
    LinkedHashMap<String, Object> credentials = (LinkedHashMap<String, Object>) appsList.get("credentials");

    HashMap<String, String> parameters = new HashMap<String, String>();
    parameters.put(ID, credentials.get(ID).toString());
    parameters.put(DEFAULTS, credentials.get(DEFAULTST).toString());

    return parameters;


texts: Guessing a random number between a range of numbers

texts:
What is the general design pattern for declaring variables in a class?

I have a homework assignment to create a simple Java program which asks the user for a range of two variables. The program then creates a random variable from within this range and prompts the user to guess the number.

I'm having trouble understanding how to declare my variables. I'm not sure if I should declare variables as public or private, and static or non-static. When is it correct to use a public/private variable?

Also, how much code should I include in my main() method? What is generally placed into the main() method?

import java.util.Scanner;
import java.util.Random;

public class HiLo {

  static int guess, guessCount, randomNumber, startRange, endRange;
  static Scanner scan = new Scanner(System.in);
  static Random random = new Random();

  public static void main(String[] args) {
      getRange();
      playGame();
  }

  public static void getRange() {
      System.out.println("Welcome! Enter integer for start of range (must be > 0)");
      startRange = scan.nextInt();

      System.out.println("Enter integer for end of range (must be >0)");
      endRange = scan.nextInt();
      randomNumber = random.nextInt(endRange - startRange + 1) + startRange;
      System.out.println(randomNumber);
  }

  public static void playGame() {
      guessCount = 0;
      System.out.println("Enter guess or 0 to quit: ");
      guess = scan.nextInt();

      while (randomNumber != guess) {
          if (guess == 0) {
              break;
          }
          else if (randomNumber > guess) {
              guessCount++;
              System.out.println("Too Low");
              System.out.println("Enter guess or 0 to quit: ");
              guess = scan.nextInt();
          }
          else if (randomNumber < guess) {
              guessCount++;
              System.out.println("Too High");
              System.out.println("Enter guess or 0 to quit: ");
              guess = scan.nextInt();
          }
      }
      if (randomNumber == guess) {
          guessCount++;
          System.out.println("Correct! That took you " + guessCount + " guesses.");
      }
  }
}


texts: Counts "islands" of 1s in sea of 0s (2d array matrix)

texts:
This solution surpassed 100% of submissions for efficiency! My method was to recursively check surrounding values and change any contiguous "land" to "water". Is there a better way to write what I wrote?

  Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

class Solution {
public int numIslands(char[][] grid) {
    int islands = 0;

    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[i].length; j++) {
            if (grid[i][j] == '1') {
                islands++;
                destroyIsland(grid, i, j);
            }
        }
    }

    return islands;
}

public void destroyIsland(char[][] grid, int i, int j) {
    grid[i][j] = '0';
    if (i < grid.length - 1 && grid[i+1][j] == '1') {
        destroyIsland(grid, i+1, j);
    }
    if (i > 0 && grid[i-1][j] == '1') {
        destroyIsland(grid, i-1, j);
    }
    if (j < grid[i].length - 1 && grid[i][j+1] == '1') {
        destroyIsland(grid, i, j+1);
    }
    if (j > 0 && grid[i][j-1] == '1') {
        destroyIsland(grid, i, j-1);
    }
}
}


texts: JavaScript breadth-first search algorithm

texts:
I have implemented a breadth-first search and I'm more or less looking for suggestions on how I can improve on what I've done here.

How to use:

search(queue, "Musician");

The logs from the search:

Lansana is not a Musician. Lansana is a Software Engineer.
Zack is not a Musician. Zack is a Software Architect.
John is not a Musician. John is a Project Manager.
Francisco is not a Musician. Francisco is a Game Developer.
Ronaldinho is not a Musician. Ronaldinho is a Professional Soccer Player.
Lauren is not a Musician. Lauren is a Mango Seller.
Angelica is not a Musician. Angelica is a Professional Volleyball Player.
Cody is not a Musician. Cody is a Network Programmer.
Match found: Beyonce is a Musician!

I believe it works correctly because if you look at the order in which I enqueue people, and the order in which their friends are enqueued, you'll notice that the logs match the exact order (which of course is crucial in this algorithm in order to get the shortest path).

class Queue {
    constructor() {
        this.count = 0;
        this.data = {};
    }

    enqueue(key, val) {
        if (!this.data.hasOwnProperty(key)) {
            this.count++;
        }
        this.data[key] = val;
    }

    dequeue() {
        let key = Object.keys(this.data)[0],
            memo = this.data[key];
        delete this.data[key];
        this.count--;
        return memo;
    }
}

class Person {
    constructor(args) {
        this.name = args.name;
        this.friends = args.friends || [];
        this.profession = args.profession;
    }
}

let Ronaldinho = new Person({
        name: "Ronaldinho",
        profession: "Professional Soccer Player"
    }),
    Lauren = new Person({
        name: "Lauren",
        profession: "Mango Seller"
    }),
    Angelica = new Person({
        name: "Angelica",
        profession: "Professional Volleyball Player"
    }),
    Cody = new Person({
        name: "Cody",
        profession: "Network Programmer"
    }),
    Beyonce = new Person({
        name: "Beyonce",
        profession: "Musician"
    }),
    Lansana = new Person({
        name: "Lansana",
        friends: [Ronaldinho, Lauren, Angelica],
        profession: "Software Engineer"
    }),
    Zack = new Person({
        name: "Zack",
        friends: [Cody],
        profession: "Software Architect"
    }),
    John = new Person({
        name: "John",
        friends: [Ronaldinho, Angelica],
        profession: "Project Manager"
    }),
    Francisco = new Person({
        name: "Francisco",
        friends: [Beyonce],
        profession: "Game Developer"
    });

let queue = new Queue();

queue.enqueue("Lansana", Lansana);
queue.enqueue("Zack", Zack);
queue.enqueue("John", John);
queue.enqueue("Francisco", Francisco);

function search(queue, profession) {
    let searched = [];

    while (queue.count > 0) {
        let person = queue.dequeue();

        if (!searched[person.name]) {
            if (hasProfession(person, profession)) {
                console.log(`Match found: ${person.name} is  a ${person.profession}!`);
                return true;
            } else {
                console.log(`${person.name} is not a ${profession}. ${person.name} is a ${person.profession}.`);
                for(let i = 0, len = person.friends.length; i < len; i++) {
                    queue.enqueue(person.friends[i].name, person.friends[i]);
                }
            }

            searched.push(person.name);
        }
    }

    return false;
}

function hasProfession(person, profession) {
    return person.profession.toLowerCase() === profession.toLowerCase();
}


texts:
I recently came across this problem that asks you to print the number of leaves not eaten by the caterpillars:

  As we all know caterpillars love to eat leaves. Usually, a caterpillar
  sits on leaf, eats as much of it as it can (or wants), then stretches
  out to its full length to reach a new leaf with its front end, and
  finally "hops" to it by contracting its back end to that leaf.

  We have with us a very long, straight branch of a tree with leaves
  distributed uniformly along its length, and a set of caterpillars
  sitting on the first leaf. (Well, our leaves are big enough to
  accommodate upto 20 caterpillars!). As time progresses our
  caterpillars eat and hop repeatedly, thereby damaging many leaves. Not
  all caterpillars are of the same length, so different caterpillars may
  eat different sets of leaves. We would like to find out the number of
  leaves that will be undamaged at the end of this eating spree. We
  assume that adjacent leaves are a unit distance apart and the length
  of the caterpillars is also given in the same unit.

  For example suppose our branch had 20 leaves (placed 1 unit apart) and
  3 caterpillars of length 3, 2 and 5 units respectively. Then, first
  caterpillar would first eat leaf 1, then hop to leaf 4 and eat it and
  then hop to leaf 7 and eat it and so on. So the first caterpillar
  would end up eating the leaves at positions 1,4,7,10,13,16 and 19. The
  second caterpillar would eat the leaves at positions
  1,3,5,7,9,11,13,15,17 and 19. The third caterpillar would eat the
  leaves at positions 1,6,11 and 16. Thus we would have undamaged leaves
  at positions 2,8,12,14,18 and 20. So the answer to this example is 6.

Fortunately, the question is easy and can put a workable code in a decent time. The problem is that it is probably taking more memory than expected, because all the test cases run fine in my PC, but one of them gives a runtime error when run on the servers. How can this be improved?

#include <iostream>
#include <vector>
#include <algorithm>

int main (int argc, char const* argv[])
{
    long long n , k;
    std::cin >> n >> k;
    std::vector<int> caterpillars;
    std::vector<long long>v;
    for(int i=0;i<k;i++){
        int a;
        std::cin >> a;
        caterpillars.push_back(a);
    }
    for(int i=0;i<k;i++){
        for(int j=0;caterpillars[i]*j +1 <= n;j++){
            int temp = caterpillars[i] * j +1;
            v.push_back(temp);
        }
    }
    sort(v.begin(),v.end());
    int number = 0;
    long long prev = 0;
    for(int i=0;i<v.size();i++){
        if(v[i] != prev){
            number++;
        }
        prev = v[i];
    }
    std::cout << n - number << std::endl;
    return 0;
}

And here is that particular testcase which is causing problems:

762744433 19
96412 40852 19611 563380 236733 559627 750968 413673 300332 65 682403 441221 180068 668364 493413 443706 613246 715846 728157


texts: Circuit-Swap mechanism on going (BMP->PPM)

texts:
Reffering other "Stack Exchange" Sources, I've been told that the only way of swapping BGR to RGB involves buffering. While this isn't true, I could just perofrm a quick C-SA algorithm on fseek or bmp buffer byte offsets. I wrote a fast implementation of fwrite, that swaps the first byte with the 3rd. I do believe that this operation is not slower then the regular one.

size_t fwrite_ps ( const void * ptr, size_t size, size_t count, FILE * stream )
{
    size_t i, chr = 0;
    char p;
    signed pc = 0;

    for(i = 0; i != count * size; i++)
    {
        switch(pc)
        {
            case 1  :   p = 0;          break;
            case 2  :   p = (-2);       break;
            default :   p = 2; pc = 0;  break;
        }

        if( fputc( ((unsigned char*)ptr)[(i+p) - 0], stream ) != EOF ) { chr++; pc++; }
        else                                                           { break; }
    }
    return chr / size;
}

I like my style of codding. For me, it is pretty readable even after years. If it is not as readable for others, it might be because they are most likely used to other, more common styles.

I would like to enhance the utility of this, so i will also provide a really fast way of copying pixels in the proper order. Except functional and fast, it also simplifies varieties of different standarts. It will not copy padding and it involves only one loop.

#define IMAGE_NAME "sample.bmp"

typedef unsigned short WORD;
typedef unsigned long DWORD;

DWORD WIDTH     = BMPDATA[18] + BMPDATA[19] * 256; // Max width 65791
DWORD HEIGHT    = BMPDATA[22] + BMPDATA[23] * 256; // Max height 65791
DWORD h;
FILE* fp = fopen(IMAGE_NAME, "rb");

fprintf(fp, "P6\n%i %i\n%i\n", WIDTH, HEIGHT, 255);  // Copies PPM data

for(h = (HEIGHT-1)*((WIDTH*3) + WIDTH%4); h>=0; h -= (WIDTH*3) + (WIDTH%4))
{
    fwrite_ps(&BMPDATA[BMPDATA[10] + h], 1, WIDTH*3, fp);
}
// BMPDATA is your buffer containing a bmp image.


texts: Lazy properties for the angle and length of a line segment

texts:
The code below shows the pattern I use to manage properties in my classes when I have the following requirements:

Some properties are slow to calculate and are rarely used, so I want them to be lazy
Some methods change the value of a property

The properties are defined the first time they are requested and are deleted when the methods are executed. Calculating the length in the Line class shown in the example is fairly fast, but calculating the Length of a shape made of many Lines would be slow and must be avoided unless required. The full code include many more properties and the list in _reset_attributes([...]) can have dozens of items.

Is this the correct/pythonic/fast way of managing properties?

class Line:
    @property
    def angle(self):
        try:
            return self._angle
        except AttributeError:
            self._angle = math.atan2(self.end.y - self.start.y, self.end.x - self.start.x)
            return self._angle

    @property
    def length(self):
        try:
            return self._length
        except AttributeError:
            self._length = math.sqrt((self.end.x - self.start.x) ** 2 + (self.end.y - self.start.y) ** 2)
            return self._length

    def rotate(self, pivot_point, angle):
        self.start.rotate(pivot_point, angle)
        self.end.rotate(pivot_point, angle)
        self._reset_attributes(['_angle'])

    def scale(self, pivot_point, factor):
        self.start.scale(pivot_point, factor)
        self.end.scale(pivot_point, factor)
        self._reset_attributes(['_length'])

    def _reset_attributes(self, attributes):
        for attribute in attributes:
            try:
                delattr(self, attribute)
            except:
                pass


texts: Guess how many are in the jar game in Java

texts:
I'm reading up on java and have completed a fairly simple console game.

I'm unsure on my own structure when considering maintainability, separation of concerns and best practices.

Any tips or suggestions is appreciated.

import java.io.*;
import java.util.Scanner;
import java.util.*;

class Prompter {
    private static Scanner scanner = new Scanner(System.in);

    public Prompter() {}

    public static String getInput(String title) {
        System.out.print(title);
        String input = scanner.nextLine();

        return input;
    }

    public static void getReadyforGame() {
        String line;

        do {
            System.out.print("Ready? (press ENTER to start guessing): ");

        } while ((line = scanner.nextLine( )).length( ) > 0);
    }

    public static void getGuess(Jar jar) {
        System.out.print("\nGuess: ");
        int answer = scanner.nextInt();

        while (answer != jar.getNumberToGuess()) {
            jar.incrementNumberOfGuesses();

            System.out.print("Guess: ");
            answer = scanner.nextInt();
        }

    }

    public static void printResult(Jar jar) {
        System.out.println("\nCongratulations - you guessed that there are " +
                            jar.getNumberToGuess() + " lentils in the jar! It took you " +
                            jar.getNumberOfGuesses() + " guess(es) to get it right.\n");
    }

}

class Jar {
    private String itemName;
    private int numberOfItems;
    private int numberToGuess;
    private int numberOfGuesses;

    public Jar(String itemName, int numberOfItems) {
        this.itemName = itemName;
        this.numberOfItems = numberOfItems;
        this.numberToGuess = new Random().nextInt(numberOfItems) + 1;
        this.numberOfGuesses = 1;
    }

    public String getItemName() {
        return itemName;
    }

    public int getNumberOfItems() {
        return numberOfItems;
    }

    public int getNumberToGuess() {
        return numberToGuess;
    }

    public int getNumberOfGuesses() {
        return numberOfGuesses;
    }

    public void incrementNumberOfGuesses() {
        ++numberOfGuesses;
    }
}

class Admin {
    private Prompter prompter;

    public Admin () {}

    public Jar setupGame() {
        System.out.print("ADMINISTRATOR SETUP\n" +
                         "===========================\n\n");

        boolean success     = false;
        int numberOfItems   = 0;
        String itemName     = prompter.getInput("Name of items in the jar: ");

        while (!success) {
            try {
                numberOfItems   = Integer.parseInt(prompter.getInput("Maximum of lentils in the jar: "));
                success = true;
            } catch (Exception e) {
                System.out.println("Number of items was invalid");
            }
        }

        return new Jar(itemName, numberOfItems);
    }
}

class Player {
    private Prompter prompter;

    public Player() {}

    public void playGame(Jar jar) {

        System.out.print("\n\nPLAYER\n" +
                         "===========================\n" +
                         "Your goal is to guess how many lentils are in the jar. Your guess should be between 1 and " + jar.getNumberOfItems() + "\n\n");

        prompter.getReadyforGame();

        prompter.getGuess(jar);

        prompter.printResult(jar);
    }
}

class Game {
    private Admin admin;
    private Player player;
    private Prompter prompter;
    private Jar jar;

    public Game() {}

    public void start() {
        admin = new Admin();
        player = new Player();

        jar = admin.setupGame();

        player.playGame(jar);

    }
}

class Test {
    public static void main(String[] args) {
        Game game = new Game();

        game.start();

    }
}


texts:
Below is my attempt at a doubly-linked list in Python (3):

class LinkedListNode:
    def __init__(self, value):
        self.value = value
        self.left  = None
        self.right = None

class LinkedList:
    def __init__(self):
        self.head = self.tail = None
        self.size = 0

    def get_first(self):
        if self.head:
            return self.head.value
        raise Exception('Reading from an empty list.')

    def get_last(self):
        if self.tail:
            return self.tail.value
        raise Exception('Reading from an empty list.')

    def add_first(self, value):
        node = LinkedListNode(value)
        if self.head:
            node.right = self.head
            self.head.left = node
            self.size += 1
        else:
            self.head = self.tail = LinkedListNode(value)
            self.size = 1

    def add_last(self, value):
        node = LinkedListNode(value)
        if self.tail:
            node.left = self.tail
            self.tail.right = node
            self.size += 1
        else:
            self.head = self.tail = node
            self.size = 1

    def remove_first(self):
        if self.head:
            ret = self.head.value
            self.head = self.head.right
            self.head.left = None
            self.size -= 1
            return ret
        raise Exception('Removing from an empty list.')

    def remove_last(self):
        if self.tail:
            ret = self.tail.value
            self.tail = self.tail.left
            self.tail.right = None
            self.size -= 1
            return ret
        raise Exception('Removing from an empty list.')

    def __repr__(self):
        str = '['
        if self.size > 0:
            str += self.head.value
            node = self.head.right
            while node:
                str += ', ' + node.value
                node = node.right
        return str + ']'

def main():
    list = LinkedList()

    while True:
        cmd_line = input()
        if cmd_line == 'quit':
            break
        command_tokens = cmd_line.split()
        command = command_tokens[0]
        try:
            if command == "get_first":
                print(list.get_first())
            elif command == "get_last":
                print(list.get_last())
            elif command == "add_first":
                list.add_first(command_tokens[1])
            elif command == "add_last":
                list.add_last(command_tokens[1])
            elif command == "remove_first":
                list.remove_first()
            elif command == "remove_last":
                list.remove_last()
            elif command == "print":
                print(list)
        except Exception:
            print("Unknown command")

main()

How would I rewrite it in a professional manner?


texts:
This method should check whether a number is a palindrome or not:

typedef enum { false, true } Bool;

Bool is_pal(int n) {
  Bool is_pal_helper(const char *arr, size_t size);

  char temp[12];                         // INT_MIN == '-' + 10 digits (+ null-Terminator)
  sprintf(temp, "%d", n);
  return is_pal_helper(temp, strlen(temp));
}

Bool is_pal_helper(const char *arr, size_t size) {
  if (size <= 1)
    return true;

  if (*arr != *(arr+size-1))
    return false;

  return is_pal_helper(arr+1, size - 2);
}

This was my intuitive solution and I was wondering, if it would be more efficient to keep the number an int, copy and reverse (with modulo and divide-operations) the int and check whether the (reversed) copy is equal to the original int.


texts:
I made a playground to try find prime factors of any given number, and it works, and I'm happy with the first function, even if not correctly named - I don't know what to name it.

My main need for improvement is in the second half. I can't for the life of me think of a way of looping through a list until the functions output is constant. I thought of recursion, but I didn't understand it. This is what I came up with, and I'd like to see how I can improve it because it's sloppy and ugly.

import UIKit

func primeFact(tree: [Int]) -> Array<Int> {
    var newTree = tree
    for element in newTree{
        for divisor in 2..<element{
            if element%divisor == 0{
                newTree = newTree.filter { $0 != element}
                newTree+=[(element/divisor),divisor]
                break
            }
        }
    }
    return newTree
}

var initial = primeFact(tree: [992])
var temp = [Int]()
while true {
    if primeFact(tree: initial) == initial{
        break
    }
    temp = primeFact(tree: initial)
    initial = temp
}
print(primeFact(tree: initial))


texts:
I am fairly new to Python and programming. I created this simple calculator inspired by my physics class. However, I feel this code could have been done more efficiently. Is there any advice for efficiency?

import math

#calculates vector x component
#x = side length y = angle

def fxcomponent(x, y):
  number = x
  y = math.cos(math.radians(y))
  result = number * y
  return result

#calculates vector y component
def fycomponent(x, angle):
  number = x
  angle = math.sin(math.radians(angle))
  result = number * angle
  return result

prompt = 'Welcome to my Python vector components calculator!'
prompt += '\nPlease select what you wish to find: \n-type x for x-component
prompt += '\n-type y for y-component'\n-type quit to end program'

flag = True

while flag == True:
  number = input(prompt + '\n>')

  #ends program when quit
  if number.lower() == 'quit':
    flag = False

#calculates x component and continues with y component if desired
  elif number.lower() == 'x':
    print ('Please tell me the x and the angle:')
    x, angle = [int(x) for x in input('>').split()]
    result = fxcomponent(x, angle)
    print('The x component of %d at %d° is: %d' % (x, angle, result))

    answer = input('Now do you wish to find the y component? \nType Y/N\n>')

    if answer.lower() == 'y':
      print ('Please tell me the y and the angle:')
      y, angle = [int(x) for x in input('>').split()]
      result = fycomponent(y, angle)
      print('The y component of %d at %d° is: %d' % (y, angle, result))

    elif answer.lower() == 'n':
      print('Thanks for using my program! See you later!')
      flag = False

    elif answer.lower() != 'y' or 'n':
      print('Invalid command! try again')

#calculates y component and continues with x component if desired
 elif number.lower() == 'y':
  print ('Please tell me the y and the angle:')
  y, angle = [int(x) for x in input('>').split()]
  result = fycomponent(y, angle)
  print('The y component of %d at %d° is: %d' % (y, angle, result))

  answer = input('Now do you wish to find the x component? \nType Y/N\n>')

  if answer.lower() == 'y':
     print ('Please tell me the y and the angle:')
     y, angle = [int(x) for x in input('>').split()]
     result = fycomponent(y, angle)
     print('The x component of %d at %d° is: %d' % (x, angle, result))

  elif answer.lower() == 'n':
     print('Thanks for using my program! See you later!')
     flag = False

  elif answer.lower() != 'y' or 'n':
     print('Invalid command! try again')

  else:
    print ('Invalid command; try again!')
    continue


texts:
I need to create an image on the fly where one large image covers a small image. The large image is a mask which makes the underlying image visible. Here is a quick sketch of what I'm trying to accomplish:

It's important that Y lies beneath X.

I have created to code for this and it works, but I was wondering how I can make the code more efficient. This is what I have:

    // Create a blank image with the underlying image correctly positioned
    $blank = imagecreatetruecolor(403, 403);
    $profile = imagecreatefromjpeg('img.jpg');
    $w = imagesx($profile);
    $h = imagesy($profile);
    imagecopy($blank, $profile, 0, 140, 0, 0, $w, $h);
    imagejpeg($blank, 'tmp.jpg', 100);

    // Frame overlay
    $frame = imagecreatefrompng('frame.png');
    $photo = imagecreatefromjpeg('tmp.jpg');
    imagecopy($photo, $frame, 0, 0, 0, 0, 403, 403);
    imagejpeg($photo, 'output.jpg', 100);

    // Garbage collection
    unlink('tmp.jpg');
    imagedestroy($blank);
    imagedestroy($profile);
    imagedestroy($frame);
    imagedestroy($photo);

I just think that creating 2 different images is just overkill, but I just can't find a better solution.


texts: Calculation of duration between two timestamps in different rows

texts:
In my sample data table below, all datatypes are varchar(255).

|      event      |            timestamp           |       traceid       |
| accepted        | 2016-01-16T09:35:48.653418931Z | AIP1452936948-44467 |
| published_event | 2016-01-16T09:35:48.659767348Z | AIP1452936948-44467 |

Here is the expected output:

|       traceid       | duration |
| AIP1452936948-44467 |   108    |

And the code I would like reviewed...

select traceid, bUnixMS - aUnixMS as duration
from (
select
a.traceid,
CONVERT(UNIX_TIMESTAMP(STR_TO_DATE(a.mydatetime,'%Y-%m-%d %H:%i:%s')), SIGNED) as aUnix,
CONVERT(UNIX_TIMESTAMP(STR_TO_DATE(b.mydatetime,'%Y-%m-%d %H:%i:%s')), SIGNED) as bUnix,
(CONVERT(UNIX_TIMESTAMP(STR_TO_DATE(a.mydatetime,'%Y-%m-%d %H:%i:%s')), SIGNED) + (CONVERT(LEFT(a.ms, 3), SIGNED) / 1000)) * 1000 as aUnixMS,
(CONVERT(UNIX_TIMESTAMP(STR_TO_DATE(b.mydatetime,'%Y-%m-%d %H:%i:%s')), SIGNED) + (CONVERT(LEFT(b.ms, 3), SIGNED) / 1000)) * 1000 as bUnixMS,
CONVERT(LEFT(a.ms, 3), SIGNED) as aMS,
CONVERT(LEFT(b.ms, 3), SIGNED) as bMS

from (
   select
      event,
      traceid,
      CONCAT(SUBSTRING_INDEX(timestamp, 'T', 1), ' ', SUBSTRING_INDEX(SUBSTRING_INDEX(timestamp, 'T', -1), '.', 1)) as mydatetime,
      SUBSTRING_INDEX(SUBSTRING_INDEX(timestamp, 'T', -1), '.', -1) as ms
   from applogs
   where event = "accepted"
) a

join (
   select
      event,
      traceid,
      CONCAT(SUBSTRING_INDEX(timestamp, 'T', 1), ' ', SUBSTRING_INDEX(SUBSTRING_INDEX(timestamp, 'T', -1), '.', 1)) as mydatetime,
      SUBSTRING_INDEX(SUBSTRING_INDEX(timestamp, 'T', -1), '.', -1) as ms
   from applogs
   where event = "published_event"
) b on a.traceid = b.traceid
) as x


texts: A partition algorithm for positive integers

texts:
I have encountered the following problem that I found very interesting to solve:

  Given an array of positive integers {a1, a2, ..., an} you are required
  to partition the array into 3 blocks/partitions such that the maximum
  of sums of integers in each partition is the minimum it can be.
  Restriction: you cannot alter the turn in which the numbers appear
  (example: if you have {2, 5, 80, 1, 200, 80, 8000, 90} one partition
  CANNOT be the {2, 80, 1, 90}). The program must output ONLY the maximum sum, not the partitions.

So, for example let's have the array:

{2, 80, 50, 42, 1, 1, 1, 2}

The best partitioning according to the problem is:

{ {2, 80}, {50}, {42, 1, 1, 1, 2} }

so the output of the program in this case would be 82.

I have already thought of a \$O(n^2)\$ algorithm, but isn't there any better (e.g. \$O(n)\$ or \$O(n\log n)\$) algorithm?

My \$O(n^2)\$ algorithm:

#include <stdio.h>
#include <iostream>

using namespace std;

int main() {

    int n, *arr, onee = 0, twoo, threee, total = 0, maxx = -1, temp_maxx;

    cin >> n;
    arr = new int[n];

    for (int i = 0; i < n; i++) {
        cin >> arr[i];
        total += arr[i];
    }

    // O(n^2) is the following

    for (int i = 1; i < n - 1; i++) {
        onee += arr[i - 1];
        twoo = 0;
        for (int j = i + 1; j < n; j++) {
            twoo += arr[j - 1];
            threee = total - twoo - onee;
            temp_maxx = max(max(onee, twoo), threee);
            if ((temp_maxx < maxx) || (maxx == -1))
                maxx = temp_maxx;
        }
    }

    cout << maxx;

    return 0;
}


texts: Calculating the distance squared between all vertex-pairs of a number of 2D polygons

texts:
I have implemented my code using Cython. It is the current bottleneck in my computations.

There are two non-numpy functions involved:

calculate_2D_dist_squared which calculates the distance squared between two points
calculate_2D_dist_squared_matrix which generates the distances squared between every two distinct vertices. calculate_2D_dist_squared_matrix organizes results so that dist_squared_matrix[1, 2, 3, 4] = "the distance between polygon 1, vertex 2 and polygon 3, vertex 4". All indexing starts from 0.

cdef double calculate_2D_dist_squared(self, np.ndarray[np.float64_t, ndim=1] p1, np.ndarray[np.float64_t, ndim=1] p2):
    cdef np.ndarray[np.float64_t, ndim=1] relative_vector = p1 - p2

    return relative_vector[0]**2 + relative_vector[1]**2

cdef np.ndarray[np.float64_t, ndim=4] calculate_2D_dist_squared_matrix(self, np.ndarray[np.float64_t, ndim=3] polygons_vertex_coords, int num_polygons, int num_vertices):
    cdef:
        int pi_focus
        int vi_focus
        int pi
        int vi
        # at initialization, set all dist_squared values to be -1,
        # indicating that they have been initialized, but not set properly
        # since by definition a dist_squared value has to be >= 0
        np.ndarray[np.float64_t, ndim=4] result  = -1*np.ones((num_polygons, num_vertices, num_polygons, num_vertices), dtype=np.float64)

    for pi_focus in range(num_polygons):
        for vi_focus in range(num_vertices):
            for pi in range(num_polygons):
                for vi in range(num_vertices):
                    # if a dist_squared < 0, then it means that it
                    # it has not been changed since initialization, and
                    # needs to be updated, this way I avoid repeating work
                    if result[pi_focus, vi_focus, pi, vi] < 0:
                        dist_squared = self.calculate_2D_dist_squared(polygons_vertex_coords[pi_focus, vi_focus], polygons_vertex_coords[pi, vi])
                        result[pi_focus, vi_focus, pi, vi] = dist_squared
                        result[pi, vi, pi_focus, vi_focus] = dist_squared

    return result

What are some things I could think about in order to increase the performance of my code?

For the time being, I got a significant improvement in performance by only re-calculating updates to the dist_squared_matrix, rather than always re-calculating the dist_squared_matrix entirely every step.


texts: Splitting a string by spaces without space-splitting elements in double-quotes

texts:
I need to split a command like:

r'  "C:\Program Files (x86)\myeditor" "$FILEPATH" -n$LINENO "c:\Program Files" -f$FILENAME -aArg2'`

into:

['"C:\\Program Files (x86)\\myeditor"',
 '"$FILEPATH"',
 '-n$LINENO',
 '"c:\\Program Files"',
 '-f$FILENAME',
 '-aArg2']

That is, I want to split by spaces, but avoid splitting the elements in double-quotes.

I have this code:

import re

s = r'  "C:\Program Files (x86)\myeditor" "$FILEPATH" -n$LINENO "c:\Program Files" -f$FILENAME -aArg2'

start = end = 0
split = []

for elem in re.findall('".*?"', s):
    end = s.find(elem)
    split.append(s[start:end])
    split.append(elem)
    start = end + len(elem)

split.extend(s[start:].split())
split = [elem.strip() for elem in split]
split = list(filter(None, split))

It works, but I'm wondering if there's some more elegant/shorter/more readable way to do that in Python(3) ?


texts: Find all sub matrices of type N*M in it which are palindromic

texts:
Today I had an interview, where I was asked to solve this question.

A \$N*M\$ matrix is called a palindromic matrix, if for all of its rows and columns, elements read from left to right in a row are same as elements read from right to left, and similarly, elements read from top to bottom in a column are same as elements read from bottom to top in the column.

Example: below matrices are palindromic

3*5 Matrix

1 2 2 2 1
2 1 1 1 2
1 2 2 2 1

  Given a matrix, find all submatrices of type \$N*M\$ in it which are palindromic. If the original matrix is a palindrome, print it as well.
  Constraints: \$2 <= N, 2 <= M\$

  I wrote this code, How do I improve its complexity?

def check_palindrome(mat):
    if mat:
        m = len(mat)
        n = len(mat[0])
        for i in xrange(m/2 + 1):
            for j in xrange(n/2 + 1):
                if mat[i][j] != mat[m-1-i][j] or mat[i][j] != mat[i][n-1-j] or mat[i][j] != mat[m-1-i][n-1-j]:
                    return False

    return True

def check_submatrix_palindome(mat):
    m = len(mat)
    n = len(mat[0])

    for i in xrange(m-1):
        for j in xrange(n-1):
            for k in xrange(i+2,m):
                for l in xrange(j+2,n):
                    sub_mat = [mat[x][j:l+1] for x in xrange(i,k+1)]
                    if check_palindrome(sub_mat):
                        print "palindrome =", sub_mat

    return

m = int(raw_input())
mat = []
for i in xrange(m):
    row = []
    row = map(int, raw_input().strip().split(' '))
    mat.append(row)

check_submatrix_palindome(mat)


texts:
I am piggybacking an iterator-based implementation of merge-sort to count array inversions. My first correct solution looks as follows:

#include <vector>
#include <iterator>
#include <stdio.h>

template<typename It>
std::vector<typename It::value_type> SortAndCountInversionsSubroutine(const It begin, const It middle, const It end, unsigned int& count)
{
    std::vector<typename It::value_type> v;
    It left{ begin }, right{ middle };
    while (left != middle && right != end)
    {
        if (*left <= *right)
        {
            v.push_back(*left++);
        }
        else
        {
            count+= std::distance(left, middle);
            v.push_back(*right++);
        }
    }
    v.insert(v.end(), left, middle);
    v.insert(v.end(), right, end);
    return v;
}

template<typename It>
void SortAndCountInversions(It begin, It end,unsigned int& count)
{
    auto size = std::distance(begin, end);
    if (size < 2)
        return;
    auto mid = std::next(begin, size / 2);
    SortAndCountInversions(begin, mid, count);
    SortAndCountInversions(mid, end, count);
    auto v = SortAndCountInversionsSubroutine(begin, mid, end, count);
    std::move(v.cbegin(), v.cend(), begin);
}

The implementation can be used as follows:

std::vector<int> v1{ 1, 3, 5, 2, 4, 6 };
unsigned int inversionCount = 0;
unsigned int expectedCount = 3;
SortAndCountInversions(v1.begin(), v1.end(), inversionCount);
Assert::AreEqual(expectedCount, inversionCount);

inversionCount = 0;
expectedCount = 5;
std::vector<int> v2{ 1, 20, 6, 4, 5 };
SortAndCountInversions(v2.begin(), v2.end() , inversionCount = 0);
Assert::AreEqual(expectedCount, inversionCount);

I am looking for any suggestions to improve my code. Particularly, I would like to return the inversion count as a return value, instead of a parameter reference. Any ideas?


texts: Reduce the code in a WHERE clause without using dynamic SQL

texts:
How can I write the following T-SQL query part in a shorter way without using dynamic SQL?

WHERE
    ( (@Max IS NULL OR @Type <> 'Products')
        OR (@Max IS NOT NULL AND @Type = 'Products'
            AND ProductCount >  @Max ) )

    AND ( (@Min IS NULL OR @Type <> 'Products')
        OR (@Min IS NOT NULL AND @Type = 'Products'
            AND ProductCount <  @Min ) )

    AND ( (@Max IS NULL OR @Type <> 'Vendors')
        OR (@Max IS NOT NULL AND @Type = 'Vendors'
            AND VendorCount >  @Max ) )

    AND ( (@Min IS NULL OR @Type <> 'Vendors' )
        OR (@Min IS NOT NULL AND @Type = 'Vendors'
            AND VendorCount <  @Min ) )

    AND ( (@Max IS NULL OR @Type <> 'Order')
        OR (@Max IS NOT NULL AND @Type = 'Order'
            AND OrderCount >  @Max ) )

    AND ( (@Min IS NULL OR @Type <> 'Order')
        OR (@Min IS NOT NULL AND @Type = 'Order'
            AND OrderCount <  @Min ) )


texts: Sum to zero of all triples in a list - n^2 running time

texts:
As part of an interview, I had to submit a code sample to solve the classical "triples sum to 0" problem. The reviewer said the algorithm needed to be in n2 time, and I was later informed that the code I wrote did not accomplish this.

Can you guys help me identify where I went wrong? I've written comments explaining my thought process.

# Small struct to hold the values we need for computing unique sums
DoubleSum = namedtuple('DoubleSum', 'arg_sum int1 int2 int1_index int2_index')

def sum_zero(integers: [int]) -> [(int, int, int)]:
    """
    Given a list of integers, compute all triples that sum to 0
    :param integers: The integers to arrange
    :return: All triples that sum to 0, or [] if there are no sums
    """
    # Check for trivial issues
    if integers is None or len(integers) < 3:
        raise ValueError("Must have an input of at least 3 integers to check.")

    s_integers = sorted(integers)

    # Compute all unique possible sums of two integers
    # Should run in n^2
    sums = []
    for i in range(0, len(s_integers)):
        for j in range(i+1, len(s_integers)):
            int1 = s_integers[i]
            int2 = s_integers[j]
            sums.append(DoubleSum(int1+int2, int1, int2, i, j))

    # For each integer, find all two-element sums that would equal 0
    # Should be n^2 - for each integer, find all double sums that match it
    triples = []
    for i in range(0, len(s_integers)):
        current = s_integers[i]
        matches = filter(lambda s: s.arg_sum == -current, sums)
        for match in matches:
            test_triple = (i, match.int1_index, match.int2_index)
            # If the current index isn't below both indices in the sum,
            # we have come across another permutation of a previous sum to 0
            if i < match.int1_index and i < match.int2_index:
                triples.append(test_triple)

            # We could reduce the runtime if we added a break statement to the
            # else clause, but that seems to introduce errors after maintenance
            # when nobody quite remembers what the break did in the first place

    # Map the indices in `triples` to the actual values
    return [(s_integers[t[0]],
             s_integers[t[1]],
             s_integers[t[2]]) for t in triples]