texts: Find group of available stalls in an aisle

texts:
An aisle is defined as two rows of six stalls each.  A stall is adjacent to another if it is directly next to it or across from it.  My method finds out how many stalls can be found in a chain from the stall currently being worked with that are available for use.  For example, * is a stall that is already occupied, and . is a stall that is available.  With an aisle like this:

...*..
......

the get_available_adjacents method of the top left stall would return a set of eleven stalls, every stall except the occupied one.  With

...*..
...*..

the top left stall would return a set of six stalls because the occupied ones form a break in the line.  One of the occupied ones, however, would return a set of ten stalls because it is connected to both groups of available stalls.  My solution below seems inefficient.  With only twelve stalls per aisle, it is figured out quickly enough, but I would like to know if there is a more efficient solution.

It works by creating a set found to store all of the stalls that we find.  It also creates a set used that contains all stalls for which the get_available_adjacents method has been called.  It then loops through each adjacent of the current stall, and if it is available, adds it to the used set and updates found by calling the adjacent's get_available_adjacents method.

class Stall:
    def __init__(self, occupant=None):
        self.occupant = occupant
        self.available = True

    def get_available_adjacents(self, used=None):
        if used is None:
            used = {self}

        found = set()
        if self.available:
            found.add(self)

        for adjacent in self.adjacents:
            if adjacent in used or not adjacent.available:
                continue
            used.add(adjacent)
            found.update(adjacent.get_available_adjacents(used))
        return found

For testing:

class Aisle:
    def __init__(self, row_length=6):
        self.top = [Stall() for _ in range(row_length)]
        self.bottom = [Stall() for _ in range(row_length)]

        self.top[0].adjacents = (self.top[1], self.bottom[0])
        self.top[-1].adjacents = (self.top[-2], self.bottom[-1])
        self.bottom[0].adjacents = (self.bottom[1], self.top[0])
        self.bottom[-1].adjacents = (self.bottom[-2], self.top[-1])

        for i, (t, b) in enumerate(zip(self.top[1:-1], self.bottom[1:-1]), 1):
            t.adjacents = (self.top[i-1], self.top[i+1], b)
            b.adjacents = (self.bottom[i-1], self.bottom[i+1], t)

aisle = Aisle()
print(aisle.top[0].get_available_adjacents()) # gives 12 results
aisle.top[2].available = False
print(aisle.top[0].get_available_adjacents()) # gives 11 results
aisle.bottom[2].available = False
print(aisle.top[0].get_available_adjacents()) # gives 4 results
print(aisle.top[2].get_available_adjacents()) # gives 10 results


texts: Reducing a large array of objects to a simple object with 8 properties

texts:
I'm reducing a large array of objects to a simple object with 8 properties. I'm currently using Array.prototype.reduce to loop through the array of objects to create a new object. In order to assign a correct key to the value in the array I'm using a switch statement. My code currently works, but I'm looking to refine it. I have no control over the API and how it returns its response.

The array of objects that are returned look like this:

[
  {
    field_id:89107336,
    values : [{ value:"Star Warz"}]
  },
  {
    field_id:89107337,
    values : [{ date:"December 24, 2015"}]
  },
  {
    field_id:89107415,
    values : [
               {
                 value: { item_id:1234123}
               },
               {
                 value: { item_id:4746576}
               }
  },
  {
    field_id:89107340,
    values : [{ value:"5.00"}]
  },
  {
    field_id:89107344,
    values : [{ value:"This is description"}]
  },
  {
    field_id:89107348,
    values : [
               {
                 value:{file_id:234234}
               }
             ]
  }
]

The object values come back random at times, so the only way for me to tell the difference between the title, the date, description, etc. Is for me to run the response through a switch statement based upon field_id. So I created an object like so:

var eventFieldIds = {
        title: 89107336,
        date: 89107337,
        attendees: 89107415,
        price: 89107340,
        desc: 89107344,
        img: 89107348
    };

Then I use a switch statement to reduce the array objects  like this:

var newEvent = arrayObjects.reduce(function(p, c) {
    switch (c.field_id) {
        case eventFieldIds.title:
            {
                p.name = c.values[0].value;
                break;
            }
        case eventFieldIds.date:
            {
                p.date = new Date(c.values[0].start_date);
                break;
            }
        case eventFieldIds.attendees:
            {
                //this is an array of values
                var tempArray = c.values.map(function(v) {
                    return value.value.item_id;
                });
                p.attendees = JSON.stringify(tempArray);
                break;
            }
        case eventFieldIds.price:
            {
                p.price = c.values[0].value;
                break;
            }
        case eventFieldIds.desc:
            {
                p.description = c.values[0].value;
                break;
            }
        case eventFieldIds.img:
            {
                p.img = {
                    file_id: c.values[0].value.file_id
                };
                break;
            }
    }

    return p;
}, {});

How can I refine this? Can I cut out the switch statement? Is there a better way to do this?


texts:
I am working on a JavaScript exercise. I am running into issues with arrays.

NOTE: I posted this code in this forum because the code works. But, I would appreciate people reviewing it, and letting me know there are better ways to do this.

I am creating two arrays.

I am putting items into the first array. These are the separate parts of a string that represent a time: hours:minutes:seconds:milliseconds. You will see the times in the input string in my code.

I am putting those time segments into the first array, and then I am pushing that array into the second array (muti dimensional). I am doing this because I don't know how many times will be in an input string. I am also doing this because I need to eventually add up these times in the input string, and then add another set of time segments from a second input string that I did not include here in this code. (I realize that I have to convert these to numbers eventually.)

I tried the code below without the commented out line:

// arrSubtitlesSeparate = [];

I don't get what I expected.
When I include this line of code, I get the multi dimensional array I want.

Here is the results of the console logs. You will see them if you run the code.

You can see that the times are being found with the regex. But, the multi dimensional array is being filled with the last set of time segments that is found. You can easily see this just by looking at the last three digits which are the milliseconds in the time strings that are found.

found time: 00:13:37,243

arrSubtitlesSepMultiDim: 00,13,37,243

found time: 00:13:39,744

arrSubtitlesSepMultiDim: 00,13,39,744,00,13,39,744

found time: 00:13:39,779

arrSubtitlesSepMultiDim: 00,13,39,779,00,13,39,779,00,13,39,779

found time: 00:13:43,548

arrSubtitlesSepMultiDim: 00,13,43,548,00,13,43,548,00,13,43,548,00,13,43,548

If I add/uncomment that line of code, I get what I want.
The times are all added to the multi dimensional array.

My questions about coding this:

What is the proper way of creating the multidimensional array in this case?

Why is this happening when I don't include that line of code?

Does this have something to do with the fact that the first set of time segment values found in the input string are the first set of values being put into the array?

Would I be better off initializing the sub array with the first set of values, and then using the splice method to replace the values?

Here is my code. You should be able to copy/paste into an HTML doc.

    <script>

var subtitles = "188 00:13:37,243 --> 00:13:39,744 30 minutes. Everyone's ready. 189 00:13:39,779 --> 00:13:43,548 ♪ ";
var arrSubtitles = subtitles.split(" ");

console.log("arrSubtitles: " + arrSubtitles);

var arrSubtitlesSeparate = [];
var arrSubtitlesSepMultiDim = [];

for(var i = 0; i < arrSubtitles.length; i++){
    if(/[0-9]{2}:[0-5][0-9]:[0-5][0-9],[0-9]{3}/.test(arrSubtitles[i]) === true){
        console.log("found time: " + arrSubtitles[i]);
    arrSubtitlesSeparate[0] = arrSubtitles[i].charAt(0) + arrSubtitles[i].charAt(1);
    arrSubtitlesSeparate[1] = arrSubtitles[i].charAt(3) + arrSubtitles[i].charAt(4);
    arrSubtitlesSeparate[2] = arrSubtitles[i].charAt(6) + arrSubtitles[i].charAt(7);
    arrSubtitlesSeparate[3] = arrSubtitles[i].charAt(9) + arrSubtitles[i].charAt(10) + arrSubtitles[i].charAt(11);
    arrSubtitlesSepMultiDim.push(arrSubtitlesSeparate);
    // arrSubtitlesSeparate = [];
    console.log("arrSubtitlesSepMultiDim: " + arrSubtitlesSepMultiDim);
    }
}

</script>


texts: Finding the largest mirror image of a subset/set of integers present in an array of integers

texts:
The problem I am talking about is this:

  We'll say that a "mirror" section in an array is a group of contiguous
  elements such that somewhere in the array, the same group appears in
  reverse order. For example, the largest mirror section in {1, 2, 3, 8,
  9, 3, 2, 1} is length 3 (the {1, 2, 3} part). Return the size of the
  largest mirror section found in the given array.

  maxMirror({1, 2, 3, 8, 9, 3, 2, 1}) → 3
  maxMirror({1, 2, 1, 4}) → 3
  maxMirror({7, 1, 2, 9, 7, 2, 1}) → 2

Conditions for solving:

No other helper methods.
Do not use Java.util.Arrays.copyOf or any other utility under Arrays
Do not use collections.

The solution I got was a little messy, and any cleaner solutions are welcome.

public int maxMirror(int[] nums) {
  final int len=nums.length;
  if(len==0)
  return 0;
  int maxCount=1;
  boolean flag=false;

  for(int i=0;i<len;i++)
  {
     int tempCount=1;
     int count=i;
     flag=false;

     for(int j=len-1;j>=0&&(count<len);j--)
     {
        if((nums[count]==nums[j])&&!(flag))
        {
          flag=true;
          count++;
          continue;
        }
        if((nums[count]==nums[j])&&(flag))
        {
          tempCount++;
          count++;
          maxCount=(tempCount>maxCount)?tempCount:maxCount;
         continue;
        }
        if(!(nums[i]==nums[j])&&(flag))
        {
          flag=false;
          count=i;
          tempCount=1;
          continue;
        }
        if((j==count)||(j-count)==1)
        {
          flag=false;
          break;
          }

      }
  }
      return maxCount;

}


texts: Join 5 optional strings with a joiner character

texts:
I need to append some query parameters to my API URL. The consumer of my API would pass me this optional structure called as APIParameters, which contain 5 optionals, one array of strings and rest strings

Lets assume the following:

let baseURL = "baseURL"
let path = "path"

This is the final URL structure

//assuming since and offset is nil, this would be the URL
result = "baseURL" + "path" + "?"+ "with=some1,some2,some3&limit=100&width=0"

To solve this, I made a struct, and added a method to return me the string that I need to append to my URL.

struct APIParameters {
    var with: [String]?
    var since: NSDate?
    var width: Int?
    var offset: Int?
    var limit: Int?

    func stringToAppendToURL() -> String{
    //started with this approach

        var stringToAppend = ""

        if with != nil {

            var withParamaters = ",".join(with!)
            println("withParamaters = \(withParamaters)")

            stringToAppend += "with=\(withParamaters)"

        }

        if limit != nil {
            println("limit = \(limit)")

        }
    //realized this would be too long so tried using switch

        switch (with, limit, width, offset, since){
        case (nil, nil, nil, nil, nil):
            return ""
        case (.Some(let withParameters), nil, nil, nil, nil):
            return "with=" + ",".join(withParameters)
        case (nil, .Some(let limitParams), nil, nil, nil):
            return "limit=\(limitParams)"
        case (nil, nil, .Some(let widthParams), nil, nil):
            return "width=\(widthParams)"
        case (nil, nil, nil, .Some(let offsetParams), nil):
            return "offset=\(offsetParams)"
        case (nil, nil, nil, nil, .Some(let sinceParams)):
            return "since=\(Int(sinceParams.timeIntervalSince1970))"
        case (.Some(let withParams), .Some(let limitParams), nil, nil, nil):
        return "with=" + ",".join(withParams) + "&" + "limit=\(limitParams)"
    //realized that number of conditions would become too many so decided to ask for help

        default:
            return ""

        }

    }
}

Example:

let apiParams1 = APIParameters(with: ["option", "full"], since: nil, width: nil, offset: nil, limit: 10)
let apiParams2 = APIParameters(with: ["option", "full"], since: nil, width: nil, offset: nil, limit: nil)

println("\(apiParams1.stringToAppendToURL())")
println("\(apiParams2.stringToAppendToURL())")

  Output:

"with=option,full&limit=10"
"with=option,full"

Is there a more elegant way to do this?


texts: Snippet to get all local classes from a module

texts:
I'm working on a project which due to the complexity of the business logic has had to pull out some classes to do computation related to some values in a database. To link the code and database, both when inserting and selecting, I need to get a list of all the class names contained within a single file. It works for me, but is this a sane approach?

import inspect

import my_module

my_module_class_names = [
    name for name, clazz in inspect.getmembers(my_module, inspect.isclass)
    if clazz.__module__ == my_module.__name__
]

inspect.getmembers(my_module, inspect.isclass) gets any class members of my_module.
if clazz.__module__ == my_module.__name__ ensures that classes imported into my_module are excluded from the list. This is the main reason I'm asking for a review - I only thought to include this clause because I had already imported other classes, and therefore the list had extraneous members.

Alternatively, from within my_module:

import inspect
import sys

def class_names() -> List[str]:
    return [
        name for name, clazz in inspect.getmembers(sys.modules[__name__], inspect.isclass)
        if clazz.__module__ == sys.modules[__name__].__name__
    ]


texts:
Here is my Implementation. It is I think almost like algorithm.

 public static uint[] CountingSort(uint[] A ,uint max)
        {
            uint[] B = new uint[A.Length];
            int[] c = new int[max +1 ];
            for (int j = 0; j < A.Length; j++)
                c[A[j]]++;
            for (int i = 1; i < max + 1; i++)
                c[i] += c[i - 1];
            for (int j = A.Length-1 ; j>=0; j--)
                B[--c[A[j]]] = A[j];

            return B;
        }


texts: Measuring the length of binary numbers in English words in C

texts:
Inspired by this question (link to original video), I decided to write some code in C to perform this task, and it is much faster than the Python code, even when run with PyPY, up to a billion, it takes just 700 seconds.

For \$10^8\$ (a hundred million) it takes 62 seconds, while Python with pypy about 5 minutes!

Task

Given a number transform it into the length of the English one-zero representation: for example 2 is one_zero = 7. Calculate how many of these numbers end in 13 and in 18 when applying this step repeatedly. (All numbers end in one of the two.)

My code is really simple, but I am a beginner in C so I ask you in case I may have missed optimizations:

#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <limits.h>

int letter_sum(int n) {
    int sum = 0;
    while (n != 0) {
        div_t x = div(n, 2);
        n = x.quot;
        sum += x.rem == 0 ? 4 : 3;
    }
    return sum;
}

int ends_in_18(int n) {
  if (n == 18) {return 1;}
  if (n == 13) {return 0;}
  return ends_in_18(letter_sum(n));
}

int main() {
    assert(letter_sum(18) == 18);

    int eighteen_count = 0;
    for (int i = 1; i < 100000000; i++) {
        if (ends_in_18(i)) {
            eighteen_count++;
        }
        else { printf("%d ", i); }
    }
    printf("%d %d\n", 100000000 < INT_MAX, eighteen_count);
}


texts: Get resources inside or outside constructor?

texts:
I need your opinion on writing a constructor that's clean code and unit test friendly.

Option 1 :

var res1 = bigObject.GetResource1();
var res2 = bigObject.GetResource2();
var res3 = bigObject.GetResource3();
var myObject = new Foo(bigObject, res1, res2, res3);
//and the foo ctor just initializes its internal fields with given data

Option 2 :

var myObject = new Foo(bigObject);
[...]
public Foo(Bar bigObject)
{
    _bigObject = bigObject;
    _res1 = _bigObject.GetResource1();
    _res2 = _bigObject.GetResource2();
    _res3 = _bigObject.GetResource3();
}

Option 2 is cleaner (?) in the code (in option 1 I have the feeling I have to spoon-feed the Foo object because it is not smart enough to get what it needs by itself)), but requires helper methods in the tests to mock calls to Get* and pass what we want.

Of course, I can also write both ctors, and use one in the tests and the other in the "real" code, but it'd looks a bit weird and bloated to someone discovering the class, and the simple constructor wouldn't be tested.

What would you advise ?

EDIT :

Resources are not especially linked to the big object (i.e. there is no "wrong" combination). Imagine for example that the big object is a College, and resources are a list of teachers, a list of courses and a list of rooms, and we want to build, say, a timetable.


texts: Cryptographic Random Number Generator function implementation

texts:
While surfing and through some experimentation, I have a new method to generate random numbers without using Randomize or Random or RND. It uses RNGCryptoServiceProvider Class for generating random numbers. We can generate a wide range of positive and negative random numbers with this. I built a function which generate positive and negative random numbers.I wish to share that code with you to make it much better.

We need to import Imports System.Security.Cryptography file to work with the function. Here is the code:

Public Sub Randomgenerator()
    Dim byte_count As Byte() = New Byte(6) {}
    Dim random_number As New RNGCryptoServiceProvider()
    random_number.GetBytes(byte_count)
    Dim Output As Integer = BitConverter.ToInt32(byte_count, 0)
    MsgBox(Output)
End Sub

Suggestions and tips to improve this function are invited.


texts: My implementation of lexicographic permutation in F# is 3x slower than C#

texts:
Can someone help me with the following micro optimization for the F# code for lexicographic permutation?

I have code in C# which runs for 0.8s. As a learning practice, I translated it into F#. However, it becomes 2.9s. Just out of curiosity, I am wondering why my code in F# runs that slow? Are there any improvement can be made to my F# code without changing the algorithm?

C#

 static bool ToNextLexicographic(int[] myArray)
    {
        int pivot = -1;

        for (int i = myArray.Length - 1; i > 0; i--)
        {
            if (myArray[i] > myArray[i - 1])
            {
                pivot = i - 1;
                break;
            }
        }

        if (pivot == -1)
            return false;

        for (int j = myArray.Length - 1; j > pivot; j--)
        {
            if (myArray[j] > myArray[pivot])
            {
                // swap
                var tmp = myArray[j];
                myArray[j] = myArray[pivot];
                myArray[pivot] = tmp;

                // reverse
                for (int i = pivot + 1, k = myArray.Length - 1; i < k;i++,k-- )
                {
                    var tmp = myArray[i];
                    myArray[i] = myArray[k];
                    myArray[k] = tmp;
                }
                break;
            }
        }
        return true;
    }
    static IEnumerable<int[]> GetPermutationsLexicographic(int[] myArray)
    {
        Array.Sort(myArray);
        yield return myArray;

        while (ToNextLexicographic(myArray))
        {
            //yield return myArray.ToArray();
            yield return myArray;
        }
    }

F# (much readable than C#)

let inline toNextLexicographic (myArray: _[]) =
    let rec findPivot i =
        if i = 0 then -1
        else
            if myArray.[i] > myArray.[i-1] then i - 1
            else findPivot (i - 1)

    let rec findTarget value i =
        if (myArray.[i] > value) then i
        else findTarget value (i - 1)

    let inline swap i j =
        let tmp = myArray.[i]
        myArray.[i] <- myArray.[j]
        myArray.[j] <- tmp

    let inline reverse i =
        let mutable a = i
        let mutable b = myArray.Length - 1
        while a < b do
            swap a b
            a <- a + 1
            b <- b - 1

    let pivot = findPivot (myArray.Length - 1)
    if pivot = -1 then false
    else
        let target = findTarget myArray.[pivot] (myArray.Length - 1)
        swap pivot target
        reverse (pivot + 1)
        true;

let inline getPermutationsLexicographic myArray = seq {
    Array.sortInPlace myArray
    yield myArray
    while toNextLexicographic myArray do
        yield myArray
    }

// benchmark
let mutable d = 0
for x in getPermutationsLexicographic([|1..11|]) do
    d <- d + 1
d


texts: Test if two nodes in a binary search tree are cousins

texts:
Cousins are nodes at the same level of the tree, with different parents.
They don't have to share the same grandparent.

My solution depends on having a binary search tree with unique elements.

This code is faster than writing a special find(Node *) that returns the node's level and parent, and comparing results for each node.  If the nodes are not at the same level, this version will only descend down to the level of the node closer to the top, and bail out early.

I'm looking for confirmation that it is correct.

bool are_cousins(Node *root, Node *a, Node *b)
{
    if (a == b || a == nullptr || b == nullptr) {
        return false;
    }

    Node *a_parent = nullptr;
    Node *b_parent = nullptr;
    Node *a_seek = root;
    Node *b_seek = root;
    while (a_seek != nullptr && b_seek != nullptr) {
        if (a == a_seek && b == b_seek) {
            // found both nodes at the same level
            return a_parent != b_parent;
        }

        if (a == a_seek || b == b_seek) {
            // found one node but not the other at this level. bail out
            return false;
        }

        // found neither. seek down one more level
        a_parent = a_seek;
        a_seek = (a->value < a_seek->value) ?
            a_seek->left : a_seek->right;
        b_parent = b_seek;
        b_seek = (b->value < b_seek->value) ?
            b_seek->left : b_seek->right;
    }
    return false;
}


texts:
I've got a piece of code that will run a period task to do a small bit of processing. The task depends on an externally managed connection resource, and if the resource goes away then the task should unschedule itself.

Condensed into a unit test (although lacking any sort of assertions):

@Test
public void testSelfCancelling() throws InterruptedException {
  ScheduledThreadPoolExecutor refreshExecutor = new ScheduledThreadPoolExecutor(2);
  final AtomicReference<Future<?>> futureRef = new AtomicReference<>();

  final AtomicBoolean closed = new AtomicBoolean(false);

  futureRef.set(refreshExecutor.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
      // If the resource has been closed, then cancel this refresh task
      if (closed.get()) {
        Future<?> future = futureRef.get();
        // There may be a race condition here if the directory is closed after this task is scheduled, but before
        // the future is set. It's not a big deal because we will always cancel the task next time.
        if (future != null) {
          future.cancel(false);
        }
        System.out.println("Cancelling!");
      } else {
        System.out.println("Processing!");
      }
    }
  }, 1, 2, TimeUnit.SECONDS));

  refreshExecutor.schedule(new Runnable() {
    @Override
    public void run() {
      closed.set(true);
    }
  }, 6, TimeUnit.SECONDS);

  Thread.sleep(10000);
  refreshExecutor.shutdown();
}

As written, it works correctly. The test will be "processing" three times and then cancel. The whole execution wraps up at the 10 second mark as expected. However, is this safe? I have a nagging feeling that I'm missing some finer point of the concurrency which can lead to a deadlock or other undesirable situation down the road.

In my real use case, there would be multiple tasks, all checking separate resources, all potentially cancelling themselves independently.


texts:
In a YouTube video I watched, the speaker said it is important to know how to calculate between numbers of different bases; i.e. two, ten, and sixteen. I was then inspired to write a small C program to ensure I understand how such conversions are done. I then wrote a short Python2 script to test the program. I'd like any constructive feedback on the coding style, layout, efficiency, and anything else that stands out. Debug lines are commented out.

calc.c

#include <math.h>
#include <stdio.h>
#include <string.h>

typedef enum {
    AND = '&',
    OR = '|',
    XOR = '^',
    NONE = 0
} operator;

typedef enum {
    B02 = 'b',
    B10 = 'd',
    B16 = 'x'
} type;

const char zero = '0';
const char _A = 'A';
const char _a = 'a';

int main(int argc, char **argv) {
    int i, offs, len;
    char *nend;
    long result = 0, tmp, optmp;
    operator op = NONE;
    type ntype;

    for (i = 1; i < argc; i++) {
        len = strlen(argv[i]);
        nend = argv[i] + len - 1;
        if (len == 1) {
            op = *nend;
            continue;
        }
        ntype = *nend;
        nend--;
        offs = 0;
        optmp = 0;
        while (offs < len - 1) {
            switch (ntype) {
            case B02:
                tmp = (*(nend - offs) - zero) * pow(2, offs);
                break;
            case B10:
                tmp = (*(nend - offs) - zero) * pow(10, offs);
                break;
            case B16:
                tmp = *(nend - offs);
                if (tmp >= _a) tmp -= _a - 10;
                else if (tmp >= _A) tmp -= _A - 10;
                else tmp -= zero;
                tmp *= pow(16, offs);
                break;
            }
            optmp += tmp;
            offs++;

        }
//printf("%s: offs: %i tmp: %li optmp: %li len: %i result: %li\n", argv[i], offs, tmp, optmp, len, result);
        switch (op) {
        case AND:
            result &= optmp;
            break;
        case OR:
            result |= optmp;
            break;
        case XOR:
            result ^= optmp;
            break;
        case NONE:
            result += optmp;
            break;
        }
//printf("\n");
    }
    printf("%li\n", result);
    return 0;
}

makecalc.sh

gcc -Wall calc.c -o calc

testcalc.py

import subprocess as subp
import time

_bin = lambda x: bin(x)[2:] + 'b'
_dec = lambda x: str(x) + 'd'
_hex = lambda x: hex(x)[2:] + 'x'

ops = ('&', '|', '^')
types = (_bin, _dec, _hex)
RANGE = 20

tmp = None

def test(op, t, x, y):
    call = ["./calc", t(x), op, t(y)]
    print call
    proc = subp.Popen(call, stdout=subp.PIPE, stdin=subp.PIPE)
    data = proc.stdout.readline().replace("\n", "")
    exec("tmp = %s %c %s;" % (str(x), op, str(y)))
    if tmp != int(data):
        print ("fail", tmp, data)
        quit()

for op in ops:
    for t in types:
        for x in range(RANGE):
            for y in range(RANGE):
                test(op, t, x, y)


texts:
Could you review my code for finding max, min, and mode?

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

int main()
{
    std::vector <int> v = { 2, 5, 3, 4, 3, 2, 3, 3, 3 , 6, 6, 6, 6, 6, 6, 6, 6, 1};
    sort(v.begin(), v.end());
    int number = v[0];
    int max = v[0];
    int min = v[0];
    int mode;
    for (int i = 1, countMode = 1, count = 1; i < v.size(); ++i) {
        if (v[i] == number)
            ++countMode;
        if (countMode > count) {
            count = countMode;
            mode = number;
        }
        if (v[i] > max)
            max = v[i];
        if (v[i] < min)
            min = v[i];
        number = v[i];
    }
    std::cout << max << ' ' << min << ' ' << mode;
}


texts: Moving a cursor with the keyboard in assembly

texts:
I am a beginner in assembly. But that didn't stop me from making a simple operating system completely made in assembly. It's very simple and doesn't do much. It's just a proof of concept. I would like to know what I can improve. Any feedback would be great.

bits 16
mov dl, 0 ; Cursor position column
mov dh, 0 ; Cursor position row

; Draw a really simple UI
; Draws a blue background
mov ah, 09h
mov al, 32
mov bl, 10h
mov cx, 1000h
int 10h

; Draws a gray bar
mov ah, 09h
mov al, 32
mov bl, 70h
mov cx, 160d
int 10h

main:
    ; Waits for a key press
    mov ah, 00h
    int 16h

    ; Compare the al register to see what key the user pressed

    ; If the user pressed the 's' key move the cursor down
    cmp al, 115
    je Down

    ; If the user pressed the 'w' key move the cursor up
    cmp al, 119
    je Up

    ; If the user pressed the 'a' key move the cursor left
    cmp al, 97
    je Left

    ; If the user pressed the 'd' key move the cursor right
    cmp al, 100
    je Right

    ; If the user pressed the Space Bar make the background of the   cursor magenta
    cmp al, 32
    je SpaceBar

    ; Jump back to main
    jmp main

    ; Our functions
    SpaceBar:
          mov ah, 09h
          mov bl, 50h
          mov cx, 1d
          int 10h
          jmp main

    Right:
        add dl, 1
        call SetCursor
        jmp main
        ret

    Left:
      sub dl, 1
      call SetCursor
      jmp main
      ret

   Up:
     sub dh, 1
     call SetCursor
     jmp main
     ret

   Down:
      add dh, 1
      call SetCursor
      jmp main
      ret

   SetCursor:
       mov ah, 02h
       mov bh, 00
       int 10h
       ret

 times 510-($-$$) db 0
 dw 0xAA55


texts: Sorted unidirectional list with add, delete and find

texts:
I am aware of the fact that a sorted unidirectional list has only very few use cases, but nevertheless, this python code feels fairly long for Python code. How can I improve it?

class List:
    def __init__(self, list):
        self.first = list

    def __repr__(self):
        element = self.first
        elementsList = ''
        while (element != None):
            elementsList += str(element) + '\n'
            element = element.next
        return elementsList

    """Searches for names in list, starts at 0, returns predecessor as object if possible, returns -1 if not found"""
    def search(self, name):
        if self.first.name == name:
            return 0
        else: return self.search_rec(self.first, name, 1)

    """Recursive workhorse for search"""
    def search_rec(self, item, name, i):
        if item.next != None:
            if item.next.name == name:
                return i, item.name
            else:
                return self.search_rec(item.next, name, i+1)
        else: return -1

class Element:
    """Class to implement elements of the list"""

    """Append item to list or create one"""
    def __init__(self, name, listPos=None):
        if listPos != None:
            listPos = listPos.parent.first
            self.parent = listPos.parent
            previous = None
            while (listPos.name < name and listPos.next != None):
                previous, listPos = listPos, listPos.next
            if previous != None:
                previous.next, self.next = self, listPos
            else: self.parent.first = self
        else:
            self.parent = List(self)
        self.name = name
        self.next = listPos

    def __del__(self):
        print(repr(self) + ' dies now...')

    def delete(self):
        if (self == self.parent.first): self.parent.first = self.next
        else:
            listPos = self.parent.first
            while (listPos.next != self):
                listPos = listPos.next
            if listPos.next.next != None: listPos.next = listPos.next.next
            else: listPos.next = None

    def __repr__(self):
        return '[%s]' % self.name

    def __str__(self):
        if self.next != None:
            next = 'Next element: ' + self.next.name
        else:
            next = '*end of the list*'
        return repr(self) + '\n' + next

x = Element('test')
a = Element('d', x)
y = Element('c', x)
z = Element('a', x)

print(x.parent)

a.delete()

print(a.parent)

print(x.parent.search('c'))


texts: Number of occurence of two letters separted by a finit gap

texts:
Lets we have a string Seq of size N and contain z alphabet { A,B,C….}.
I have to perform a function that calculates number of occurrence of letter i which is separated with l letters (gap) form the letter j:
Example:

I=A, j=T and gap=10
That have to find the number of occurrence of AT,A-T,A--T,A---T,A----T,,,A----------T(- is any alphabet)

I used this code for DNA sequence (alphabet z=4) and suppose that is N(L*N)
 complexity:

inline const short int V (const char x){
    switch(x){
    case 'A':case 'a':
      return 0;
      break;
    case 'C':case 'c':
      return 1;
      break;
    case 'G':case 'g':
      return 2;
      break;
    default:
      return 3;
    break;
    }

  }

  // [[Rcpp::export]]
  IntegerVector basem(std::string seq ,int gap ,int N){
    IntegerVector res(16);
     short int x=0;
    short int y=0;
    for(int i=0;i<N-gap;i++){
      x=V(seq[i]);
      y=V(seq[i+gap]);
      res[4*x+y]++;
    }
    return res;
  }

  // [[Rcpp::export]]
  List basegap (std::string sequence,int x){
    int n=sequence.size();
    List result ;
    for(int j=1;j<x;j++) {
      result.push_back(basem(sequence,j,n));
    }
    return result;
  }

  basem:calculate the number of occurence for a gap

  basegap: calculate the number of occurence for a gap from 1 to X

Running Example:

a
[1] "atgccatcactcagtaaagaagcggccctggttcatgaagcgttagttgcgcgaggactggaaacaccgctgcgcccgcccgtgcatgaaatggataacgaaacgccgaaaagccttattgctggtcatatgaccgaaatcatgcagctgctgaatctcgacctggctgatgacagtttgatggaaacgcggcatcgcatcgctaaaatgtatgtcgatgaaattttctccggtctggattacgccaatttcccgaaaatcaccctcattgaaaacaaaatgaaggtcgatgaaatggtcaccgtccgcgatatcactctgaccagcacctgtgaacaccattttgttaccatcgatggcaaagcgacggtggcctatatcccgaaagattcggtgatcggtctgtcaaaaattaaccgcattgtgcagttctttgcccagcgtccgcaggtgcaggaacgtctgacgcagcaaattcttgttgccgcgctacaaacgctgctgggcaccaataacgtggctgtctcgatcgacgcggtgcattactgcgtgaaggcgcgtggcatccgcgatgcaaccagtgccacgacaacgtcctctcttggtggattgttcaaatccagtcagaatacgcgccacgagtttctgcgcgctgtgcgtcatcacaactga"

 basem(a,5,nchar(a))
 [1] 40 50 42 37 47 46 36 49 45 39 44 39 38 42 45 28
x<-basegap(a,10)
[[1]]
 [1] 61 38 23 48 48 39 57 35 44 58 28 38 17 44 60 33

[[2]]
 [1] 42 47 43 38 42 49 53 35 44 44 35 44 42 39 37 36

[[3]]
 [1] 50 39 44 37 35 53 44 47 46 41 47 33 39 46 32 36

[[4]]
 [1] 42 54 36 38 54 36 52 36 43 49 41 34 31 39 38 45

[[5]]
 [1] 40 50 42 37 47 46 36 49 45 39 44 39 38 42 45 28

[[6]]
 [1] 42 44 40 42 45 44 44 45 38 44 47 38 44 45 36 28

[[7]]
 [1] 38 44 44 42 44 49 42 42 40 44 42 41 47 40 39 27

[[8]]
 [1] 34 48 47 38 46 49 41 41 47 39 39 42 42 40 40 31

[[9]]
 [1] 43 37 45 42 40 46 56 34 45 57 33 32 40 36 33 44

m<-matrix(unlist(x),nrow=16)
m
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
 [1,]   61   42   50   42   40   42   38   34   43
 [2,]   38   47   39   54   50   44   44   48   37
 [3,]   23   43   44   36   42   40   44   47   45
 [4,]   48   38   37   38   37   42   42   38   42
 [5,]   48   42   35   54   47   45   44   46   40
 [6,]   39   49   53   36   46   44   49   49   46
 [7,]   57   53   44   52   36   44   42   41   56
 [8,]   35   35   47   36   49   45   42   41   34
 [9,]   44   44   46   43   45   38   40   47   45
[10,]   58   44   41   49   39   44   44   39   57
[11,]   28   35   47   41   44   47   42   39   33
[12,]   38   44   33   34   39   38   41   42   32
[13,]   17   42   39   31   38   44   47   42   40
[14,]   44   39   46   39   42   45   40   40   36
[15,]   60   37   32   38   45   36   39   40   33
[16,]   33   36   36   45   28   28   27   31   44

My questions are:

How to reduce the complexity for this calculation?
Are there any ideas to improve this code?


texts:
Given a dictionary of cows and their weight:

cows = {'Betsy': 9, 'Oreo': 6, 'Herman': 7, 'Florence': 2, 'Maggie': 3, 'Moo Moo': 3, 'Milkshake': 2, 'Lola': 2, 'Millie': 5, 'Henrietta': 9}

I want to get a list of lists to move all cows, each nested list of cow's a total weight <= 10, hence to first two trips will have just Betsy and Henrietta:

The answer for GREEDY COW TRANSPORT:

[['Betsy'], ['Henrietta'], ['Herman', 'Maggie'], ['Oreo', 'Moo Moo'], ['Millie', 'Florence', 'Milkshake'], ['Lola']]

Here is my code that took too long in a net grader:

def greedy_cow_transport(cows,limit=10):
    train = []
    cart = []

# get tuples from dictionary key ordered by value high to low
    CowTupleList = sorted(cows.items(), key=lambda x: x[1], reverse = True)

# put cow names in list order high to low to loop over
    names = []
    for i in range(len(cows)):
        names.append(CowTupleList[i][0])
    train = []
    while sum(cows.values()) > 0:
        cart = []
        total = 0

        for cow in names:
            if cows[cow] != 0 and cows[cow] + total <=limit:
                cart.append(cow)
                total += cows[cow]
                cows[cow] = 0
        train.append(cart)
    return train

This took too much time for the online grader, so I failed. Can this be done in only a few lines?


texts:
I have created a function that adds "shadow" to the content of a canvas. The algorithm for adding shadow follows these rules:

If the either x or y is 0, ignore.
If the pixel on the current pixel's top left corner is not completely transparent, set current pixel's alpha value to 0.1.

This algorithm runs from top to bottom, left to right. Here's the relevant part, where rendered is a canvas that already contain rendered content.

    function getIndex(x, y){
        return (y * width + x) * 4;
    }

    function isClear(x, y){
        var index = getIndex(x, y);
        return data[index + 3] === 0;
    }

    function isInShadow(x, y){
        if(x < 1 || y < 1)                          return false;
        if(isClear(x, y) && !isClear(x - 1, y - 1)) return true;

        return false;
    }

    var width = rendered.width, height = rendered.height,
        imgData = renderedCtx.getImageData(0, 0, width, height),
        data = imgData.data;

    for(var x = 0; x < width; x++){
        for(var y = 0; y < height; y++){
            if(isInShadow(x, y)){
                data[getIndex(x, y) + 3] = 256 * 0.1;
            }
        }
    }

    renderedCtx.putImageData(imgData, 0, 0);

As you can see, this function performs per pixel manipulation and is quite slow in performance. What is a good way to improve performance, probably without checking each pixel independently?


texts:
Are these classes properly guarded for thread safety?  Do you see any issues with any of the classes?

@ThreadSafe
public class RetirementAccount {

     public static final int TYPE1 = 0;
     public static final int TYPE2 = 1;

    @GuardedBy("this")
    private final int accountType;
    @GuardedBy("buySell")
    public final List<BuySell> buySell;

    public RetirementAccount(int accountType) {
       this.accountType = accountType;
       this.buySell = Collections.synchronizedList(new ArrayList<BuySell>());
    }

    public void addToAccount(double amount) {
       if (amount <= 0) {
            throw new IllegalArgumentException();
       } else {
           synchronized (buySell) {
               buySell.add(new BuySell(amount));
            }
         }

      public double interestGained() {

           synchronized (this) {
              switch (accountType) {
                …..
        }
      }

BuySell:

@Immutable
public class BySell {
    public final double depositAmount;

    public BuySell(double depositAmount) {
        this.depositAmount = depositAmount;

    }

  }


texts:
I am doing some tests with html5 Canvas object. At the same time I am trying to make my javascript code more modular.  In the following code, where/how should I declare canvas and context, so that it can be shared with other objects?  Please provide general comments/improvements?

Output:

Code:

$( document ).ready(function() {

    var axis = {
        LEFT_INDENT : 100,
        START_WORK_HOUR : 8,
        END_WORK_HOUR : 17,
        HOURS_IN_WORKDAY : 0,
        CANVAS_WIDTH : 0,
        CANVAS_HEIGHT : 0,
        AXIS_SIDE_MARGIN : 20,
        AXIS_TOP_MARGIN : 40,
        AXIS_ORIGIN : new Array(),
        AXIS_RIGHT : 0,
        TICK_INCREMENT :  0,

        setup: function(){

            // assumes that I have <canvas id="myCanvas" width="800" height="300"></canvas>  in the HTML
            this.canvas = document.getElementById('myCanvas');
            this.context = this.canvas.getContext('2d');

            this.HOURS_IN_WORKDAY = this.END_WORK_HOUR - this.START_WORK_HOUR;
            this.CANVAS_WIDTH = this.canvas.width;
            this.CANVAS_HEIGHT = this.canvas.height;

            this.AXIS_ORIGIN = { x: this.AXIS_SIDE_MARGIN,
                            y: this.AXIS_TOP_MARGIN };

            this.AXIS_RIGHT = this.canvas.width-this.AXIS_SIDE_MARGIN;

            this.TICK_INCREMENT = (this.CANVAS_WIDTH-this.LEFT_INDENT-(2*this.AXIS_SIDE_MARGIN))/this.HOURS_IN_WORKDAY;
            this.AXIS_RIGHT = this.canvas.width-this.AXIS_SIDE_MARGIN;
        },

        draw_lines: function(){
            this.context.beginPath();
            this.context.moveTo(this.LEFT_INDENT, this.AXIS_ORIGIN.y);
            this.context.lineTo(this.AXIS_RIGHT,  this.AXIS_ORIGIN.y)
            this.context.stroke();
            this.counter = this.START_WORK_HOUR;

            for(x=this.AXIS_SIDE_MARGIN+this.LEFT_INDENT ; x < this.AXIS_RIGHT ; x = x + this.TICK_INCREMENT){
                // grid lines
                this.context.beginPath();
                this.context.moveTo(x,30);
                this.context.lineTo(x,50)
                this.context.stroke();

                // background line - top to bottom
                this.context.save();
                this.context.fillStyle = "#F0F8FF";
                this.context.beginPath();
                this.context.lineWidth = .1;
                this.context.moveTo(x,30);
                this.context.lineTo(x,this.CANVAS_HEIGHT-20)
                this.context.stroke();
                this.context.restore();

                // text
                this.context.font = "14px Arial";
                this.context.fillStyle = "#011f5b";
                this.counter++;
                this.context.fillText(this.counter+":00",x-7,20);
            }
        }
    }
    axis.setup();
    axis.draw_lines();
});


texts: Implementation of an OkHttp singleton for Android

texts:
I'm new to Android programming. I am going to make lots of HTTP requests: 500, 1k, 2k, 10k.

I have tried to create a singleton class for OkHttp. I wrote this:

public class OkSingleton extends OkHttpClient {

private  static  OkSingleton minstance;
private final OkHttpClient myClient;

private OkSingleton (){
    myClient= new OkHttpClient();
}

public static synchronized  OkSingleton getMinstance(){

    if (minstance==null){
        minstance=new OkSingleton();
    }

    return minstance;
}}

Can you show me my mistakes?


texts: Authenticating and redirecting six specific users

texts:
In a project I have a few long switch statements which seem ugly to me. Please suggest how to refactor the following code.

    protected void processRequest(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
     String username = request.getParameter("username");
     String password = request.getParameter("password");

     switch(username) {
     case "client1":
         if(PASSWORD.equals(password)) {
             request.getSession(true).setAttribute("username", username);
             response.sendRedirect("app1/apk-1-index.html");
         }
         break;

     case "client2":
         if(PASSWORD.equals(password)) {
             request.getSession(true).setAttribute("username", username);
             response.sendRedirect("app2/apk-2-index.html");
         }
         break;

     case "client3":
         if(PASSWORD.equals(password)) {
             request.getSession(true).setAttribute("username", username);
             response.sendRedirect("app3/apk-3-index.html");
         }
         break;

     case "client4":
         if(PASSWORD.equals(password)) {
             request.getSession(true).setAttribute("username", username);
             response.sendRedirect("app4/apk-4-index.html");
         }
         break;
     case "client5":
         if(PASSWORD.equals(password)) {
             request.getSession(true).setAttribute("username", username);
             response.sendRedirect("app5/apk-5-index.html");
         }
         break;
     case "client6":
         if(PASSWORD.equals(password)) {
             request.getSession(true).setAttribute("username", username);
             response.sendRedirect("app5/apk-5-index.html");
         }
         break;
    default:
        response.sendRedirect("/Test2/index.jsp");
     }
}


texts: My PHP function that reads names and attempts to fix the suffixes

texts:
I am reading a text file that has some name inconsistencies. For example I have names like:

MILLERS, WALTER M IV
DUPONTE, THOMAS B. II
HARDIWAY, GRANT U. SR.
GUIDRY, PAUL JOHN

As you can see I can split the name by first name and last name however the suffixes are placed incorrectly. Ideally the names should be:

WALTER M MILLERS IV
THOMAS B. DUPONTE II
GRANT U. HARDIWAY SR.
PAUL JHN GUIDRY

That being said this is what I have but I feel Im over complicating something simple. Any tips? Also my logic does not account for the suffix of V since that could be a middle initial also.

private function extractFullName($name){

        $suffix = collect(['II', 'III', 'IV', 'JR.', 'SR.']);

        // lets first assemble a full name from the row
        $fullNameArray = explode(",", $name);
        $firstName=trim($fullNameArray[1]);
        $lastName=trim($fullNameArray[0]);

        //lets look at the FIRST NAME for II/III/IV/JR./SR.
        $suffix->each(function ($item, $key) use ($firstName, $lastName) {

            if (strpos($firstName, " ".$item)){
                $firstName = preg_replace('/ '.$item.'$/', '', $firstName);
                $lastName.=' '.$item;
                return false;
            }
        });

        //Basically arranging it in a 'firstname lastname II/III/IV/JR./SR.' format
        $name = $firstName." ".$lastName;
        $name = ucwords(strtolower($name));
        return $name;
    }


texts:
I am trying to create a very basic class: Line as follows:

class Line:

    def __init__(self, x1, y1, x2=None, y2=None, dx=None, dy=None):
        self._x1 = x1
        self._y1 = y1

        if dx is None:
            if x2 is None:
                raise ValueError("You must specify either x2 or dx. both argument are not passed")
            else:
                self._x2 = x2
                self._dx = dx
        else:
            if x2 is None:
                self._x2 =  self._x1 + dx
                self._dx = dx
            else:
                raise ValueError("Both x2 and dx are passed. You must supply only one of them")

        if dy is None:
            if y2 is None:
                raise ValueError("You must specify either y2 or dy. both argument are not passed")
            else:
                self._y2 = y2
                self._dy = dy
        else:
            if y2 is None:
                self._y2 =  self._y1 + dy
                self._dy = dy
            else:
                raise ValueError("Both y2 and dy are passed. You must supply only one of them")

    def x1(self):
        return self._x1

    def x2(self):
        return self._x2

    def y1(self):
        return self._y1

    def y2(self):
        return self._y2

    def dx(self):
        return self._dx

    def dy(self):
        return self._dy

x1 and y1 arguments are mandatory. But I want:

Only x2 or dx is passed not both.
Only y2 or dy is passed not both.

In the code above I feel that I am repeating my self. How can I achieve that with minimum conditons?

I appreciate your help


texts:
Here is my current toggle function:

$scope.toggleSelect = event => {
  $scope.selection = event.target.innerHTML;

  if ($scope.selection === 'Select All') {
     $scope.emailList = $scope.users.filter(user => !user.report.emailed);
  } else {
     $scope.emailList = $scope.emailList = [];
  }
};

Here are my thoughts and questions about the best practices:

I make an assignment to $scope.emailList in the if and else statement. Instead of separate assignments, is one assignment better? Refactoring to one assignment will pollute the code with unnecessary variables, but it may make the code more readable?

$scope.toggleSelect = event => {
  $scope.selection = event.target.innerHTML;
  const emailListUpdate;
  if ($scope.selection === 'Select All') {
    emailListUpdate = $scope.users.filter(user => !user.report.emailed);
  } else {
    emailListUpdate = $scope.emailList = [];
  }
   $scope.emailList = emailListUpdate;
};

The main benefit I see here is that anybody reading the code can skim to the last line and know the overall purpose. Overall, I don't see this to be a beneficial refactor since I don't think it adds additional readability and potentially makes it harder to follow. I would appreciate thoughts on this.
Ternary or if/else:

I reviewed a great post about the benefits and use cases of using ternary or if/else. Here is  what the code would look like refactored to a ternary:

$scope.toggleSelect = event => {
  $scope.selection = event.target.innerHTML;
  $scope.emailList = $scope.selection === 'Select All' ? $scope.users.filter(user => !user.report.emailed); : [];

};

Quoting from the article linked above:

  An if/else statement emphasizes the branching first and what's to be done is secondary, while a ternary operator emphasizes what's to be done over the selection of the values to do it with.

I feel the if/else feels more natural, but I'm not sure if that is just related to my lack of experience using ternary.
I have another toggleItem function used when a checkbox is clicked.

$scope.toggleItem = (event, user) => {
  if (event.target.checked) {
    $scope.emailList.push(user);
  } else {
    $scope.emailList = _.reject($scope.emailList, item => item._id === user._id);
  }

I've thought about combining both of my toggle functions but overall I think it is better to keep them separate instead of trying to make a generic toggle function with multiple use cases.

In the toggleItem function above, I think it is cleaner (and more obvious) to use an if/else instead of a ternary since I am only making an assignment in the else statement.

I'm trying to improve on writing cleaner code, If anyone has any input or thoughts on best practices to use here or how to clean up this code it would be appreciated.


texts:
I'm thinking about DOM modification performance.

In a perfect way, we alter each element but DOM modification is really heavy and alter many elements at same time froze the browser. I didn't make any performance tests but I want to know if the second way can be more powerful.

In my head, the first way will ask the browser to refresh the display for each div. So logically, with the second way, the browser will refresh only once per injection. Is that correct?

HTML:


texts: JavaScript telegram bot that sends images based on user search

texts:
In my freetime, I did this little Telegram bot in Node.js that provides some basic text-based commands and one command where a user can search for an image in order for the bot to send back an image related to that word.

Is there anything about this code I can optimize regarding performance and / or code quality in general?

// Request module
const request = require('request');

// Telebot module
const Telebot = require('telebot');

// Bot
const bot = new Telebot("YOUR TELEGRAM API TOKEN");

// DOMParser
const jsdom = require('jsdom');
const { JSDOM } = jsdom;

// /start command
bot.on('/start', (msg) => msg.reply.text('Hello! For informations about usage, creator, etc., please use the command /help!'));

// /help command
bot.on('/help', (msg) => msg.reply.text('Usage:\n /imageof <your_word> sends you an random image.\nExample:\n/imageof dog - You\'ll get an random image of a dog.\n\nAbout:\nVersion: 2.0\nCreator: @CodeFox\nGitHub: https://github.com/CodeF0x/image-search-telegram-bot\nAll images are taken from https://unsplash.com.'));

// /imageof command
bot.on(/^\/imageof (.+)$/, (msg, props) => {
    request(`https://unsplash.com/search/photos/${props.match[1]}`, function (error, response) { // Get the search results of bing
        var html = new JSDOM(response.body); // Parse the response
        var images = html.window.document.getElementsByClassName('_2zEKz'); // Get all images - in this case by class name, otherwise we would get profile pictures too
        var sources = []; // Array to pick random url from
        for (var i = 0; i < images.length; i++) { // Loop through all images and push only valid url to the array
            if (images[i].src.includes('https')) {
                sources.push(images[i].src);
            }
        }
        // Check if the array containing the url has any values
        if (typeof sources[0] !== "undefined") {
            sendPhoto(msg, sources[Math.floor(Math.random() * sources.length)]); // Random url as parmeter
        } else {
            sendError(msg, props);
        }
    });
});

// Actual function to send the photo
const sendPhoto = (msg, url) => msg.reply.photo(url); // Send the photo

// Function to send an error message
const sendError = (msg, props) => msg.reply.text(`⚠ Sorry, I couldn't find any image for "${props.match[1]}". ⚠`);

bot.start();


texts: Search for ways in OpenStreetMap extract

texts:
What does it do ?

Looks in big XML files (1-3 GB) for given parameters that I need in my project, appends them to lists and finally exports both of them to the CSV files.

My XML scheme

I need to get child named 'v', which is  value of specific child 'k' nested in tag named 'tag' which is nested within parent 'way'.

What I tried

IBM's take on big xml files

Plus various scripts from StackExchange.

Performance

My function needs 50% less time to parse XML than above method, any other I tried or I was able to try, because with some I was unable to figure things out and given up on them.

My goal

To get some tips on my code, hopefully find way to speed it up.
I need to parse about 20 - 30 GB of XML files (as mentioned before single file is 1-3 GB), whole procedure is really time consuming - It takes about 12 hours up to 2 days of non stop parsing.

Variables description:

xml - path to xml file
list_agis - list of IDs, list which length is number between 5k - 1 kk
parent - way
child - tag
child_atribitute - k
child_value_1 - highway
child_value_2 - track
name_id, name_atribute, name_file, path_csv, part_name - variables needed to create csv file name

My code

def save_to_csv(
        list_1, list_2, name_1,
        name_2, csv_name, catalogue,
        part_name):
    """
    Saves to CSV, based on 2 lists.
    """
    raw_data = {name_1: list_1,
                name_2: list_2}
    df = pd.DataFrame(raw_data, columns=[name_1, name_2])
    df.to_csv(
        '{0}\{1}_{2}.csv'.format(catalogue, part_name, csv_name),
        index=False, header=True, encoding = 'CP1250')

def xml_parser(
        xml, lista_agis, parent,
        atribiute_parent, child, child_atribiute,
        child_value_1, child_value_2, name_file,
        sciezka_csv, name_id, name_atribiute,
        part_name):
    """
    Function to pick from xml files tag values.
    Firstly it creates tree of xml file and then
    goes each level town and when final condtion is fullfiled
    id and value from xml file is appended to list in the end of
    xml file list is saved to CSV.

    """
    rootElement = ET.parse(xml).getroot()
    list_id = []
    list_value = []
    for subelement in rootElement:
        if subelement.tag == parent:
            if subelement.get(atribiute_parent) in lista_agis:
                for sselement in subelement:
                    if sselement.tag == child:
                        if sselement.attrib[child_atribiute] == child_value_1:
                            list_id.append(
                                subelement.get(atribiute_parent))
                            list_value.append(
                                sselement.get(child_value_2))

    save_to_csv(
        list_id, list_value, name_id,
        name_atribiute, name_file,
        sciezka_csv, part_name)


texts:
I wrote a function, which takes a list of Integers, and then makes a balanced binary tree.

Please critique it. I'd like to know know how to make it more concise and idiomatic.

-- Note that the Integer represents the height of the Tree
data Tree a = Leaf
              | Node Integer (Tree a) a (Tree a)
              deriving (Show)-- where Integer is the height (bottom = 0)

-- make balanced, binary tree (height diff is <= 1)
-- Note - I would've liked to have kept `foldTree` point-free,
--        but I'm not sure how to do that since I need `xs` for `treeHeight`
foldTree :: [a] -> Tree a
foldTree xs = (foldingFn . zip [0..]) xs
   where foldingFn = foldr (\(i, elem) acc -> if (odd i) then insertFreeOrLeft  treeHeight elem acc
                                              else            insertFreeOrRight treeHeight elem acc) Leaf
         treeHeight = getBinTreeHt xs

-- get Binary Tree Height (used to start making the Tree)
getBinTreeHt :: [a] -> Integer
getBinTreeHt = floor . (logBase 2) . fromIntegral . length

-- insert where there's a Leaf, otherwise choose Left
insertFreeOrLeft :: Integer -> a -> Tree a -> Tree a
insertFreeOrLeft index x Leaf                    = Node index  Leaf x Leaf
insertFreeOrLeft _ x (Node level Leaf val right) = Node level (Node (level-1) Leaf x Leaf) val right
insertFreeOrLeft _ x (Node level left val Leaf)  = Node level left val (Node (level-1) Leaf x Leaf)
insertFreeOrLeft _ x (Node level left val right) = Node level (insertFreeOrLeft (level-1) x left) val right

-- insert where there's a Leaf, otherwise choose Right
insertFreeOrRight :: Integer -> a -> Tree a -> Tree a
insertFreeOrRight index x Leaf                    = Node index  Leaf x Leaf
insertFreeOrRight _ x (Node level left val Leaf)  = Node level left val (Node (level-1) Leaf x Leaf)
insertFreeOrRight _ x (Node level Leaf val right) = Node level (Node (level-1) Leaf x Leaf) val right
insertFreeOrRight _ x (Node level left val right) = Node level left val (insertFreeOrRight (level-1) x right)

Testing

*Main> foldTree "ABC"
Node 1 (Node 0 Leaf 'B' Leaf) 'C' (Node 0 Leaf 'A' Leaf)

*Main> foldTree "ABCDE"
Node 2 (Node 1 (Node 0 Leaf 'B' Leaf) 'D' Leaf) 'E' (Node 1 Leaf 'C' (Node 0 Leaf 'A' Leaf))


texts: Possible optimizations for calculating squared euclidean distance

texts:
I need to do a few hundred million euclidean distance calculations every day in a Python project.

Here is what I started out with:

#!/usr/bin/python
import numpy as np

def euclidean_dist_square(x, y):
    diff = np.array(x) - np.array(y)
    return np.dot(diff, diff)

This is quite fast and I already dropped the sqrt calculation since I need to rank items only (nearest-neighbor search). It is still the bottleneck of the script though. Therefore I have written a C extension, which calculates the distance. The calculation is always done with 128-dimensional vectors.

#include "euclidean.h"
#include <math.h>

double euclidean(double x[128], double y[128])
{
    double Sum;
    for(int i=0;i<128;i++)
    {
        Sum = Sum + pow((x[i]-y[i]),2.0);
    }
    return Sum;
}

This is the relevant part of the extension, the complete code for the extension is here.
Now this gives a nice speedup in comparison to the numpy version.

But is there any way to speed this up further (this is my first C extension ever so I assume there is)? With the number of times this function is used every day, every microsecond would actually provide a benefit.

Some of you might suggest porting this completely from Python to another language, unfortunately this is a larger project and not an option.


texts:
We are designing a small framework to create and send messages to external parties as a result of internal events.  I am reasonably happy with the design, but I am wandering if it can be further improved.

The external messages are large and complex and involve getting data from different areas in the system and are sent asynchronously when the internal event happens.  A single internal event can cause multiple external messages to be sent.

The internal event (incomingMessage) contains some of the information required to populate the message, and that is provided to the message sending framework, but additional information is required to be retrieved from the database through a potentially expensive query.

The MessageBuilder class builds the messages resulting from the internal event with the help of a list of IMessageContentProvider, which can provide content for different parts of the message. These are passed in through the constructor.

public interface IMessageBuilder<in TIncoming>
{
    IEnumerable<object> Build(TIncoming incomingMessage);
}
 public class MessageBuilder<TIncoming, TOutgoing> : IMessageBuilder<TIncoming> where TOutgoing : class, new()
{
    private readonly IMessageContentProvider<TIncoming, TOutgoing>[] contentProviders;

    public MessageBuilder(IMessageContentProvider<TIncoming, TOutgoing>[] contentProviders)
    {
        this.contentProviders = contentProviders;
    }

    public IEnumerable<object> Build(Project project, IServiceBusResolver serviceBusResolver, TIncoming incomingMessage)
    {
        TOutgoing outgoingMessage = BuildOutgoingMessage(project, serviceBusResolver, incomingMessage);

        return outgoingMessage != null ? new[] { outgoingMessage } : null;
    }

    protected virtual TOutgoing BuildOutgoingMessage(Project project, IServiceBusResolver serviceBusResolver, TIncoming incomingMessage)
    {
        TOutgoing outgoingMessage = new TOutgoing();

        foreach (IMessageContentProvider<TIncoming, TOutgoing> contentProvider in contentProviders)
        {
            contentProvider.Populate(incomingMessage, ref outgoingMessage);
        }

        return outgoingMessage;
    }

The external message definition also requires some translation from internal types to external message types, these are enumerations and data structures used in the external large message. This is done in a static converter class (this seems a bit clunky), which has a series of methods to convert specific parts of the message. All required data is passed in as parameters.

public static class XXMessageConverter
{
    public static TypeA GetTypeA(InternalTypeA internalTypeA, OtherData1 data, OtherData2 data2)
    {
    }
    // ... More getter methods
}

One thing that worries me is that the content providers are independent of each other and there is nothing stopping one provider overwriting data populated by another. Also the order of the providers passed in to the MessageBuilder is important. I have been thinking whether using the fluent builder pattern will be more appropriate and whether message type conversion should happen in the builder or in a separate class.

I added a new type ITypeConverter and started adding a series of converters for translating messages. It's simple at this stage, I may have to add some context to it as some messages require external information to convert.

public interface ITypeConverter<in TSource, out TDestination>
{
    TDestination Convert(TSource source);
}


texts:
I have posted my solution to the jolly jumpers programming challenge(detailed here) for your review:

  A sequence of n > 0 integers is called a jolly jumper if the absolute
  values of the differences between successive elements take on all
  possible values 1 through n - 1. For instance,

  1 4 2 3

  is a jolly jumper, because the absolute differences are 3, 2, and 1,
  respectively. The definition implies that any sequence of a single
  integer is a jolly jumper. Write a program to determine whether each
  of a number of sequences is a jolly jumper.

  Input

  Each line of input contains an integer n < 3, 000 followed by n
  integers representing the sequence.

  Output

  For each line of input generate a line of output saying Jolly or
  Not jolly.

  Sample Input

4 1 4 2 3
5 1 4 2 -1 6

  Sample Output

 Jolly
 Not jolly

//platform specific code
#ifdef WINDOWS
#include "stdafx.h"
#endif // WINDOWS

#include <iostream>
#include <vector>

using std::cout;
using std::cin;
using std::vector;

const int MAX_SEQUENCE_LENGTH = 3000;

int main()
{
    bool not_jolly;
    vector<int> sequence(MAX_SEQUENCE_LENGTH, 0);
    vector<bool> in_sequence(MAX_SEQUENCE_LENGTH, false);
    int sequence_length;
    while (cin >> sequence_length) {
        not_jolly = false;
        std::fill(sequence.begin(), sequence.end(), 0);
        std::fill(in_sequence.begin(), in_sequence.end(), false);
        for (int i = 0;i < sequence_length; i++) {
            cin >> sequence[i];
        }

        for (int i = 1;i < sequence_length; i++) {
            in_sequence[abs(sequence[i] - sequence[i - 1])] = true;
        }

        for (int i = 1;i < sequence_length;i++) {
            if (!in_sequence[i]) {
                not_jolly = true;
                break;
            }
        }

        if (not_jolly == false) {
            cout << "Jolly" << "\n";
        } else {
            cout << "Not jolly" << "\n";
        }
    }
}


texts:
I have started to learn C and I have tried my hand at temperature conversion. The idea is to convert a temperature from Fahrenheit to Celsius and vice/versa. Can somebody review my code and let me know how I might be able to improve it?  My program is as follows:

#include <stdio.h>

void fahconv()
{
    double fah;
    puts("Enter value to convert from Fahrenheit to Celsius");
    scanf("%lf",&fah);
    printf("Converted temperature from F to C: %lf",((fah - 32.0)*5.0)/9.0);
}

void celsconv()
{
    double cels;
    puts("Enter value to convert from Celsius to Fahrenheit");
    scanf("%lf",&cels);
    printf("Converted temperature from C to F: %lf",(cels*9/5)+32);
}

void invalidchoice()
{
    printf("Invalid choice..exiting");
}

int main()
{
    char choice;
    puts("Enter (F or f) to convert from Fahrenheit to Celsius");
    puts("Enter (C or c) to convert from Celsius to Fahrenheit \n");
    scanf("%c",&choice);
    switch(choice)
    {
        case 'c':
        case 'C': celsconv();
              break;
        case 'f':
        case 'F': fahconv();
              break;
        default: invalidchoice();
    }
    return 0;
}


texts: Advent of Code 2017 Day 2 (1) in Functional programming (FP)


texts:
I put this together and it seems to work.

1channel.py -breakingbad 1

The Output (1-10):

(1) - Currently 3.80/5
(2) - Currently 3.50/5

(1 opens the link in browser)

If anyone has any suggestions or wants to improve it:

from bs4 import BeautifulSoup
import urllib2, sys, webbrowser

def Work(tvshow):
    print "\n[*] Working...\n"

    try:

        f = urllib2.urlopen(tvshow)
        html = f.read()
        soup = BeautifulSoup(html)

        for table in soup.findAll('table',{"width":"100%"}):
            for a in table.findAll('a',{"target":"_blank"}):
                for li in table.findAll('li',{"class":"current-rating"}):

                    if a.text=="Version 2":
                        print "(1) - %s\n" % (li.text)
                        link1 = "http://www.1channel.ch" + a['href']

                    elif a.text=="Version 3":
                        print "(2) - %s\n" % (li.text)
                        link2 = "http://www.1channel.ch" + a['href']

                    elif a.text=="Version 4":
                        print "(3) - %s\n" % (li.text)
                        link3 = "http://www.1channel.ch" + a['href']

                    elif a.text=="Version 5":
                        print "(4) - %s\n" % (li.text)
                        link4 = "http://www.1channel.ch" + a['href']

                    elif a.text=="Version 6":
                        print "(5) - %s\n" % (li.text)
                        link5 = "http://www.1channel.ch" + a['href']

                    elif a.text=="Version 7":
                        print "(6) - %s\n" % (li.text)
                        link6 = "http://www.1channel.ch" + a['href']

                    elif a.text=="Version 8":
                        print "(7) - %s\n" % (li.text)
                        link7 = "http://www.1channel.ch" + a['href']

                    elif a.text=="Version 9":
                        print "(8) - %s\n" % (li.text)
                        link8 = "http://www.1channel.ch" + a['href']

                    elif a.text=="Version 10":
                        print "(9) - %s\n" % (li.text)
                        link9 = "http://www.1channel.ch" + a['href']

                    elif a.text=="Version 11":
                        print "(10) - %s\n" % (li.text)
                        link10 = "http://www.1channel.ch" + a['href']

        user = raw_input(">>> ")

        if user == '1':
            webbrowser.open(link1)
        elif user == '2':
            webbrowser.open(link2)
        elif user == '3':
            webbrowser.open(link3)
        elif user == '4':
            webbrowser.open(link4)
        elif user == '5':
            webbrowser.open(link5)
        elif user == '6':
            webbrowser.open(link6)
        elif user == '7':
            webbrowser.open(link7)
        elif user == '8':
            webbrowser.open(link8)
        elif user == '9':
            webbrowser.open(link9)
        elif user == '10':
            webbrowser.open(link10)
        else:
            exit(0)

    except urllib2.HTTPError:
            print "- HTTP Error!"
    except urllib2.URLError:
            print "- Connection Faliure!"
    except UnboundLocalError:
            print "Episode does not exist!"

def Main():
    if len(sys.argv) !=3:
        print "1channel.py -show episode#"
        sys.exit()

    elif sys.argv[1] == '-breakingbad':
        tvshow = 'http://www.1channel.ch/tv-4128-Breaking-Bad/season-4-episode-' + sys.argv[2]

    elif sys.argv[1] == '-walkingdead':
        tvshow = 'http://www.1channel.ch/tv-2490619-The-Walking-Dead/season-3-episode-' + sys.argv[2]

    elif sys.argv[1] == '-poi':
        tvshow = 'http://www.1channel.ch/tv-2727923-Person-of-Interest/season-2-episode-' + sys.argv[2]

    else:
        sys.exit()

    Work(tvshow)

if __name__ == '__main__':
    Main()


texts:
I have been developing multilanguage website based on Symfony4. Structure of one of the tables:

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| title_en  | varchar(255) | NO   |     | NULL    |                |
| title_fr  | varchar(255) | NO   |     | NULL    |                |
| title_de  | varchar(255) | NO   |     | NULL    |                |
| parent_id | int(11)      | NO   |     | NULL    |                |

What is the optimal way to select appropriate column in template depending on user locale?

How bad will look the approach below to get needed entity field ?

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Category
 *
 * @ORM\Table(name="category")
 * @ORM\Entity
 */
class Category
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title_en", type="string", length=255, nullable=false)
     */
    private $titleEn;

    /**
     * @var string
     *
     * @ORM\Column(name="title_fr", type="string", length=255, nullable=false)
     */
    private $titleFr;

    /**
     * @var string
     *
     * @ORM\Column(name="title_de", type="string", length=255, nullable=false)
     */
    private $titleDe;

    /**
     * @var int
     *
     * @ORM\Column(name="parent_id", type="integer", nullable=false)
     */
    private $parentId = '0';

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getLocalizedTitle(): ?string
    {
        $locale='title'.ucfirst($GLOBALS['request']->getLocale());
        return  $this->{$locale};
    }

    public function getTitleEn(): ?string
    {
        return $this->titleEn;
    }

    public function setTitleEn(string $titleEn): self
    {
        $this->titleEn = $titleEn;

        return $this;
    }

    public function getTitleDe(): ?string
    {
        return $this->titleDe;
    }

    public function setTitleDe(string $titleDe): self
    {
        $this->titleDe = $titleDe;

        return $this;
    }

    public function getParentId(): ?int
    {
        return $this->parentId;
    }

    public function setParentId(int $parentId): self
    {
        $this->parentId = $parentId;

        return $this;
    }

}

Then in view to get field we just use

{{ job.category.getLocalizedTitle }}


texts: Daily, Weekly, Monthly Individual Tech time in task Repoert

texts:
I'm trying to create daily, monthly and weekly SQL Query report to our services time we spent int task and total billing time just want to see if I'm on right track

GO
--Daily

SELECT     SUM(billingsTimes.actualTotalTime) AS TotalTime, Tasks.taskName, billableType.billableTypeName
FROM         billingsTimes INNER JOIN
                      aspnet_Users ON billingsTimes.userID = aspnet_Users.UserId INNER JOIN
                      billableType ON billingsTimes.billableTypeID = billableType.rank INNER JOIN
                      Tasks ON billingsTimes.taskID = Tasks.taskID
WHERE     (billingsTimes.taskID = 10045) AND (aspnet_Users.UserId = '178db2a8-be1d-48e0-9ebc-f64f7b1ff63e') AND (CONVERT(DATE, billingsTimes.dateOfService)
                      = '01/29/2013')
GROUP BY billingsTimes.billableTypeID, Tasks.taskName, billableType.billableTypeName,DATEPART(D, dateOfService)

GO
--Weekly

SELECT     SUM(billingsTimes.actualTotalTime) AS TotalTime, Tasks.taskName, billableType.billableTypeName,DATEPART(WEEK, dateOfService)AS weekNumber
FROM         billingsTimes INNER JOIN
                      aspnet_Users ON billingsTimes.userID = aspnet_Users.UserId INNER JOIN
                      billableType ON billingsTimes.billableTypeID = billableType.rank INNER JOIN
                      Tasks ON billingsTimes.taskID = Tasks.taskID
WHERE     (billingsTimes.taskID = 10045) AND (aspnet_Users.UserId = '178db2a8-be1d-48e0-9ebc-f64f7b1ff63e')
GROUP BY billingsTimes.billableTypeID, Tasks.taskName, billableType.billableTypeName,DATEPART(WEEK, dateOfService), DATEPART(WEEK, dateOfService)

GO
--Monthly

SELECT     SUM(billingsTimes.actualTotalTime) AS TotalTime, Tasks.taskName, billableType.billableTypeName,DATEPART(MONTH, dateOfService)AS monthNumber
FROM         billingsTimes INNER JOIN
                      aspnet_Users ON billingsTimes.userID = aspnet_Users.UserId INNER JOIN
                      billableType ON billingsTimes.billableTypeID = billableType.rank INNER JOIN
                      Tasks ON billingsTimes.taskID = Tasks.taskID
WHERE     (billingsTimes.taskID = 10045) AND (aspnet_Users.UserId = '178db2a8-be1d-48e0-9ebc-f64f7b1ff63e')
GROUP BY billingsTimes.billableTypeID, Tasks.taskName, billableType.billableTypeName,DATEPART(MONTH, dateOfService)
GO


texts: Flipping True or False values to save typing and time

texts:
I have a few columns in a DBGrid that I want to hide and show at different times depending on what the user wants to view.

Rather than writing the following code;

For i := 1 to DBGrid1.Columns.Count -1 do
  Begin

    If DBGrid1.Columns[i].FieldName = 'SOMETHING' then
      Begin
        if DBGrid1.Columns[i].visible then
        DBGrid1.Columns[i].visible:=false else
        DBGrid1.Columns[i].visbile:=true;
      End;

    If DBGrid1.Columns[i].FieldName = 'ANOTHERFIELD' then
      Begin
        if DBGrid1.Columns[i].visible then
        DBGrid1.Columns[i].visible:=false else
        DBGrid1.Columns[i].visbile:=true;
      End;

    { And so on... for another 8 columns }

  End;
End;

I've got the following function;

Function Flip(CurrentState:Boolean):Boolean;
Begin

  If CurrentState then
     Result:=False else
     Result:=True;

End;

Then I use the function above like this;

For i := 1 to DBGrid1.Columns.Count -1 do
  Begin

    If DBGrid1.Columns[i].FieldName = 'SOMETHING' then
    DBGrid1.Columns[i].visible := Flip(DBGrid1.Columns[Loop].visible;

    If DBGrid1.Columns[i].FieldName = 'ANOTHERFIELD' then
    DBGrid1.Columns[i].visible := Flip(DBGrid1.Columns[Loop].visible;

    { And so on... for another 8 columns }

  End;
End;

I can't address columns by their index directly because they move around, therefore I use the Field Name associated with it.

My question is this, is there are better and smarter way to hide and unhide many columns?


texts: Take an array and return "n" elements, as evenly spaced as possible


texts: Initializing object by settings implemented as a class

texts:
Here is the story.

We have the BankTerminalSettings class.

It has many properties:

public class BankTerminalSettings {
    public bool IsEnabled { get; set; }
    public string IPAddress {get; set;}
    public ushort TcpPort {get; set; }
    public List<string> Zombies {get; set;}

    //and many other properties
}

And we have a class which takes BankTerminalSettings as a parameter of it's constructor.

public class BankTerminal {
    public BankTerminal(BankTerminalSettings terminal, int clientId) {
        ValidateBankTerminalSettings(terminal);

        terminalSettings = terminal;
        this.clientId = clientId;
    }
}

The thing is that the BankTerminal uses only three of all those properties in that domain config class named BankTerminalSettings.
It's a temptation just to pass the whole instace of the BankTerminalSettings, but the caller can incidentally change those properties which are relevant for the BankTerminal. That can cause very subtle bugs.

What would you recommend?
To replicate the BankTerminalSettings before passing it's instance?
To replicate the BankTerminalSettings in the constructor of the BankTerminal?
To pass only those parameters which are truely needed by the BankTerminal?


texts: Determine amicable pairs within confines of Θ(n)

texts:
I had to implement a program that takes a number userNum from the user and finds all perfect numbers and pairs of amicable numbers within the range \$\lbrace 2, \ldots, \texttt{userNum} \rbrace\$ and output them to the user.

Requirements

Implement function void AnalyzeDivisors(int num, int& outCountDivs, int& outSumDivs)
implement bool IsPerfect(int num) using AnalyzeDivisors
Use functions to write a program that reads from the user a positive integer and prints all perfect numbers between 2 and M and All pairs of amicable numbers that are between 2 and M (both numbers must be in range).
Calls to AnalyzeDivisors must be kept to \$\Theta(m)\$ times all together.

I have not been able to satisfy requirement 4 … Currently my algorithm is very inefficient and I'm unsure how to do it otherwise.  Any recommendations on how to remain within \$\Theta(m)\$ in reference to AnalyzeDivisors would be greatly appreciated.

Code below:

main:

const string IS_PERFECT_NUM = " is a perfect number.";

void AnalyzeDividors(int num, int& outCountDivs, int& outSumDivs);
bool IsPerfect(int userNum, int outSumDivs);

int main()
{
    int userNum;

    //Request number input from the user
    cout << "Please input a positive integer num (>= 2): " << endl;
    cin >> userNum;

    for (int counter = 2; counter <= userNum; counter++)
    {
        //Set variables
        int outCountDivs = 0, outSumDivs = 0;
        bool perfectNum = false, isAmicablePair = false;

        //Analyze dividors
        AnalyzeDividors(counter, outCountDivs, outSumDivs);

        //determine perfect num
        perfectNum = IsPerfect(counter, outSumDivs);

        if (perfectNum)
            cout << endl << counter << IS_PERFECT_NUM;

        //Smallest pair of amicable numbers (220,284)...No need to check if not above range
        if (userNum >= 284)
        {

            for (int amicablePairCounter = counter + 1; amicablePairCounter <= userNum; amicablePairCounter++)
            {
                //Determine if amicable pairs exist by checking against outCountDivs and outSumDivs from prior counter number
                int otherAmicablePairSum = 0, otherOutCountDivs = 0;

                AnalyzeDividors(amicablePairCounter, otherOutCountDivs, otherAmicablePairSum);

                if (otherAmicablePairSum == counter && outSumDivs == amicablePairCounter)
                    cout << endl << amicablePairCounter << " and " << counter << " are an amicable pair.";
            }
        }

    }

    return 0;
}

Analyze Dividors

void AnalyzeDividors(int num, int& outCountDivs, int& outSumDivs)
{
    int divisorCounter;

    for (divisorCounter = 1; divisorCounter <= sqrt(num); divisorCounter++)
    {
        if (num % divisorCounter == 0 && num / divisorCounter != divisorCounter && num / divisorCounter != num)
        {
            //both counter and num/divisorCounter
            outSumDivs += divisorCounter + (num / divisorCounter);
            outCountDivs += 2;
        }

        else if ((num % divisorCounter == 0 && num / divisorCounter == divisorCounter) || num/divisorCounter == num)
        {
            //Just divisorCounter
            outSumDivs += divisorCounter;
            outCountDivs += 1;
        }
    }
}

IsPerfect

bool IsPerfect(int userNum, int outSumDivs)
{

    if (userNum == outSumDivs)
        return true;
    else
        return false;

}


texts:
I've implemented an A* with a priority queue. I am not getting any performance issues in this little game that I am making but it would be interesting to know how to improve this.
I am doing a few o(n) searches in getNode & isSuccessorValid. I thought about using an unordered map and pointing to each node location but when erasing from the vector, that pointer might not be valid anymore.
Thank you in advance.
    struct PriorityQueueNode
{
    PriorityQueueNode(const glm::ivec2& position, const glm::ivec2& parentPosition, float g, float h);

    float getF() const;

    glm::ivec2 position;
    glm::ivec2 parentPosition;
    float g;
    float h;
};

const auto nodeCompare = [](const auto& a, const auto& b) -> bool { return b.getF() < a.getF(); };
class PriorityQueue : private std::priority_queue<PriorityQueueNode, std::vector<PriorityQueueNode>, decltype(nodeCompare)>
{
public:
    PriorityQueue(size_t maxSize)
        : priority_queue(nodeCompare),
        m_maxSize(maxSize),
        m_addedNodePositions()
    {
        c.reserve(maxSize);
    }

    size_t getSize() const
    {
        assert(c.size() == m_addedNodePositions.size());
        return c.size();
    }

    bool isEmpty() const
    {
        assert(c.empty() && m_addedNodePositions.empty() || !c.empty() && !m_addedNodePositions.empty());
        return c.empty();
    }

    bool contains(const glm::ivec2& position) const
    {
        return m_addedNodePositions.find(position) != m_addedNodePositions.cend();
    }

    const PriorityQueueNode& getTop() const
    {
        assert(!isEmpty());
        return top();
    }

    const PriorityQueueNode& getNode(const glm::ivec2& position) const
    {
        auto node = std::find_if(c.cbegin(), c.cend(), [&position](const auto& node) -> bool
        {
            return node.position == position;
        });

        assert(node != c.end());
        return (*node);
    }

    bool isSuccessorNodeValid(const PriorityQueueNode& successorNode) const
    {
        auto matchingNode = std::find_if(c.cbegin(), c.cend(), [&successorNode](const auto& node) -> bool
        {
            return successorNode.position == node.position;
        });

        return matchingNode != c.cend() && successorNode.getF() < matchingNode->getF();
    }

    void changeNode(const PriorityQueueNode& newNode)
    {
        assert(isSuccessorNodeValid(newNode) && contains(newNode.position));

        eraseNode(newNode.position);
        add(newNode);
    }

    void add(const PriorityQueueNode& node)
    {
        assert(!contains(node.position) && c.size() + 1 <= m_maxSize);

        push(node);
        m_addedNodePositions.insert(node.position);
    }

    void popTop()
    {
        assert(!isEmpty());

        auto iter = m_addedNodePositions.find(top().position);
        assert(iter != m_addedNodePositions.end());
        m_addedNodePositions.erase(iter);

        pop();
    }

    void clear()
    {
        c.clear();
        m_addedNodePositions.clear();
    }

private:
    const size_t m_maxSize;
    std::unordered_set<glm::ivec2> m_addedNodePositions;

    void eraseNode(const glm::ivec2& position)
    {
        auto node = std::find_if(c.begin(), c.end(), [&position](const auto& node)
        {
            return node.position == position;
        });
        assert(node != c.cend());

        m_addedNodePositions.erase(position);
        c.erase(node);
    }
};


texts: Implementation of a simple stack with min method

texts:
The problem statement:

  Implement a stack which has push and pop method and also min method whereas min method has \$O(1)\$ complexity.

From an interview standpoint, what mistakes would you point out in terms of algorithmic design and other things?

#include <iostream>
#include <string>

template<typename T>
class stack
{
  private:
    struct stackNode
    {
       stackNode(T val) : val(val), next(nullptr) {}
       stackNode() {next=nullptr;}
       T val;
       stackNode *next;
    };

  public:
    stack() { first = min = nullptr; sz = 0;}
    ~stack()
    {
      while(first) {
        stackNode *tmp = first->next;
        delete first;
        first = tmp;
      }
    }

    void print()
    {
      stackNode *tmp = first;
      std::cout << "Stack => ";
      while(tmp) {
        std::cout << tmp->val << ", ";
        tmp = tmp->next;
      }
      std::cout << std::endl;
    }

    stackNode* push(T val, stackNode *head)
    {
      stackNode *tmp = new stackNode(val);
      tmp->next = head;
      return head;
    }

    void push(T val)
    {
      first = push(val, first);

      T tVal = val;
      if(min && (min->val < val)) {
        tVal = min->val;
      }
      min = push(tVal, min);
      sz++;
    }

    size_t size()
    {
      return sz;
    }

    void pop()
    {
      if(first) {
        stackNode *tmp = first->next;
        delete first;
        first = tmp;

        //pop min temporary
        tmp = min->next;
        delete min;
        min = tmp;
        sz--;
      }
    }

    T minimum()
    {
      if(min) {
        return min->val;
      }
      return T();
    }

  private:
    stackNode *first, *min;
    size_t sz;
};

using myStack = stack<int>;

int main()
{
  myStack s;

  s.push(10);
  s.push(100);
  s.push(33);
  s.push(55);
  s.push(17);
  s.push(9);
  s.push(201);

  s.print();
  std::cout << "Size of stack = " << s.size() << std::endl;
  std::cout << "Minimum = " << s.minimum() << std::endl;

  s.pop(); s.pop();
  s.print();
  std::cout << "Minimum = " << s.minimum() << std::endl;

  s.pop(); s.pop();
  s.print();
  std::cout << "Minimum = " << s.minimum() << std::endl;

  return 0;
}


texts: Medical database design and queries optimization

texts:
I have created a MySQL database which will be used in a medical app, but I am pretty sure the design and the used queries can be improved, since I am new in database design. My biggest doubt is the s_apply column in combination table. The user should choose 1 main symptom (s_id). Main symptoms may have 0, 1 or 2 symptoms that apply (s_apply). I know it is bad practice to store the full names in s_apply, but I don't know how to improve this. I really need a way to store the symptoms that apply (s_apply) more efficient.

The d_weight in disease indicates if a disease in that context is either common (d_weight <= 5) or less common (d_weight > 5).

Combination table has 2 foreign keys: s_id and d_id.

To get all symptoms of a combination of age, gender and bodypart, I use the following query. There should be a better way to do this:

SELECT DISTINCT symptom.s_id, s_name, s_common FROM symptom, combination WHERE combination.age = '$age' AND combination.gender = '$gender' AND combination.bp_id = '$bodypart' AND combination.s_id = symptom.s_id

To get all diseases of a combination of age, gender, bodypart, s_id and symptoms that apply (s_apply), I use the following query:

SELECT DISTINCT disease.d_id, d_name, d_weight FROM disease, combination, symptom WHERE combination.age = '$age' AND combination.gender = '$gender' AND combination.bp_id = '$bodypart' AND combination.s_id = symptom.s_id AND combination.s_id = '$s_id'

Symptom table

Disease table

Combination table


texts: Prim's algorithm for finding the minimum spanning tree

texts:
So I was coding Prim's algorithm for practice and this is what I wrote. It works for finding the weight of the minimum spanning tree (MST) but I'm wondering if the loop I am doing to add the the edges in the frontier to the minheap is optimal.

import heapq
from collections import defaultdict
g = defaultdict(list)
weight = 0
connected = set([])
pq = []

#n is the number of nodes m is the number of edges
n, m = [int(x) for x in raw_input().split(" ")]
#create adjacency list from inputs of the form "vertex1 vertex2 weight"
for _ in xrange(m):
    a, b, w = [int(x) for x in raw_input().split(" ")]
    g[a].append((w, b))
    g[b].append((w, a))

start = int(raw_input())
connected.add(start)
for tup in g[start]:
    heapq.heappush(pq, tup)
while pq:
    w, b = heapq.heappop(pq)
    if b not in connected:
        weight += w
        connected.add(b)
        #by how much does this loop affect the run time of Prims?
        for tup in g[b]:
            heapq.heappush(pq, tup)

print weight


texts: Generate combinations of a given sequence without recursion

texts:
Given an array of unique numbers find the combinations
Doing a shallow copy in the code to avoid changes to the passed obj by reference
This has a run time of \$O(n \times \text{#ofcombinations})\$ - can this be done better -- iteratively and easy to understand

import copy
def gen_combinations(arr): #
    res = [[]]
    for ele in arr:
        temp_res = []
        for combination in res:
            temp_res.append(combination)
            new_combination = copy.copy(combination)
            new_combination.append(ele)
            temp_res.append(new_combination)
            res = copy.copy(temp_res)

    return res


texts: Passing file identifiers to all subroutines of fortran code

texts:
The Fortran program 'MAIN' below calls 3 subroutines.

It opens a file if it is not present, (overwrites if it is already present).
writes something on the file using the file identifier integer and
closes the file.

       program MAIN

2001 FORMAT (A,I10)
   INTEGER FILEIDS(10)
   CHARACTER*64 fname
   FILEIDS(1) = 701
   write(*,2001) 'opnoutfl', FILEIDS(1)

   fname = 'advect1.dat'

   CALL OFNFL (FILEIDS(1), fname)

   CALL BDEXCH (FILEIDS(1))
   CALL CLOOUTFL(FILEIDS(1))
   END

   SUBROUTINE OFNFL (UNITNO, fname)

   LOGICAL EXISTS, OPND

   INTEGER UNITNO
   CHARACTER*64 fname,dirname,path

2001 FORMAT (A,I10)
     write(*,2001) 'opnoutfl', UNITNO
    dirname = 'sediment/'
    path  = trim(dirname) // trim(fname)

   INQUIRE (file=path, EXIST=EXISTS)

  IF (EXISTS) THEN
     OPEN (UNITNO, file=path, status='old')
     close(UNITNO, STATUS='DELETE')
     OPEN (UNITNO, file=path, status='NEW')
     WRITE(UNITNO,2001) 'Alte Dateil ist geloest  ',UNITNO
  ELSE
     OPEN (UNITNO, file=path, status='NEW')
     WRITE(UNITNO, 2001) 'Neue Datei ist geoeffnet',UNITNO
  END IF

    RETURN
    END

  SUBROUTINE CLOOUTFL (UNITNO)

  INTEGER UNITNO

  CLOSE(UNITNO)
  RETURN
  END

   SUBROUTINE BDEXCH (MESSU)

   INTEGER MESSU

2001 FORMAT (A,I10)

   WRITE(MESSU, 2001) 'bdexch schreibt', MESSU+10

    RETURN
    END

My question is, at this moment I am passing file identifier as argument. How can I modify/improve this code so that the file identifier created in first subroutine i.e. OFNFL() be automatically seen to subsequent subroutines which uses/writes on the file? The program where I want to use it creates lots of files and then different subroutines writes on different files, so passing file identifier like this will not look very clean!!


texts: Integer version of c++ standard library midpoint

texts:
I was extremely annoyed by the lengthy, edge-case-galore explanation of integer version of C++ standard library mindpoint implementation here, so I made my own simple 2's complement version. I present it for your judgement.
The general idea is to carry out a + (b-a)/2 in a wider signed integer that won't ever overflow.
Say a and b are N bit integers. Consider them as imaginary signed (2's complement) N+1 bit integers. The obvious magic of 2's complement is that we can carry out addition/subtraction as usual, so first we obtain the lower N bits of the hypothetical N+1 bit difference,
Unsigned diff = Unsigned(b) - Unsigned(a);

working with unsigned type to avoid signed overflow UB. We don't really have the +1 bit, so just imagine sign extension also happens. We only care about lower N bits anyway since we know the final half difference has to fit there. Problem is - we can't do division in this straightforward way, so we have to branch, based on the sign of the final result.

If N+1 bit difference was negative (highest/sign bit set), we jump through hoops:Negate/abs (2's complement approved as subtraction 0-diff).Unsigned negative_2x = -diff; Divide (it works cause sign bit is now guaranteed 0).negative_2x /= 2;
Now we can fit this halved difference back into our original N bit signed int, so we convert it back and negate to restore the original sign.Integer negative = -Integer(negative_2x);
Converting first is important to avoid signed overflow UB again. If original Integer was unsigned this still works, since the wrapping behavior is consistent with 2's complement.

Otherwise if difference was positive, it fully fit in N bits unsigned, and half of it should fit in signed, no hoops:Integer positive = diff / 2;

The actual branch looks like this to encourage conditional move, not that compilers care...
return a + (b < a ? negative : positive);

The code by itself with a primitive/stand-in function signature, for the purposes of copying into an IDE and compiling:
#include <type_traits>

template<typename Integer, typename Unsigned = std::make_unsigned_t<Integer>>
Integer midpoint(Integer a, Integer b)
{
    Unsigned diff = Unsigned(b) - Unsigned(a);

    Unsigned negative_2x = -diff;
    negative_2x /= 2;
    Integer negative = -Integer(negative_2x);

    Integer positive = diff / 2;

    return a + (b < a ? negative : positive);
}

Also available here, passes all the libstdc++ and libc++ unit tests for integers.


texts: Implementing joinWithSeparator on a Character array

texts:
I recently answered a Stack Overflow question about transforming an array of Characters into a String in Swift.  Looking at the question and the Swift standard lib, it appears that there is a method joinWithSeparator, but the current implementation only supports SequenceType instances where the Element is a String.  As an exercise to myself, I wanted to write an extension on SequenceType that could flatten an array of Characters into a String:

extension SequenceType where Generator.Element == Character {

    @warn_unused_result
    public func joinWithSeparator(separator: String) -> String {

        var str = ""

        self.enumerate().forEach({
            str.append($1)

            if let arr = self as? [Character], endIndex: Int = arr.endIndex {
                if $0 < endIndex - 1 {
                    str.append(Character(separator))
                }
            }
        })

        return str
    }
}

How can I further optimize this code?  Would it be possible to replace the forEach loop with flatMap?  Or is a map call inappropriate since I need to append each character to a String, rather than create a new array?