texts: Project Euler # 62 Cubic permutations in Python

texts:
The cube, 41063625 (\$345^3\$), can be permuted to produce two other cubes: 56623104 (\$384^3\$) and 66430125 (\$405^3\$).
In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.

Find the smallest cube for which exactly five permutations of its digits are cube.

from collections import Counter
from time import perf_counter

def get_cube_permutations(upper_bound, number_of_permutations):
    """Return minimum cube that has number_of_permutations permutations as cubes."""
    cubes = [str(number ** 3) for number in range(1, upper_bound)]
    sorted_cubes = [''.join(sorted(cube)) for cube in cubes]
    count = Counter()
    for sorted_cube in sorted_cubes:
        count[sorted_cube] += 1
    for sorted_cube, number_of_occurrences in count.items():
        if number_of_occurrences == number_of_permutations:
            return cubes[sorted_cubes.index(sorted_cube)]
    return 0

if __name__ == '__main__':
    START_TIME = perf_counter()
    UPPER_BOUND = 10 ** 4
    TARGET_PERMUTATIONS = 5
    MINIMUM_CUBE = get_cube_permutations(UPPER_BOUND, TARGET_PERMUTATIONS)
    if MINIMUM_CUBE:
        print(f'Minimum cube that has {TARGET_PERMUTATIONS} permutations of its digits as cubes: {MINIMUM_CUBE}.')
    else:
        print(f'No cube found that has {TARGET_PERMUTATIONS} of its digits for numbers within range {UPPER_BOUND}.')
    print(f'Time: {perf_counter() - START_TIME} seconds.')


texts: Creating a complex hierarchy for "Player Effects"

texts:
I'm coding a plugin for a game that has a Player class which has a boolean attribute frozen, which decides if the player is frozen or not. There are more "effects" like frozen, but I'm using it as an example, since solving one should solve them all.

The problem is, this frozen attribute only supports True/False, and if a player attacks an other player, freezing him for 5 seconds, and then someone else freezes the player permanently, the permanent freeze will go off after the other person's 5 second freeze ends (due to delay(5, setattr, (player, 'freeze', False)). This is why I need to implement a system that manages all the freezes applied to a player, and then unfreezes the player only when all of the freezes are gone.

Here's my original take on it, which I think is messy and I don't like the fact that I had to add the _effects dictionary to the Player class, when it's only used by the effect objects. I also have to rely on external _name attribute to identify the effect instances, and thus have to pass in an additional name parameter for the PlayerEffect decorator.

from ticks import delay, cancel_delay  # For delayed function calls
import game.core  # For the game's `Player` class

class PlayerEffect(object):

    def __init__(self, name, on_f=None, off_f=None, effect_cls=None):

        if effect_cls is None:
            class effect_cls(_PlayerEffect):
                pass

        effect_cls.name = name
        effect_cls.on_f = on_f
        effect_cls.off_f = off_f

        self._name = name
        self._on_f = on_f
        self._off_f = off_f
        self._effect_cls = effect_cls

    def on(self, on_f):
        return type(self)(self._name, on_f, self._off_f, self._effect_cls)

    __call__ = on

    def off(self, off_f):
        return type(self)(self._name, self._on_f, off_f, self._effect_cls)

    def __get__(self, instance, owner):
        return self._effect_cls(instance)

class _PlayerEffect(object):

    name = None
    on_f = None
    off_f = None

    def __init__(self, player):
        self._player = player

    def __call__(self, duration=-1):
        self._player._effects[self.name].append(self)
        if duration > 0:
            self._delay = delay(duration, self._disable)
        self.on_f(self._player)

    def _disable(self):
        self._player._effects[self.name].remove(self)
        if not self._player._effects[self.name]:
            self.off_f(self._player)

    def cancel(self):
        if self._delay is not None:
            cancel_delay(self._delay)
            self._delay = None
        self._disable()

class Player(game.core.Player):

    def __init__(self, index):
        super().__init__(index)
        self._effects = collections.defaultdict(list)

    @PlayerEffect('freeze')
    def freeze(self):
        self.frozen = True

    @freeze.off
    def freeze(self):
        self.frozen = False

The reason I need to have the _name is so that I can do stuff like this:

class Player(game.core.Player):

    def __init__(self, index):
        super().__init__(index)
        self._effects = collections.defaultdict(list)

    @PlayerEffect('fly')
    def fly(self):
        self.move_state = MoveStates.FLY

    @fly.off
    def fly(self):
        if self._effects['hover']:  # _name used here
            self.move_state = MoveStates.HOVER
        else:
            self.move_state = MoveStates.NORMAL

    @PlayerEffect('hover')
    def hover(self):
        self.move_state = MoveStates.HOVER

    @hover.off
    def hover(self):
        if self._effects['fly']:  # And here
            self.move_state = MoveStates.FLY
        else:
            self.move_state = MoveStates.NORMAL


texts:
I implemented a binary tree in Python, with preorder/postorder/inorder traversal methods.

class BinaryTree(object):

    def __init__(self, rootObj):
        self.key = rootObj
        self.leftChild = None
        self.rightChild = None

    def insertLeftChild(self, newNode):
        if self.leftChild == None:
            self.leftChild = BinaryTree(newNode)
        else:
            newBinaryTree = BinaryTree(newNode)
            newBinaryTree.leftChild = self.leftChild
            self.leftChild = newBinaryTree
        return self.leftChild

    def insertRightChild(self, newNode):
        if self.rightChild == None:
            self.rightChild = BinaryTree(newNode)
        else:
            newBinaryTree = BinaryTree(newNode)
            newBinaryTree.rightChild = newNode
            self.rightChild = newBinaryTree
        return self.rightChild

    def getRoot(self):
        return self.key

    def setRoot(self, obj):
        self.key = obj

    def getLeftChild(self):
        return self.leftChild

    def getRightChild(self):
        return self.rightChild

    def __str__(self):
        return '%s' % self.key

    # DFS traversal techniques.
    @classmethod
    def preorder(cls, node):
        if node == None: return False
        print node
        cls.preorder(node.getLeftChild())
        cls.preorder(node.getRightChild())

    @classmethod
    def inorder(cls, node):
        if node == None: return False
        cls.inorder(node.getLeftChild())
        print node
        cls.inorder(node.getRightChild())

    @classmethod
    def postorder(cls, node):
        if node == None: return False
        cls.inorder(node.getLeftChild())
        cls.inorder(node.getRightChild())
        print node

def buildTree():
    root = BinaryTree('a')
    firstLeft = root.insertLeftChild('b')
    firstRight = root.insertRightChild('c')
    firstLeft.insertRightChild('d')
    firstRight.insertLeftChild('e')
    firstRight.insertRightChild('f')
    return root

if __name__ == '__main__':
    binaryTree = buildTree()
    print 'Preorder'
    print BinaryTree.preorder(binaryTree)
    print 'Inorder'
    print BinaryTree.inorder(binaryTree)
    print 'Postorder'
    print BinaryTree.postorder(binaryTree)

Also, I'd like to know how go about unit testing this code. I'd appreciate guidance and links to relevant documentation.


texts: Calculate last month, last 3 months, and last 6 months from today

texts:
I am looking for some ideas on how this could be improved:

switch ($periodValue) {
    case "lastmonth":
        $until = mktime(0, 0, 0, date('n'), 1, date('Y'));
        $from = mktime(0, 0, 0, date('n', $until) - 1, 1, date('Y', $until));
        break;
    case "last3month":
        $until = mktime(0, 0, 0, date('n'), 1, date('Y'));
        $from = mktime(0, 0, 0, date('n', $until)-3, 1, date('Y', $until));
        break;
    case "last6month":
        $until = mktime(0, 0, 0, date('n'), 1, date('Y'));
        $from = mktime(0, 0, 0, date('n', $until)-6, 1, date('Y', $until));
        break;

How could I make this "smarter", so that it works out if we are near the end of the month it will show the last 30 days instead of the previous month?


texts: Signed integer-to-ascii x86_64 assembler macro

texts:
I have implemented an algorithm which converts a signed integer to its ASCII equivalent string with the corresponding sign as a first byte. I have tested it on several numbers and it worked correctly. But as a newbie I might have not noticed some logic mistakes or flaws.

I am asking for any ideas how to make this more efficient and elegant.

;;;;MACRO SECTION//////////////////////////////////////////////////////////////

%macro Int2ascii 2                  ;1 - number, 2 - string

    mov     r12, %2                 ;move ADDRESS of string

    mov     eax, dword[%1]
    cmp     eax, 0
    jge     %%placePlus             ;check either number is negative or positive

    %%placeMinus:
        mov     byte [r12], "-"     ;fill the first (0th) byte with the sign
        mov     rdi, -1             ;remember the sign
        ;neg     eax                ;negate number and forgot the sign (deprecated: see EDIT 1)
        jmp     %%skipPlacePlus

    %%placePlus:
        mov     byte [r12], "+"
        mov     rdi, 1               ;remember the sign

    %%skipPlacePlus:

    xor     rcx, rcx                ;digit counter here (used implicitely in %%fillLoop)
    mov     ebx, 10

    %%divideLoop:
        cdq                         ;eax -> edx:eax
        idiv    ebx                 ;signed division, reminder is also signed
        imul    rdx, rdi            ;"unsign" the current reminder
        ;div     ebx                ;(deprecated: see EDIT 1)
        push    rdx                 ;push the reminder to stack

        inc     rcx                 ;increment digit counter

        cmp     eax, 0
        jne     %%divideLoop

    mov     rdi, 1                  ;note that the first (0th) byte was number sign (+/-)

    %%fillLoop:
        pop     rax                     ;pop back reminders

        add     al, "0"                 ;ascii code for digit
        mov     byte [r12 + rdi], al    ;fill string
        inc     rdi
        loop    %%fillLoop

    mov     byte [r12 + rdi], 0x00      ;terminate string

%endmacro

Example of output

As @TobySpeight suggested I have tested the above algorithm on numbers: -1, 0, 1, 9, 10, 0x7fffffff, 0x80000000. Output is (gdb session):

(gdb) x/s &sNegOne
0x600377:   "-1"
(gdb) x/s &sZero
0x600368:   "+0"
(gdb) x/s &sPosOne
0x600386:   "+1"
(gdb) x/s &sNine
0x600395:   "+9"
(gdb) x/s &sTen
0x6003a4:   "+10"
(gdb) x/s &sNumber1
0x6003b3:   "+2147483647"
(gdb) x/s &sNumber2
0x6003c2:   "-2147483648"

I have realized that trying to consider only unsigned positive numbers leads to double-word overflow for initially valid double-word number 0x80000000 but invalid after taking absolute value 0x7fffffff + 1 which is no longer signed double-word number. I have overcome it by signed division. The problem here is for signed division reminders are also signed and no more applicable for storing as digits without additional processing which is just multiplying by -1 or 1 depending on sign.


texts: Format raw bytes in hex and ascii in manner like Wireshark does

texts:
This function formats raw buffer output in manner as Wireshark and many others does:

0x00: 68 65 6C 6C 6F 20 77 6F 72 6C 64 02 6B 68 67 61   |hello world.khga|
0x10: 76 73 64 20 0B 20 0A 05 58 61 73 6A 68 6C 61 73   |vsd . ..Xasjhlas|
0x20: 62 64 61 73 20 6A 61 6C 73 6A 64 6E 13 20 20 30   |bdas jalsjdn.  0|
0x30: 31 32 33 34 35 36 37 38 39                        |123456789       |

Please review and assess code quality.

std::string format_hex_payload(const char* payload, size_t payload_len)
{
    const char line_placeholder[] = "0x00:                                                   |                |";
    size_t number_of_lines = payload_len / 16 + (payload_len%16 > 0);
    size_t sizeof_output = sizeof line_placeholder * number_of_lines;
    char *output = (char*)alloca(sizeof_output);  //POSSIBLE REIMPL USE C++RVO std::string out; out.reserve(sizeof_output);

    char *pout = output;  //POSSIBLE REIMPL char *pout = out.data();
    const char *p = payload;
    const char *const end = payload + payload_len;
    size_t ascii_offset = strchr(line_placeholder,'|') - line_placeholder + 1;  //could be calculated at compile time

    unsigned short offset = 0;
    for(unsigned l=0; l < number_of_lines; l++, offset+=16)
    {
        char* pline_begin = pout;
        char* pline = pout;
        strcpy(pline,line_placeholder);
        pline += sprintf(pline, "0x%02X: ", offset);
        for(unsigned i=0; i<16 && p < end; ++i, ++p){
            pline += sprintf(pline, "%02X ", *p);
            *(pline_begin+ascii_offset+i) = isprint(*p) ? *p : '.';
        }
        *pline=' ';
        pout += sizeof line_placeholder;  // move pointer to next line
        pout[-1] = '\n';
    }
    pout[-1] = '\0';
    assert(pout == output + sizeof_output);  // sanity check

    return output;  //POSSIBLE REIMPL return out;
}


texts:
Rather than checking if my angle is in the range of 0 to 2pi every time it gets set, I got the idea to store it as an unsigned short with 0xFFFF being +2pi, thus the standard overflow behavior for unsigned numbers should keep it bound to the desired range.

Is it a good idea to do it this way, or is there something I'm missing?

#ifndef ANGLE_H
#define ANGLE_H
#include <cstdint>

class Angle
{
//static constexpr long double     _PI = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348;
  static constexpr long double _TWO_PI = 6.2831853071795864769252867665590057683943387987502116419498891846156328125724179972560696;

    static inline __attribute((always_inline)) __attribute((pure))
    uint16_t uint16_from_double(const double a) { return (a * 0x00010000) / _TWO_PI; }
    uint16_t _theta;

    Angle(uint16_t theta) :
        _theta(theta)
    {
    }

public:
    Angle(double t = 0) :
        _theta(uint16_from_double(t));
    {
    }

    inline operator double() const
    {
        return radians();
    }

    inline double radians() const { return ((double) _theta) / 0x00010000) * _TWO_PI; }
    inline double degrees() const { return ((double) _theta) / 0x00010000) * 360; }

//everything is less than and greater than everything else, because it's a circle
//so return if subtracting will get us there faster than adding...
    inline bool operator<(const Angle & it) const
    {
        return _theta < it._theta? (it._theta - _theta) < 0x00008000 : (_theta - it._theta) >= 0x00008000;
    }
    inline bool operator<=(const Angle & it) const
    {
        return _theta < it._theta? (it._theta - _theta) <= 0x00008000 : (_theta - it._theta) > 0x00008000;
    }

    inline bool operator>(const Angle & it) const
    {
        return _theta < it._theta? (it._theta - _theta) > 0x00008000 : (_theta - it._theta) <= 0x00008000;
    }
    inline bool operator>=(const Angle & it) const
    {
        return _theta < it._theta? (it._theta - _theta) >= 0x00008000 : (_theta - it._theta) < 0x00008000;
    }

    inline Angle minDelta(const Angle & it) const
    {
        uint16_t i = _theta < it._theta? it._theta - _theta :  _theta - it._theta;
        return Angle(i < 0x00007FFF? i : 0x00010000 - i);
    }

    inline const Angle & operator=(double a)
    {
        _theta = uint16_from_double(a);
        return *this;
    }

    inline const Angle & operator+=(double a)
    {
        _theta += uint16_from_double(a);
        return *this;
    }

    inline const Angle & operator-=(double a)
    {
        _theta -= uint16_from_double(a);
        return *this;
    }

    inline const Angle & operator*=(double a)
    {
        _theta *= a;
        return *this;
    }

    inline const Angle & operator/=(double a)
    {
        _theta /= a;
        return *this;
    }
};

#endif // ANGLE_H


texts:
I'm currently working on a Qt project writing Excel files through a third party DLL.
As the third party DLL has a COM interface, I have to do lots of conversions between QString and BSTR...

I wrote the following two methods to do the conversions:

QString ExcelClass::bstrToQString(const BSTR &bStr) const
{
        _bstr_t convert(bStr, false);
        return QString::fromUtf16(reinterpret_cast<const ushort*>((const WCHAR*)convert));
}

BSTR ExcelClass::qstringToBstr(const QString &qstring) const
{
        WCHAR* const pBuffer = new WCHAR[1000000]; //We have to deal with very large strings...
        MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, qstring.toLocal8Bit().data(), -1, pBuffer, 1000000);
        BSTR result = SysAllocString(pBuffer);
        delete [] pBuffer;
        return result;
}

Even if those methods do their job properly, I have the following questions:

Are those conversions completely correct or can they cause errors in rare cases?
Is there any other (better/easier) way to convert?
Can I somehow avoid allocating pBuffer every time I call the function?

The line WCHAR* const pBuffer = new WCHAR[1000000]; seems to slow the program down significantly, as I am calling the method ~60000 times... I can speed it up a lot when I do the conversion (qstringToBstr()) directly inside the calling function but I want it capsuled in this method...
(converted directly inside the caller, memory was only allocated once per 5-column-line, so still ~12000 times, but that was much faster...)


texts: Rails controller method to show an optionally scaled image using MiniMagick

texts:
I've got below implementation for my controller and show action which implements MiniMagick gem. I've just wondering is there any better way to write it down? If block in a separate, private method maybe?

  def show
    identification_document = IdentificationDocument.find(params[:id])
    authorize identification_document
    return unless identification_document

    if params.has_key?(:thumbnail)
      document = identification_document.id_document
      image = MiniMagick::Image.read(document.file.read)
      image.resize("50x60")
      scaled_image_bytes = image.to_blob
      send_data(scaled_image_bytes, filename: identification_document.file_name)
    else
      send_data(identification_document.id_document.file.read, filename: identification_document.file_name)
    end
  end


texts: Multidimensional array of objects that retrieves the id, title, and smallest box art URL for every video

texts:
Is there a way to simplify this code?

// array
const movieLists = [
        {
            name: "New Releases",
            videos: [
                {
                    "id": 70111470,
                    "title": "Die Hard",
                    "boxarts": [
                        { width: 150, height: 200, url: "http://cdn-0.nflximg.com/images/2891/DieHard150.jpg" },
                        { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/DieHard200.jpg" }
                    ],
                    "url": "http://api.netflix.com/catalog/titles/movies/70111470",
                    "rating": 4.0,
                    "bookmark": []
                },
                {
                    "id": 654356453,
                    "title": "Bad Boys",
                    "boxarts": [
                        { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/BadBoys200.jpg" },
                        { width: 140, height: 200, url: "http://cdn-0.nflximg.com/images/2891/BadBoys140.jpg" }

                    ],
                    "url": "http://api.netflix.com/catalog/titles/movies/70111470",
                    "rating": 5.0,
                    "bookmark": [{ id: 432534, time: 65876586 }]
                }
            ]
        },
        {
            name: "Thrillers",
            videos: [
                {
                    "id": 65432445,
                    "title": "The Chamber",
                    "boxarts": [
                        { width: 130, height: 200, url: "http://cdn-0.nflximg.com/images/2891/TheChamber130.jpg" },
                        { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/TheChamber200.jpg" }
                    ],
                    "url": "http://api.netflix.com/catalog/titles/movies/70111470",
                    "rating": 4.0,
                    "bookmark": []
                },
                {
                    "id": 675465,
                    "title": "Fracture",
                    "boxarts": [
                        { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture200.jpg" },
                        { width: 120, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture120.jpg" },
                        { width: 300, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture300.jpg" }
                    ],
                    "url": "http://api.netflix.com/catalog/titles/movies/70111470",
                    "rating": 5.0,
                    "bookmark": [{ id: 432534, time: 65876586 }]
                }
            ]
        }
    ];

    const arr1 = movieLists
        .map(function (outterItem) {
            return outterItem.videos
                .map(function (innerItem) {
                    return [innerItem.boxarts
                        .reduce(function (acc, currentValue) {
                            if (acc.width * acc.height < currentValue.width * currentValue.height) {
                                return acc
                            } else {
                                return currentValue
                            }
                        })]
                        .map(function (lastItem) {
                            return {
                                id: innerItem.id,
                                title: innerItem.title,
                                boxart: lastItem.url
                            }
                        })
                })
        })

    // flatten deep
    const newArray = (function flattenDeep(arr1) {
            return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
        })(arr1);

    console.log(newArray)


texts:
Please review my Deque implementation in Java and suggest ways of improving this.

    public class DequeImplementation<T> {
    private QueueNode<T> first;
    private QueueNode<T> last;
    private int size;

    private static class QueueNode<T> {
        private T val;
        private QueueNode<T> next;
        private QueueNode<T> prev;

        public QueueNode(T val) {
            this.val = val;
            this.next = null;
            this.prev = null;
        }

        public T getValue() {
            return val;
        }

        public void setNext(QueueNode<T> nextNode) {
            next = nextNode;
        }

        public QueueNode<T> getNext() {
            return next;
        }

        public void setPrev(QueueNode<T> prevNode) {
            prev = prevNode;
        }

        public QueueNode<T> getPrev() {
            return prev;
        }

        public String toString() {
            if(val == null) {
                return "null";
            }
            return val.toString();
        }
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void offerLast(T val) {
        QueueNode<T> cur = new QueueNode(val);
        if(size == 0) {
            cur.setNext(first);
            first = cur;
            last = cur;
            size++;
            return;
        }

        last.setNext(cur);
        cur.setPrev(last);
        last = cur;
        size++;
    }

    public void offerFirst(T val) {
        QueueNode<T> cur = new QueueNode(val);
        if(size == 0) {
            cur.setNext(first);
            first = cur;
            last = cur;
            size++;
            return;
        }

        cur.setNext(first);
        first.setPrev(cur);
        first = cur;
        size++;
    }

    public T peekLast() {
        if(isEmpty()) {
            return null;
        }
        return last.getValue();
    }

    public T peekFirst() {
        if(isEmpty()) {
            return null;
        }
        return first.getValue();
    }

    public QueueNode<T> pollFirst() {
        if(isEmpty()) {
            return null;
        }

        QueueNode<T> cur = first;
        first = first.getNext();
        if(first != null) {
            first.setPrev(null);
        }
        size--;
        return cur;
    }

    public QueueNode<T> pollLast() {
        if(isEmpty()) {
            return null;
        }

        QueueNode<T> cur = last;
        last = last.getPrev();
        if(last != null) {
            last.setNext(null);
        }
        size--;
        return cur;
    }

    public void clear() {
        size = 0;
        first = null;
        last = null;
    }

    @Override
    public String toString() {
        if(size == 0) {
            return "[]";
        }

        StringBuilder sb = new StringBuilder("null<-");
        QueueNode<T> cur = first;
        sb.append(cur.getValue() + "<-");

        while(cur.getNext() != null && !cur.equals(last)) {
            sb.append(cur.getNext().getValue() + "<-");
            cur = cur.getNext();
        }

        sb.append("null");
        return sb.toString();
    }

    public static void main(String[] args) {
        DequeImplementation<Integer> dq = new DequeImplementation<>();
        System.out.println(dq.size());
        System.out.println(dq.pollLast()); //returns null
        System.out.println(dq);
        dq.offerLast(100);
        dq.offerFirst(10);
        dq.offerFirst(1);
        System.out.println(dq.pollFirst());
        System.out.println(dq);
        System.out.println(dq.size());
        System.out.println(dq.peekLast());
        System.out.println(dq.pollLast());
        System.out.println(dq);
        System.out.println(dq.size());
        System.out.println(dq.pollFirst());
        System.out.println(dq.pollLast()); //returns null
        dq.clear();
        System.out.println(dq.size());
    }
}


texts: VBA Excel function to interpolate precipitation data

texts:
I wrote this code to interpolate precipitation data. When I run this code, it works very well, but the problem is that it slows my computer down so I have to wait 5 mins to interpolate the data.

Is there any way to make this function work faster?

Function IDWW(Value1, Value2, Value3, Dist1,Dist2,Dist3)
    Dim a1 As Variant
    Dim b1 As Variant
    Dim a2 As Variant
    Dim b2 As Variant
    Dim a3 As Variant
    Dim b3 As Variant

    If Value1 <> "" And Dist1 <> "" Then
        a1 = Value1 / (Dist1) ^ 2
        b1 = 1 / (Dist1) ^ 2
    Else
        a1 = 0
        b1 = 0
    End If

    If Value2 <> "" And Dist2 <> "" Then
        a2 = Value2 / (Dist2) ^ 2
        b2 = 1 / (Dist2) ^ 2
    Else
        a2 = 0
        b2 = 0
    End If

    If Value3 <> "" And Dist3 <> "" Then
        a3 = Value3 / (Dist3) ^ 2
        b3 = 1 / (Dist3) ^ 2
    Else
        a3 = 0
        b3 = 0
    End If

    'Avoid a problem if all 3 distances are empty
    If b1 + b2 + b3 = 0 Then
        IDWW = 0
    Else
        IDWW = (a1+a2+a3) / (b1+b2+b3)
    End If
End Function


texts: Implementation of many-to-many relation Tag Table

texts:
I have belowe tables, for Map string[] Tags from ViewModel to Model I'm using Below codes :

  public class Tag:BaseEntity
{
    public string Name { get; set; }
    public virtual ICollection<Blog.BlogPost> BlogPosts { get; set; }
    public virtual ICollection<News.NewsItem> NewsItems { get; set; }

}
 public class BlogPost : BaseContent, IAuditable
    {
    public virtual ICollection<Tag> Tags { get; set; }
}

public class NewsItem : BaseContent, IAuditable
    {
    public virtual ICollection<Tag> Tags { get; set; }

    public NewsItem()
    {
        Tags = new List<Tag>();
    }
}

In newsService I have two methods Insert ,Update to Add and Update NewsItem :

     public void Insert(AddNewsItemViewModel newsItemViewModel)
    {
        if (newsItemViewModel == null)
            throw new ArgumentNullException("newsItem");

        var model = Mapper.Map<NewsItem>(newsItemViewModel);

        if(newsItemViewModel.Tags.Any()) // Tags is `string[]`
        {
            var listOfActualTags = _tagService.GetTagsByName(newsItemViewModel.Tags); // return List<Tag>
            var listOfActualTagNames = listOfActualTags.Select(x => x.Name.ToLower()).ToList();

            foreach (var tag in newsItemViewModel.Tags)
            {
                if (!listOfActualTagNames.Contains(tag.ToLowerInvariant().Trim()))
                {
                    Tag tagModel = new Tag { Name=tag};
                    _tagService.Insert(tagModel);
                    model.Tags.Add(tagModel);
                }
            }

            model.MetaKeywords =string.Join(",",newsItemViewModel.Tags);
        }
        _uow.MarkAsAdded(model);
    }

and for Update  Method I have this Code :

        public void Update(EditNewsItemViewModel newsItemViewModel)
    {
        if (newsItemViewModel == null)
            throw new ArgumentNullException("newsItem");
        var model = GetById(newsItemViewModel.Id);
        model = Mapper.Map(newsItemViewModel, model);
        if (model.Tags != null && model.Tags.Any())
            model.Tags.Clear();

        var listOfActualTags = _tagService.GetTagsByName(newsItemViewModel.Tags); // return List<Tag>
        var listOfActualTagNames = listOfActualTags.Select(x => x.Name.ToLower()).ToList();

        foreach (var tag in newsItemViewModel.Tags)
        {
            Tag tagModel = new Tag { Name = tag };
            if (!listOfActualTagNames.Contains(tag.ToLowerInvariant().Trim()))
            {

                _tagService.Insert(tagModel);
                model.Tags.Add(tagModel);
            }
            else
                model.Tags.Add(tagModel);
        }

        model.MetaKeywords = string.Join(",", newsItemViewModel.Tags);

        _uow.MarkAsChanged(model);
    }

For BlogPost I have to repeat Above Code (for tag part) fro that , Is there a way to Optimize this ?


texts: Check if an XML file exists then change URLs in it

texts:
This is my first VBScript I have ever written and I would like to know if there is any obvious blunders in the code. All the code should do is check if file exists then change the Yahoo URL to the Google URL in the XML file. Note: The code seems to function properly.

Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")

If (objFSO.FileExists("C:\urlsinfo.xml")) Then
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

Dim textToReplace
Dim textReplacement
textToReplace = "http://www.yahoo.com"
textReplacement = "http://www.google.com"

Set objFile = objFSO.OpenTextFile("C:\urlsinfo.xml", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, textToReplace, textReplacement)

Set objFile = objFSO.OpenTextFile("C:\urlsinfo.xml", ForWriting)
objFile.WriteLine strNewText
objFile.Close
WScript.Quit()

Else
Dim errorFileSys, errorLogTxt

Set errorFileSys = CreateObject("Scripting.FileSystemObject")
Set errorLogTxt = errorFileSys.OpenTextFile("C:\urlsinfoError.log", ForAppending, True)
errorLogTxt.WriteLine(Now &"     urlsinfo.xml file did not exist in directory C:\. ")
errorLogTxt.Close

WScript.Quit()
End If

'Exit Script
WScript.Quit()


texts: Soup of the day: best served during election season

texts:
Community moderator elections on the Stack Exchange network are really exciting.
Alas, on the page of the primaries, I find it mildly annoying that candidates are randomly reordered on every page load, even if it's surely for a good reason.

So, I cooked up (pun totally intended) this script using Beautiful Soup 4 in Python to list the candidates in an election by their score. To use it, install beautifulsoup4 (for example with pip install --user beautifulsoup4), and then to list the candidates running for Code Review:

$ python primaries.py so -n 6  # the 6th election on Stack Overflow
10905   Martijn Pieters
7310    meagar
5923    Jon Clements
5461    Matt
5211    Madara Uchiha
4133    deceze
3301    Raghav Sood
3180    Paresh Mayani
3126    Jeremy Banks
2651    Ed Cottrell

Since all the Stack Exchange sites seem to use the same format, it can work with all Stack Exchange sites. For the sake of a POC I included support for a few other sites (use "so" for Stack Overflow, "sf" for Server Fault), obviously it should be extended for others. Another feature I plan to add soon is to find the latest election by default, rather than using the first.

I mainly suspect some improvement opportunities concerning my use of Beautiful Soup, but I'm open to any kind of improvement ideas in general.

#!/usr/bin/env python

from argparse import ArgumentParser
from urllib import request

from bs4 import BeautifulSoup

STANDARD_URL_FORMAT = 'http://{}.stackexchange.com/election/{}?tab=primary'
COM_URL_FORMAT = 'http://{}.com/election/{}?tab=primary'

SITES_INFO_HELPER = [
    (('cr', 'codereview'), STANDARD_URL_FORMAT, 'codereview'),
    (('sf', 'serverfault'), COM_URL_FORMAT, 'serverfault'),
    (('so', 'stackoverflow'), COM_URL_FORMAT, 'stackoverflow'),
]

def build_sites_info():
    sites_info = {}
    for info in SITES_INFO_HELPER:
        names, url_format, url_component = info
        for name in names:
            sites_info[name] = url_format, url_component
    return sites_info

def load_html_doc(url):
    return request.urlopen(url).read()

def get_soup(url):
    html_doc = load_html_doc(url)
    soup = BeautifulSoup(html_doc, 'html.parser')
    # print(soup.prettify())  # for debugging
    return soup

def main():
    sites_info = build_sites_info()

    parser = ArgumentParser(description='Show candidates of an SE election in sorted order')
    parser.add_argument('site', choices=sites_info.keys(),
                        help='Site short name or abbreviation')
    parser.add_argument('-n', type=int, default=1,
                        help='Election number')
    args = parser.parse_args()

    site_info = sites_info[args.site]
    url_format, url_component = site_info
    url = url_format.format(url_component, args.n)

    soup = get_soup(url)
    scores = []
    for tr in soup.find_all('tr'):
        if tr.find('td', attrs={'class': 'votecell'}):
            username = tr.find(attrs={'class': 'user-details'}).find('a').text
            votes = int(tr.find(attrs={'class': 'vote-count-post'}).text)
            scores.append((username, votes))

    for name, score in sorted(scores, key=lambda x: x[1], reverse=True):
        print('{}\t{}'.format(score, name))

if __name__ == '__main__':
    main()


texts: Storing user permissions to hierarchically structured data in SQL Server

texts:
I'm developing a system that supports creating accounts and multiple users within every account that can each access a certain subset of data of their "parent" account.

The data is stored in a SQL Server database in the following tables:

Accounts: Id(guid, primary key), Title(nvarchar(200))
Users: Id(guid, primary key), Login(nvarchar), AccountId(guid, foreign key).

Now, I need to implement a concept of "Folders" and "Files" within accounts. Each account can have a number of files (an object with a name and a few other non significant properties) that can be arranged into folders (like a file system), and every user might have a permission to access a folder. "A user has permission to view a folder" means that this user can see all files within this folder and within all its subfolders. These folders/files also have to support a lot of moving around the hierarchy, renaming, editing, etc.

I have come up with the following table structure for this scenario:

Folders: Id(guid, primary key), Name(nvarchar(200)), AccountId(guid, foreign key)), ParentFolderId(guid, foreign key)
Files: Id(guid, primary key), Name(nvarchar(200)), FolderId(guid, foreign key),
UserFolderPermissions: Id(guid, primary key), FolderId(guid, foreign key), UserId(guid, foreign key)

This structure does the job of storing data correctly, but I also need to run some complex queries against it, like finding a complete path to a file or retrieving all files that current user has permissions to access. For that, I created a view that outputs all folders, files, and users who have permissions to access them:

WITH FolderWithPath AS
    (
        SELECT
            folder.Id,
            folder.Name,
            folder.AccountId,
            folder.ParentFolderId,
            CAST('/' + folder.Name + '/' AS NVARCHAR(4000)) AS Path
        FROM
            dbo.Folders folder
        WHERE
            (ParentFolderId IS NULL)

        UNION ALL

        SELECT
            self.Id,
            self.Name,
            self.AccountId,
            self.ParentFolderId,
            CAST(parent.Path + self.Name + '/' AS NVARCHAR(4000)) AS Path
        FROM
            dbo.Folders AS self
            INNER JOIN FolderWithPath AS parent ON self.ParentFolderId = parent.Id
    )

SELECT
    file.Id AS FileId,
    folder.AccountId,
    folder.Id AS FolderId,
    folder.Path AS Path,
    userFolderPathPermissions.UserId AS AuthorizedUserId
FROM
    FolderWithPath AS folder
    LEFT OUTER JOIN dbo.Files AS file ON file.FolderId = folder.Id
    LEFT OUTER JOIN
    (
        SELECT
            UserFolderPermissions.UserId,
            folder1.Path,
            folder1.AccountId
        FROM
            FolderWithPath folder1
            INNER JOIN UserFolderPermissions AS UserFolderPermissions ON folder1.Id = UserFolderPermissions.FolderId
    ) userFolderPathPermissions ON folder.AccountId = userFolderPathPermissions.AccountId AND folder.Path LIKE userFolderPathPermissions.Path +'%'

Now, this does seem to work, but I have certain performance concerns. Is it the best database structure to fit my needs? Is the query inside the view the optimal way to access the necessary data?

Due to different security issues, I am unable to test it in a real environment with millions of users performing hundreds of operations per second, so I would appreciate any advice regarding the code above.


texts:
I developed a small package to do matrix math. I just learned Go so I may have done it wrong.

package matrix

import "fmt"
import "errors"
import "math"

type Matrix [][]float64

func Print(m Matrix) {
    fmt.Println(m)
}

func Zeros(rows, cols int) Matrix {
    m := make([][]float64, rows)
    for i := 0; i < rows; i++ {
        m[i] = make([]float64, cols)
    }
    return m
}

func Map(f func(float64) float64, m Matrix) Matrix {
    mapped := Zeros(len(m), len(m[0]))
    for i, row := range m {
        for j, val := range row {
            mapped[i][j] = f(val)
        }
    }
    return mapped
}

func Norm(m Matrix) float64 {
    var norm float64
    for _, row := range m {
        for _, val := range row {
            norm += math.Abs(val)
        }
    }
    return norm
}

func Transpose(m Matrix) Matrix {
    transposed := Zeros(len(m[0]), len(m))
    for i, row := range m {
        for j, val := range row {
            transposed[j][i] = val
        }
    }
    return transposed
}

func Multiply(a, b Matrix) (Matrix, error) {
    if len(a[0]) != len(b) {
        return nil, errors.New("Multiplication is not defined")
    }
    m := Zeros(len(a), len(b[0]))
    for i := 0; i < len(a); i++ {
        for j := 0; j < len(b[0]); j++ {
            for k := 0; k < len(b); k++ {
                m[i][j] += a[i][k] * b[k][j]
            }
        }
    }
    return m, nil
}

And here is a code using the package:

package main

import "matrix"

func main() {
    m := matrix.Map(func (f float64) float64 {
        return 1
    }, matrix.Zeros(2, 2))
    prod, _ := matrix.Multiply(m, m)
    println(matrix.Norm(prod))
}


texts: Find all combinations of a number sequence which is first increasing then decreasing

texts:
Given an integer N(Natural Number), A program/Algorithm to find the
  remainder of arrangements that can be obtained by rearranging the
  numbers 1, 2, ...., N.

  Input Format: One line containing the integer N

  Output Format: An integer m, giving the remainder of the number of
  arrangements that could be obtained from 1, 2, ...., N is divide
  by Mod

  Constraints:
  Mod = 10^9+7
  N ≤ 10^9

  Example 1 Input
  3  Output
  2  Explanation: Consider the first three natural numbers 1, 2, 3. These can be arranged in the following ways: 2, 3, 1 and 1,
  3, 2. In both of these arrangements, the numbers increase to a certain
  point and then decrease. There are two such arrangements: 2, 3, 1 and
  1, 3, 2.

  Example 2

  Input
  4  Output
  6  Explanation: The six arrangements are (1, 2, 4, 3), (1,3,4,2), (1,4,3,2), (2,3,4,1), (2,4,3,1), (3,4,2,1).

#include<stdio.h>
#include<stdlib.h>
#define m 1000000007

unsigned long long int power(unsigned long long int x, unsigned long long int n){

    unsigned long long int res = 1;
    while(n > 0){
        if(n & 1){
            res = res * x;
            res = res%m;
        }
        x = x * x;
        x= x%m;
        n >>= 1;
    }
    return res;

}

int main(){

    unsigned long long int n,res=0,temp=1,i;
    scanf("%llu", &n);
    if(n==1 || n==0){
        printf("0\n");
        return 0;
    }
    temp = power(2, n-1);
    temp--;
    temp--;
    printf("%llu\n", temp);

    return 0;
}

Can Anyone Solve This with Better Time Complexity?


texts:
Is it possible to implement this function without goto, while keeping the code correct and readable?

using iter = std::string::const_iterator;

// Skip multiline comment in a source string.
// Initial iterator is at the first character after the "/*"
iter skipMultilineComment( iter i, iter fileEnd )
{
    while( true )
    {
        const char c1 = *i;
        if( c1 != '*' )
        {
            i++;
            if( i != fileEnd )
                continue;
            break;
        }

        // Found '*' character
    FoundAsterisk:
        i++;
        if( i == fileEnd )
            break;
        const char c2 = *i;
        if( c2 == '*' )
        {
/* Found another '*' character; can be more: ****/
            goto FoundAsterisk;
        }
        if( c2 != '/' )
        {
            i++;
            if( i != fileEnd )
                continue;
            break;
        }
        // Finally, found the closing token, "*/"
        i++;
        return i;
    }
    logError( "fatal error C1071: unexpected end of file found in comment" );
    throw E_INVALIDARG;
}

P.S. That’s not a test assignment or something, it’s production code. The input is GLSL, but the comments there are the same as in C++.


texts: Stop connecting to a server after n unsuccessful attempts

texts:
I am trying to connect to a server.
If the connection goes through, then print an apt message.
If the connection does not go through, try for a total of n times. And quit after the nth attempt with an apt message.

I set up a mock server like this -

class Server:
    def __init__(self):
        self.connection_status = random.choice([True, False, False, False])

    def get_connection(self):
        if self.connection_status:
            return "Connected"
        else:
            raise EnvironmentError("Connection Error")

And then I tested it as follows -

def connect_to_server():
    s = Server()
    try:
        return s.get_connection()
    except EnvironmentError as e:
        return str(e)

def main():
    count = 0
    while count < 3:
        connection = connect_to_server()
        if connection == "Connection Error":
            count += 1
            print(connection, count)
            if count == 3:
                print("No more connection attempts")
        else:
            count = 0
            print(connection)

So, after 3 re-connection attempts, the program will terminate.

Is there a better / elegant way to do this?


texts:
I created online shop with angular 7 and I am not sure is good architecture. I created 5 modules:

main module
products
shop-cart
core
admin

I have service :

admin.service.ts
products.service.ts
data-storage-service.ts
message-data.service.ts
shop-cart.service.ts

I have module for routing:

app-routing.module.ts
products.service.ts

In main module I include all others module:

@NgModule({
  declarations: [
    AppComponent

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    CoreModule,
    AdminModule,
    SharedModule,
    ShopCartModule,
    ProductsModule,
    HttpClientModule,
    FormsModule,
    ModalModule.forRoot(),

    HttpClientInMemoryWebApiModule.forRoot(
      InMemoryDataService, { dataEncapsulation: false }
    )

  ],
  providers: [,
    InMemoryDataService],
  bootstrap: [AppComponent]
})
export class AppModule { }

This is my core module where I include all service:

@NgModule({

  imports: [
    CommonModule,
    AppRoutingModule
  ],
  exports: [
    AppRoutingModule,
    HeaderComponent,
    FooterComponent

  ],
  declarations: [
    HeaderComponent,
    HomeComponent,
    FooterComponent
  ],
  providers:[
    DataStorageServiceService,
    ProductsService,
    ShopCartService,
    AdminSerivice,
    MessageService
  ]
})
export class CoreModule { }

I using data-storage-service.ts for communication with server. In my admin.service.ts and products.service.ts I have methods for  calling method form data-storage-service.ts  and store data in list.
Example:
data-storage-service.ts have method :

 /** GET Category from the server */
  getCategory(): Observable<CategoryModel[]> {
    return this.http.get<CategoryModel[]>(this.cateogryUrl).pipe(

      catchError(this.handleError('getProduct', []))
    )
  }

admin.service.ts have method:

getCategoryFromServer() {
        this.dataStorageServiceServiceta.getCategory().subscribe((category: CategoryModel[]) => {
            this.categoryList = category;
            this.cateogoryChanged.next(this.categoryList.slice())
        })
    }

And in componentadmin.componenet.ts in ngOnInit I have

 ngOnInit() {
    this.admin.getCagegoryFromServer();
  }

Are is this correct ?


texts:
I've been fooling around in JavaScript again, and I've come up with this simple physics simulation. I think it has a pretty simple setup, here's "psuedocode" of sorts to explain it.

Constructor PhysicsEntity

Private method _calculateForces - Calculates forces to be applied.
Private method _applyForces - Apply the calculated forces.
Private method _renderEntity - Render the PhysicsEntity at it's position.
Method updateEntity - Update the entity.

I think the interface is pretty clear, but if you have any suggestions, they would be greatly appreciated.

/*
A simple physics object for managing
certain things such as forces acting
upon the object, and rendering.
*/
var PhysicsEntity = function(mass, entityWidth, entityHeight, accelerationVector, position, lifeTime)
{
    this.mass = mass;
    this.entityWidth = entityWidth;
    this.entityHeight = entityHeight;
    this.accelerationVector = accelerationVector;
    this.position = position;
    this.velocity = new PVector(0, 0);

    // Calculate the forces to be applied to the velocity
    this._calculateForces = function()
    {
        this.velocity.add(this.accelerationVector.x*this.mass, this.accelerationVector.y*this.mass);
    };

    // Apply velocity to the Entity's position
    this._applyForces = function()
    {
        this.position.add(this.velocity);
    };

    // Render the Entity at it's position
    this._renderEntity = function()
    {
        rect(this.position.x, this.position.y, this.entityWidth, this.entityHeight);
    };

    // Update the entity
    this.updateEntity = function()
    {
        this._calculateForces();
        this._applyForces();
        this._renderEntity();
    };
};

Here's an example of how this can be used.

// Data for creating new PhysicsEntities and storing them
var DEFAULT_MASS = 1;
var DEFAULT_WIDTH = 10;
var DEFAULT_HEIGHT = 10;
var DEFAULT_ACCELERATION = new PVector(0, 0.2);
var DEFAULT_LIFETIME = 250;
var entityArray = [];

// Create a new PhysicsEntity at the mouse
var createEntity = function()
{
    entityArray.push(
        new PhysicsEntity(
            DEFAULT_MASS, DEFAULT_WIDTH, DEFAULT_HEIGHT,
            DEFAULT_ACCELERATION, new PVector(mouseX, mouseY),
            DEFAULT_LIFETIME
        )
    );
};

// Update all entities
var updateEntities = function()
{
    for(var n = entityArray.length-1; n >= 0; n--)
    {
        var entity = entityArray[n];
        entity.updateEntity();
    }
};

// Main draw loop
draw = function() {
    background(255, 0, 0);
    createEntity();
    updateEntities();
};


texts: Finding the 'Minimum' AND of all the possible subsets of a set

texts:
The subset size should be greater than or equal to 2.

How can I speed up this code?

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<malloc.h>
#include <iostream>
#include <vector>
long long int set[100000];
long long int counter, j;
long long  int ans,min,count;
bool ha;
long long int pow_set_size;
long long int power[100000];
void printPowerSet(long long int set_size)
{
    pow_set_size =power[set_size];
    count=4;

    for(counter = 3; counter < pow_set_size; counter++)
    {
      ha=0;
        if(counter!=count)
       {
            for(j = 0; j < set_size; j++)
       {
          if(counter & (1<<j))
          {
              if(!ha)
                  {
                  ans=set[j];
                  ha=1;
              }
              else
             {
                  ans=((ans) & (set[j]));
              }
           }

       }
          // printf("%lld\n",ans);
            if(counter==3)
            {
            min=ans;
        }
            else if(min>ans)
                {
                min=ans;
            }
       }

        else
        {
            count=count*2;
        }
    }

   printf("%lld\n",min);
}

void pre()
    {
    power[0]=1;
    for(int i=1;i<=100000;i++)
        {
        power[i]=power[i-1]*2;

    }

}

int main()
    {
    long long int test;
    long long int len;
   long long int a;
    scanf("%lld",&test);

    pre();
    while(test--)
        {
        scanf("%lld",&len);
        for(int i=0;i<len;i++)
            {
            scanf("%lld",&set[i]);
        }
        printPowerSet(len);

    }
    return 0;
}


texts: Java method to load random paragraph from text file

texts:
Looking for some critique for this code. but ultimately I would like to be directed to resources/books that address my code writing weaknesses, in terms of style structure an convention :

The task is to create code that would read a file that has several questions and answers, each question starts with the word "Question", and out put the question and a number of lines from the answer that is not greater than 40 lines.

my code method below is meant to:

read all lines into an List.
select a random start line in the list.
check id the line starting with the string "Question".
check if the remaining list elements are more than 40 (I've appended 40 empty lines to the end of the file, to make sure to include the last lines of the file).
create a string buffer to include maximum the 39 lines which are present after the start line, the one that contains "Question" , if the the word "Question" appears before the 40th line, then we we end the text captured at the preceding line (creating a text block).
return that (text block).

public static String readJavaInterview() throws IOException{

        List<String> list = Files.readAllLines(new File("src/lists/JavaCodingInterview.txt").toPath(), Charset.defaultCharset() );
        List<String> subList = new ArrayList<>();
        int start=0 , end= 0;

        Random rand = new Random();
        int n = rand.nextInt(list.size());
        StringBuffer textBlock= new StringBuffer();
        Pattern p = Pattern.compile("Question");
        Matcher m;

        textBlock.append("Some Java Interview Qs :\n");

        if (n + 40 < list.size()){

            subList = list.subList(n, n + 40);

            for (int i = 0 ; i < subList.size() - 1 ; i++){
                m = p.matcher(subList.get(i).toString());
                boolean b = m.find();

                if (b)
                    {

                    start= i + 1;
                    textBlock.append(subList.get(i) + "\n");
                    break;
                }else{
                    continue;
                }
            }

            for(int j = start ; j < start + 39; j++){
                m = p.matcher(subList.get(j).toString());
                boolean b = m.find();
                if (!b){

                    textBlock.append(subList.get(j) + "\n");

                }else{

                    break;
                }
            }

        }else{
            return "";
        }

        return textBlock.toString();
    }

Would this be how you would do it?


texts: Hexadecimal converter using a switch statement

texts:
I need some help improving my code and wondering if I there is a better way to do the following:

StringBuilder buf = new StringBuilder(node.length() + 8);
        for (int i=0, n=node.length(); i<n; i++) {
            char c = node.charAt(i);
            String hexadecimal = "";
            switch (c) {
                case '"': hexadecimal = "\\22"; break;
                case '&': hexadecimal = "\\26"; break;
                case '\'': hexadecimal = "\\27"; break;
                case '/':  hexadecimal = "\\2f"; break;
                case ':': hexadecimal = "\\3a"; break;
                case '<': hexadecimal = "\\3c"; break;
                case '>': hexadecimal = "\\3e"; break;
                case '@': hexadecimal ="\\40"; break;
                case '\\':hexadecimal = "\\5c"; break;
                default: {
                    if (Character.isWhitespace(c)) {
                        hexadecimal = "\\20";
                    }else if(c > 127){
                        hexadecimal = "\\" + Integer.toHexString(c) + "\\";
                    }
                    else {
                        hexadecimal = String.valueOf(c);
                    }
                }
            }
            buf.append(hexadecimal);
        }
        return buf.toString();

I don't like how there is a switch statement which just sets a variable (hexadecimal) based on what the case is. I feel there is a better way to do this, such as by using a hash-map. I need the code to be flexible so that adding new characters and setting the hexadecimal is easy.


texts: Pandas dataframe custom forward fillna optimisation

texts:
I have a function that synchronizes according to some specifications columns of a dataframe.
The functions works, nevertheless I was wondering how to:

Improve performances
Make it more pythonic

Please feel free to leave any suggestions.

Function specifications

Inputs:

df : a dataframe with columns:

[a0,...aN] : a0 to aN names can be any valid string and contains numeric values
[agent,date] : are fixed names, agent contains numeric values and date contains datetime.

sync_with : The columns to synchronize with (a string or an listof string contained in [a0,..., aN] or, by default, an empty list to synchronize all the [a0,...,aN].

Synchronization:

Do a forward fillna grouped by agent values.
Drop the rows where all columns to synchronize with values are empty

Returns : the synchronized dataframe

Here is my function:

import pandas as pd
import numpy as np

def synchronize(df,sync_with=[]):
    _df = df.copy()

    if not isinstance(sync_with,list):
        sync_with = [sync_with]

    _fixed_cols = ['date','agent']
    _fixed_cols.extend(sync_with)
    _colset = [c for c in _df.columns if c not in _fixed_cols]

    for ag in _df.agent.unique():
        _df.loc[_df.agent==ag,_colset] = _df.loc[_df.agent==ag,_colset].fillna(method='ffill')
        if _sync_with:
            _df.loc[_df.agent==ag,:] = _df.loc[_df.agent==ag,:].dropna(how='all', subset=_sync_with)
            _df.loc[_df.agent==ag,:] = _df.loc[_df.agent==ag,:].fillna(method='ffill')

    return _df.dropna(how='all', subset=_sync_with)

Sample

foo = pd.DataFrame(dict(date=pd.to_datetime(['2010', '2011', '2012', '2013', '2010', '2013', '2015', '2016']),
                        agent=[1,1,1,1,2,2,2,2],
                        _a=[1, np.nan, np.nan, 4, 5, np.nan, 7, 8],
                        _b=[11, 22, np.nan, np.nan, 55, np.nan, 77, np.nan],
                        _c=[111, np.nan, 333, np.nan, np.nan, 666, 777, np.nan]))

Results

# 1. default (13 ms per loop)
print(synchronize(foo))
    _a    _b     _c  agent       date
0  1.0  11.0  111.0      1 2010-01-01
1  1.0  22.0  111.0      1 2011-01-01
2  1.0  22.0  333.0      1 2012-01-01
3  4.0  22.0  333.0      1 2013-01-01
4  5.0  55.0    NaN      2 2010-01-01
5  5.0  55.0  666.0      2 2013-01-01
6  7.0  77.0  777.0      2 2015-01-01
7  8.0  77.0  777.0      2 2016-01-01

# 2. sync with one column (35 ms per loop)
print(synchronize(foo,'_c'))
    _a    _b     _c  agent       date
0  1.0  11.0  111.0      1 2010-01-01
2  1.0  22.0  333.0      1 2012-01-01
5  5.0  55.0  666.0      2 2013-01-01
6  7.0  77.0  777.0      2 2015-01-01

# 3. sync with two columns (35 ms per loop)
print(synchronize(foo,['_a','_b']))
    _a    _b     _c  agent       date
0  1.0  11.0  111.0      1 2010-01-01
1  1.0  22.0  111.0      1 2011-01-01
3  4.0  22.0  333.0      1 2013-01-01
4  5.0  55.0    NaN      2 2010-01-01
6  7.0  77.0  777.0      2 2015-01-01
7  8.0  77.0  777.0      2 2016-01-01


texts: Pass canvas content from client to admin using web socket

texts:
The application's aim is to transfer drawings from the client canvas to the admin canvas using web sockets, as smoothly as possible. At every mousemove event, the client canvas is compressed to .png and sent to the server through a websocket to finally arrive in the admin window where the image is drawn into the admin canvas.

Actually, the code lags a little in the admin window. It seems the bottleneck is ctx.drawImage() but I am not sure.

I wonder if there is a way to first find the bottleneck and then a way to optimise the transfer with debounce or web workers or other.

Client side:

<canvas id="clientCanvas" style="position: absolute; top: 0px; left: 0px;" width="1563" height="528">

function onMouseMove (e) {
    var canvas = document.getElementById('clientCanvas');
    var ctx = canvas.getContext("2d");
    var imageData = canvas.toDataURL("image/png");

    socket.emit('SS_onMouseMove', {imageData: imageData});
};

admin side:

<canvas id="adminCanvas" style="position: absolute; top: 0px; left: 0px;" width="1563" height="528">

var canvas = document.getElementById("adminCanvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   ctx.drawImage(image, 0, 0);
};

socket.on("SS_onMouseMove", function(response) { onClientMouseMove(response); });

function onClientMouseMove(response){
    image.src = response.imageData;
}


texts:
I want to sync the table every few minutes to a remote database. I want it to be as efficient as possible. I wrote this stored procedure that will only return rows that are added or removed after the last query.

Basically, this stored procedure will return something like this:

190107080001 | REMOVED | NULL   | NULL  | NULL | NULL        | NULL |
190107080005 | ADDED   | 225545 | Name2 | 5    | Specialist2 | 26   |
190107080108 | ADDED   | 230139 | Name3 | 8    | Specialist3 | 44   |

Note: the [key] is actually simple hashed value from the row itself, the remote database will use the [key] as Identity.

Actually I do not have problem with this code until now, but I think my implementation is not effective enough considering I will execute this query 24/7.

CREATE PROCEDURE [dbo].[GetMonthlySchedules]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    ----------------------------------------------------------------
    -- Select new record and save it to temporary table
    ----------------------------------------------------------------
    SELECT [key]
         , id
         , therapist
         , therapistId
         , specialist
         , specialistId

      INTO #Temp_MonthSchedule

      FROM doc
INNER JOIN spe ON doc.specialistId = spe.Id
INNER JOIN lis ON doc.Id = lis.DocId

     WHERE lis.Dt >= DATEADD(dd, 1, DATEDIFF(dd, 0,  GETDATE()))
       AND lis.Dt <= DATEADD(mm, 1, DATEDIFF(dd, 0,  GETDATE()))

    ----------------------------------------------------------------
    -- Select the different between old and new records to return it later
    ----------------------------------------------------------------
    SELECT ISNULL(old.[key], new.[key]) AS [key]
        , CASE WHEN old.Id IS NULL THEN 'ADDED' WHEN new.Id IS NULL THEN 'REMOVED' END AS operation
        , new.id, new.therapist, new.therapistId, new.specialist, new.specialistId

      INTO #Temp_MonthScheduleDiff

      FROM ComparerMonthSchedule AS old
FULL OUTER JOIN #Temp_MonthSchedule AS new
        ON old.[key] = new.[key]

     WHERE old.id IS NULL
        OR new.id IS NULL

    ----------------------------------------------------------------
    -- Replace old record with new record
    ----------------------------------------------------------------

    DELETE FROM ComparerMonthSchedule
    INSERT INTO ComparerMonthSchedule SELECT * FROM #Android_Temp_MonthSchedule

    ----------------------------------------------------------------
    -- Return records
    ----------------------------------------------------------------

    SELECT * FROM #Temp_MonthScheduleDiff

    ----------------------------------------------------------------
    -- Delete temporal table
    ----------------------------------------------------------------

    IF OBJECT_ID('tempdb..#Temp_TodaySchedule') IS NOT NULL BEGIN DROP TABLE #Temp_TodaySchedule END;
    IF OBJECT_ID('tempdb..#Temp_TodayScheduleDiff') IS NOT NULL BEGIN DROP TABLE #Temp_TodayScheduleDiff END;
END


texts: Enforce what is passed to an activity in an intent similar to the newInstance pattern for fragments

texts:
For fragments I have this code to create a new instance:

public static FoodDetails newInstance(Food food) {
    FoodDetails foodDetails = new FoodDetails();
    Bundle args = new Bundle();
    args.putParcelable(FoodConstants.BundleConstants.FOOD_OBJECT, food);
    foodDetails .setArguments(args);
    return foodDetails ;
}

What I like about this is that I can see what arguments are passed to the fragment.

I want a similar way for Activities so this is my proposed solution.

public class FullScreenImageActivity extends BaseActivity {

public static Intent createIntent(String[] images, String googleAnalyticsCategory,int positionToStartFrom){
    Intent intent = new Intent(MyApplication.getInstance(),FullScreenImageActivity.class);
    intent.putExtra(FoodConstants.BundleConstants.LIST_OF_IMAGES_TO_DISPLAY,images);
    intent.putExtra(FoodConstants.BundleConstants.GOOGLE_ANALYTICS_CATEGORY,googleAnalyticsCategory);
    intent.putExtra(FoodConstants.BundleConstants.POSITION_TO_START_FROM, positionToStartFrom);
    return intent;
}

The method returns a built intent and adds the parameters to the bundle
Note that MyApplication is a subclass of Application so I am using the application context in the intent argument.

And then you can start the activity like this:

startActivity(FullScreenImageActivity.createIntent(mImages, AnalyticsUtils.CATEGORY_FOOD,position));

The benefits are:

Do not need type the bundle keys all the time
You can see what arguments are passed to the activity


texts: Angular 2 Component conditionally displaying a list of elements from an array

texts:
This Angular component displays a list of polls that are fetched from the server and has a slide toggle giving the authenticated user the option to display all polls or just the ones that the user has authored. I use Angular Material and Angular Flex Layout.

I'm specifically looking for feedback regarding best practices and how I handled displaying polls conditionally, but welcome all feedback. I chose to keep most of the conditional logic in the component instead of in the template but I'm not sure that is in accordance with Angular best practices.

poll-list.component.html

  <md-slide-toggle *ngIf="isLoggedIn()" (change)="displayMyPolls()" fxFlexAlign="center">Show only my polls</md-slide-toggle>
  <md-nav-list fxFlexAlign="center">

      <md-icon md-list-icon>poll</md-icon>

{{poll?.question}}

{{poll?.getTotalVotes()}} votes

  </md-nav-list>

poll-list.component.ts

import { Component, OnInit } from '@angular/core';

import { PollService } from './poll.service';
import { AuthService } from '../auth/auth.service';
import { Poll } from './poll.model';

@Component({
  selector: 'app-poll-list',
  templateUrl: './poll-list.component.html',
  styleUrls: ['./poll-list.component.css']
})
export class PollListComponent implements OnInit {
  polls: Poll[] = [];
  pollsToDisplay: Poll[] = [];
  showOnlyMyPolls = false;

  constructor(private pollService: PollService, private authService: AuthService) { }

  ngOnInit() {
    this.pollService.getPolls()
      .subscribe(
                (polls: Poll[]) => {
                    this.polls = polls;
                    this.pollsToDisplay = polls;
                }
            );
  }

  displayMyPolls() {
    this.showOnlyMyPolls = !this.showOnlyMyPolls;
    if (this.showOnlyMyPolls) {
      this.pollsToDisplay = this.polls.filter((poll) => {
        return this.authService.isLoggedInUser(poll.userId);
      });
    } else {
      this.pollsToDisplay = this.polls;
    }
  }

  isLoggedIn() {
    return this.authService.isLoggedIn();
  }

}


texts: Adjusting dates in an array based on a start date

texts:
I have a data structure like this which holds start/end dates:

----|-----------|-----------
Item| start     | end
----|-----------|-----------
1   |2017-05-12 | 2017-05-12
2   |2017-05-12 | 2017-05-13
3   |2017-05-13 | 2017-05-13
4   |2017-05-13 | 2017-05-14
5   |2017-05-14 | 2017-05-15
6   |2017-05-15 | 2017-05-16
7   |2017-05-16 | 2017-05-16

I want to move the start date of the first item to 2017-01-01 and every item should follow that start date and must stay within its ranges. The result should look like the following:

----|-----------|-----------
Item| start     | end
----|-----------|-----------
1   |2017-01-01 | 2017-01-01
2   |2017-01-01 | 2017-01-02
3   |2017-01-02 | 2017-01-02
4   |2017-01-02 | 2017-01-03
5   |2017-01-03 | 2017-01-04
6   |2017-01-04 | 2017-01-05
7   |2017-01-05 | 2017-01-05

This is how I implemented the method:

// ActiveItems() method (although it's bad naming) retrieves all the currently active hotels/transfers etc from a booking.
var items = booking.ActiveItems(); // each item has check-in and/or check-out dates, internals doesn't matter for this problem

var tempCurrentDate = newStartDate;
var previousCheckoutDate = newStartDate;

// go thru each item
for (var i = 0; i < items.Count; i++)
{
    var currentItem = items[i];
    // again, bad naming but internals doesn't really matter. method returns a check-in date (DateTime)
    var itemCheckinDate = currentItem.CheckInDate();
    var itemCheckoutDate = currentItem.CheckOutDate();

    // no of days between check-out and check-in
    // this difference later added to the new check-in date to get the new check-out
    var checkinToCheckoutDifference = (itemCheckoutDate - itemCheckinDate).Days;
    if (i == 0)
    {
        // check-in equals to start date if the item is the first one in the list
        itemCheckinDate = tempCurrentDate;
    }
    else
    {
        var prevDayToCurrentCheckinDifference = (previousCheckoutDate - currentItem.CheckInDate()).Days;
        itemCheckinDate = tempCurrentDate.AddDays(prevDayToCurrentCheckinDifference);
    }

    //SetCheckInDate() internals really doesn't matter here.
    currentItem.SetCheckInDate(itemCheckinDate);

    previousCheckoutDate = itemCheckoutDate;

    tempCurrentDate = itemCheckinDate.AddDays(checkinToCheckoutDifference);

    currentItem.SetCheckOutDate(tempCurrentDate);
}

Even though this code works as expected, is there a better and efficient way of doing this?


texts: Collecting adjacent cells in a 2D grid implemented as a 1D list

texts:
The grid is implemented as an ArrayList<Cell> cells with the number of columns as int cols and int length = rows * cols. The id of a Cell is equal to its position in the list. The first element of cells is the top-left cell and the last element is the bottom-right cell.

public ArrayList<Cell> getAdjCells(int id) {
    ArrayList<Cell> cs = new ArrayList<>();
    //check if cell is on an edge
    boolean l = id %  cols > 0;        //has left
    boolean u = id >= cols;            //has upper
    boolean r = id %  cols < cols - 1; //has right
    boolean d = id <  length - cols;   //has lower
    //collect all existing adjacent cells
    if (l)      cs.add(cells.get(id - 1       ));
    if (l && u) cs.add(cells.get(id - 1 - cols));
    if (u)      cs.add(cells.get(id     - cols));
    if (u && r) cs.add(cells.get(id + 1 - cols));
    if (r)      cs.add(cells.get(id + 1       ));
    if (r && d) cs.add(cells.get(id + 1 + cols));
    if (d)      cs.add(cells.get(id     + cols));
    if (d && l) cs.add(cells.get(id - 1 + cols));
    return cs;
}

I may restructure ArrayList<Cell> cells as Cell[] cells later on. Return type can be any type of collection really. I just want this function to be as fast as possible, since I have to use it very often.


texts:
This is a basic sorting function written in jQuery that moves items in the DOM around to create empty spaces for a droppable(). Since there is so much going on in a droppable over event, i'd love some feedback on how this could be done better.

This is all in a function called on the over event of the droppable()

I have an array of empty spots

    var emptyHolders = [];

    $('.pipeline-holder').each(function(){
        if($(this).hasClass('holder-empty')){
            var eid = $(this).attr('id');
            emptyHolders.push(eid.substring(14));
        }
    });

cid is the droppable element that you're over top of, so I find the next open slot using

   for (var i = 0; i < emptyHolders.length; i++) {
        var currentEmpty = emptyHolders[i];
        if (currentEmpty > cid) {
            nextEmpty = currentEmpty;
            i = emptyHolders.length;
        } else {
            prevEmpty = parseInt(currentEmpty);
        }
    }

If there is a an empty slot further down the list, I use a for loop to loop through moving the items around the DOM to make the space needed to drop the element.

 if (nextEmpty != null) {
        var moveMe = nextEmpty -1;

        for (var i = moveMe; i >= cid; i--) {

            var nextcount = i + 1;
            var me = $('#pipeline-rank-' + i);
            var next = $('#pipeline-rank-' + i).parents('.pipeline-rank-row').next().find('.pipeline-holder');
            var pid = $('#pipeline-rank-' + i).find('.content-wrapper').attr('id');

            next.append($('#pipeline-rank-' + i).find('.content-wrapper'));
            next.removeClass('holder-empty');
            next.siblings('.remember-my-position-hover').html(pid);
        }
         $('#pipeline-rank-' + cid).addClass('holder-empty');
    }

If there is not one further down the list, I do the same thing in reverse to check if there is a spot above the droppable to push items up into.

It's usable here: http://jsfiddle.net/mstefanko/LEjf8/9/

Any thoughts are extremely appreciated!


texts: AngularJs: Preventing multiple $q.get() per url

texts:
I've wrote a pretty useful method to prevent multiple requests per single get url. There is a well known pattern - to store promise and return it for each next request. But there is too much copy/paste for my taste. So, please check my solution. Maybe you can give me advice to make it better or maybe point at any mistakes.

Here it is (working plunker):

promisedService.$inject = ['$q', '$http', '$httpParamSerializer'];
function promisedService($q, $http, $httpParamSerializer){

    var promisesInProgress = {};

    return {

        singleGet: singleGet

    }

    /**
     * you can pass:
     * url
     * url and callback function
     * url, params and callback function
     */
    function singleGet(url){

        var params, preResolve;
        if(arguments.length == 3){
            preResolve = arguments[2];
            params = arguments[1];
        }
        else if(arguments.length == 2){
            if(typeof arguments[1] === 'function'){
                preResolve = arguments[1];
            }
            else {
                params = arguments[1]
            }
        }

        // creating unique key based on URL + params
        var requestUrl = _buildUrl(url, params);

        // checking for promise. If promise already exists - returning it
        if(promisesInProgress.hasOwnProperty(requestUrl)) {
            return promisesInProgress[requestUrl];
        }

        // else - saving new promise
        var deferred = $q.defer();
        promisesInProgress[requestUrl] = deferred.promise;

        // sending a request
        $http.get(url, params).then(function(response){
            console.log('server request');

            // if callback was passed, wrapping it in promise and returning
            // why do we need a callback. In case we need to cache data
            if(preResolve){
                $q.when(preResolve(response)).then(function(data){
                    deferred.resolve(data);
                });
            }
            else
            //else - returning data as is
                deferred.resolve(response);
            delete promisesInProgress[requestUrl];
        }, function(error){
            deferred.reject(error);
            delete promisesInProgress[requestUrl];
        });

        return deferred.promise;
    }

    /////////////////////////////// PRIVATE /////////////////////////////////

    function _buildUrl(url, params) {
        var serializedParams = $httpParamSerializer(params);

        if (serializedParams.length > 0) {
            url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
        }

        return url;
    }
}


texts: Identifying indices of non-delimited characters in a string, supporting greater than 1 length of delimiters

texts:
The code below takes a string that potentially contains a true match for a delimiter. There can be multiple delimiters located anywhere in the string. We need to obtain the indices that are not a match and when the delimiter starts and ends.
The following code achieves this. However, I am unsure if this is the most optimal method. What do you think? Test cases below the code.
String baseText = "%!ABCD%!EF%";
String delimiter = "%";
ArrayList<String> selectedParameters = new ArrayList<>();

int lastNonDelimited = 0;
int i = 0;
while (i < baseText.length()) {
    int j = 0;
    while (j < delimiter.length()) {

        if (j + i == baseText.length() - 1 && j != delimiter.length() - 1) {
            lastNonDelimited += 1;
            System.out.println(lastNonDelimited);
            break;
        }

        char c = baseText.charAt(i + j);
        char d = delimiter.charAt(j);

        if (c == d) {
            if (j == delimiter.length() - 1) {
                lastNonDelimited += delimiter.length();
                i += (delimiter.length() - 1);
                System.out.println("End" + (i + j));
            } else {

                System.out.println("Beginnning" + (i + j + 1));
            }
        } else {
            lastNonDelimited += 1;
            System.out.println(lastNonDelimited);
            break;
        }

        j += 1;
    }

    i += 1;
}

Test case 1:
String %!ABCD%!EF% with %! delimiter results in:
Beginnning1
End2
3
4
5
6
Beginnning7
End8
9
10
11

Test case 2:
String %!ABCD%!EF%! with %! delimiter results in:
Beginnning1
End2
3
4
5
6
Beginnning7
End8
9
10
Beginnning11
End12


texts:
I did some study on the command pattern but most of its examples were in Java so, there must be some difference in implementation in Python. I implemented it in Python with some minor differences, please let me know if something is not correct.

from abc import ABCMeta
from abc import abstractmethod
import inspect
import os

class Command(object):
    """
    Abstract / Interface base class for commands.
    """
    __metaclass__ = ABCMeta

    @abstractmethod
    def execute(self):
        pass

    @abstractmethod
    def undo(self):
        pass

class CreateCommand(Command):
    """
    Create command implementation.
    """
    def __init__(self, name):
        self.file_name = name

    def execute(self, name):
        open(self.file_name, 'w')
        print str(self) + ':::Method:::' + inspect.stack()[0][3]

    def undo(self):
        os.remove(self.file_name)
        print str(self) + ':::Method:::' + inspect.stack()[0][3]

class MoveCommand(Command):
    """
    Move command implementation.
    """
    def __init__(self, src, dest):
        self.src = src
        self.dest = dest

    def execute(self, src, dest):
        os.rename(self.src, self.dest)
        print str(self) + ':::Method:::' + inspect.stack()[0][3]

    def undo(self):
        os.rename(self.dest, self.src)
        print str(self) + ':::Method:::' + inspect.stack()[0][3]

class Invoker(object):

    def __init__(self, command):
        self.command = command

    def do(self):
        self.command.execute()

    def undo(self):
        self.command.undo()

# Client for the command pattern
if __name__ == '__main__':
    create_cmd = CreateCommand('/tmp/foo.txt')
    move_cmd = MoveCommand('/tmp/foo.txt', '/tmp/bar.txt')
    create_invoker = Invoker(create_cmd)
    move_invoker = Invoker(move_cmd)
    create_invoker.do()
    move_invoker.do()
    move_invoker.undo()
    create_invoker.undo()

O/P:

<__main__.CreateCommand object at 0xb705130c>:::Method:::execute
<__main__.MoveCommand object at 0xb705134c>:::Method:::execute
<__main__.MoveCommand object at 0xb705134c>:::Method:::undo
<__main__.CreateCommand object at 0xb705130c>:::Method:::undo


texts:
I simply want to organize some data (class= MarketOnCloseSecurity) to be used in another class MarketOnClosePortfolio. The former class would not have any methods but just a constructor that includes a ticker for a company symbol and two Pandas dataframes bars and signals.

class MarketOnCloseSecurity():
    """Encapsulates the notion of a portfolio of positions based
    on a set of signals as provided by a Strategy.

    Requires:
    symbol - A stock symbol which forms the basis of the portfolio.
    bars - A DataFrame of bars for a symbol set.
    signals - A pandas DataFrame of signals (1, 0, -1) for each symbol.
   """

    def __init__(self, symbol, bars, signals):
        self.symbol = symbol
        self.bars = bars
        self.signals = signals

Now the MarketOnClosePortfolio would have all the methods to calculate a portfolio.

Is creating a class with essentially no methods (besides constructor) in python a good practice?

The idea is to pass MarketOnClosePortfolio a list of MarketOnCloseSecurity objects.

An alternative (non-OOP) solution would do something like list_of_MOCS = [{'symbol_1':(bars_1,signals_1)},...,{'symbol_N':(bars_N,signals_N)}] so basically a list containing a map with the key being the ticker and value being a tuple of the two dataframes.

MarketOnClosePortfolio will identify the positions (buy/sell) and how based on each MarketOnCloseSecurity and form a Portfolio Dataframe. It will then calculate metrics, such as holdings, cash, and returns based on the summation of each MarketOnCloseSecurity. The code is not complete, but I have included it for reference.

class MarketOnClosePortfolio(Portfolio):
    """Encapsulates the notion of a portfolio of positions based
    on a set of signals as provided by a Strategy.

    Requires:
    market_on_close_securities
    initial_capital - The amount in cash at the start of the portfolio."""

    def __init__(self, market_on_close_securities, initial_capital=100000.0):
        self.market_on_close_securities = market_on_close_securities
        self.initial_capital = float(initial_capital)
        self.positions = self.generate_positions()

    def generate_positions(self):
        #loop through each MOCS (market_on_close_security) to calculate positions

        # Initialize index for positions Dataframe. Picking index 0 was arbitary they all have same index length
        positions = pd.DataFrame(index=self.market_on_close_securities[0].signals.index).fillna(0.0)
        for security in self.market_on_close_securities:
            positions[security.symbol] = 100 * security.signals['signal'] # This strategy buys 100 shares

        return positions

    def backtest_portfolio(self):

        portfolio_series = self.positions[self.symbol] * self.bars[0]['close_price'].astype(float)

        pos_diff = self.positions.diff()

        # Will need to use this for multiple columns (Eventually)
        symbol_columns = [self.symbol]

        portfolio = pd.DataFrame(index=self.bars[0].index, columns=symbol_columns)
        portfolio[self.symbol] = portfolio_series.values

        # Sum holdings from each company
        portfolio['holdings'] = portfolio.sum(axis=1)
        portfolio['cash'] = self.initial_capital - (pos_diff[self.symbol] * self.bars[0]['close_price'].astype(float)).cumsum()
        portfolio['cash'][0] = self.initial_capital
        portfolio['total'] = portfolio['cash'] + portfolio['holdings']
        portfolio['returns'] = portfolio['total'].pct_change()

        return portfolio

The backtest_portfolio() will determine the total returns/holdings based on each MarketOnCloseSecurity. This implementation is not complete, and is currently the method used when MarketOnClosePortfolio was adapted for only one security.


texts: Script to load controllers dynamically for AngularJS

texts:
I would like to hear your thoughts, idea's or feedback on the following code.

Ive added to code to github.

https://github.com/redbullzuiper/angularjs-dynamic-controllers

Usually when you attach a controller to a DOM element using ng-controller="myController", you need to include the controller somewhere in your page; for instance:

<script src="src/application/controllers/my-controller.js"></script>

However, when including the script I wrote in the head, it will traverse across the DOM and search for all ng-controller attributes.

It will then automatically append the correct controller into the head of the page. After it's done including all the controllers, it will manually bootstrap the application using:

angular.bootstrap(document, ['module_name']);

This way all controllers are getting loaded dynamically, without the need of including all controllers in your head. But they will instead only get loaded when called.

Can't create a demo using a fiddle, but a working demo can be found here

The code:

window.onload = function()
{
    var promises = [];
    var ngApp = document.querySelectorAll('[ng-app]')[0];
    var ngControllers = document.querySelectorAll('[ng-controller]');

    // Throw warning if angular is not found
    if(typeof angular == 'undefined')
    {
        console.warn("simplify error: Angular not found, operation canceled.");
        return;
    }

    // Throw warning if ng-app directive exists. Script will bootstrap the application manually
    if(ngApp)
    {
        console.warn("Please remove the ng-app directive. `Simplify` will bootstrap the application manually.");
        console.warn("This will also most likely fix the 'Uncaught Error: [$injector:modulerr]' error.");
    }

    // Append the scripts
    for(var i = 0;i < ngControllers.length;i++)
    {
        var promise = new Promise(function(resolve, reject) {
            var src = 'src/application/controllers/'+ ngControllers[i].getAttribute('ng-controller') + '.controller.js';
            var script = document.createElement('script');
                script.setAttribute('src', src);

            document.head.appendChild(script);

            script.addEventListener('load', function() {
                resolve(script);
            });
        });

        // Push promises to array to resolve them all together later on
        promises.push(promise);
    }

    // Resolve all promises then bootstrap the app
    // Without the use of promises, the bootstrap will start before all scripts are included
    // This results into an erro
    Promise.all(promises).then(function() {
        angular.bootstrap(document, ['app']);
    });
}


texts: Python pandas: Take column of counts and create DataFrame with a row per count

texts:
I have a DataFrame with values in columns a and b and a third column with the count of that row. I would like to convert this into a DataFrame (either new or remake the old one) with columns a and b repeated the number of times as is in the count column. It's probably more clear with an example. I have this DataFrame:

import pandas as pd
df = pd.DataFrame({'a' : [1,2,3], 'b' : [0,0,1], 'count' : [3,1,4]})

I am converting it like this:

new_df = pd.DataFrame(columns=df.columns[:-1])
for _, row in df.iterrows():
    num = row['count']
    for i in range(num):
        pd.concat([new_df, row])
        new_df = new_df.append(row[:-1])

This does exactly what I want but seems inelegant to me because of the for-loop inside iterrows. Is there a better or more pythonic way to do this?


texts:
I am trying to find a efficient solution for the 3n + 1 problem on uvaonlinejudge. The code I have uses memoization using a dictionary. I am getting a 'Time limit Exceeded' error when I submit the code.
Can anyone suggest an improvement(s) that will help with the execution time of this code.

I have already seen this post and implemented the proposed improvements. All other posts related to this are either for C++ or Java.

import sys

def recCycleLength(n,cycLenDict):
    if n==1:
        return 1
    if n not in cycLenDict:
        if n%2==0:
            cycLen = recCycleLength(n//2, cycLenDict)
            cycLenDict[n] = cycLen + 1
            return cycLen+1
        else:
            cycLen = recCycleLength(3*n+1, cycLenDict)
            cycLenDict[n] = cycLen + 1
            return cycLen+1
    else:
        return cycLenDict[n]

def maxCycle(a, b):
    i = a
    mydict = {}
    maxLength = 1
    while i <= b:
        m = recCycleLength(i, mydict)
        if m > maxLength:
            maxLength = m
        i = i + 1
    return maxLength

for line in sys.stdin:
    curr_line=line.split()
    num1 = int(curr_line[0])
    num2 = int(curr_line[1])
    if num1>num2:
        num1, num2 = num2, num1
    m = maxCycle(num1, num2)
    print("{} {} {}".format(num1, num2, m))


texts: Finding sum of consecutive values from a list

texts:
I'd like to improve my algo to find out the (sub)sum of consecutive values from the list. The function will return match as a double index, where the first value is the starting point of values, and the second value is the endpoint of values, where the searched sum can be generated.

// f=find sum value, a=list of values
function findConsecutiveSum(f, a) {

  var r = []; // result
  var b = []; // lookback values
  var s = 0;  // current sum
  var i = 0;  // index
  var l = a.length; // length of list

    // look back when sum (s) exceeds find sum value (f)
  function lookback() {
    // first value from lookback list
    var m = b.shift();
    while (m) {
      s -= m;
      if (s > 0) {
        if (s == f) {
          r.push([i-b.length, i]);
          b = []; s = 0;
          break;
        } else {
          m = b.shift();
        }
      } else {
        break;
      }
    }
  }
    // loop over all values from the list starting from beginning
  while (i<l) {
    s += a[i];
    // match found
    if (s == f) {
      r.push([i-b.length, i]);
      b = []; s = 0;
    // sum bigger than matched value
    } else if (s > f) {
      lookback();
      // if sum is not 0 after lookback, then add current value to lookback list
      if (s) b.push(a[i]);
    // sum smaller than matched value
    } else {
      b.push(a[i]);
    }
    i++;
  }
  // end of the original list is reached, but we still might need to look back
  if (b.length) lookback();
  return r;
}

To test and debug I use this snippet:

// debug, changes index range to actual values and check the sum
function checkResult(result, a, f) {
    return result.map(function(item) {
    var s = a[item[0]];
    var b = a[item[0]];
    for (var i=item[0]; i<item[1]; i++) {
        // real sum
        s += a[i+1];
      b += '+'+a[i+1];
    }
    return b+'='+s+(f==s ? ' true'  : ' false');
  });
}

// find value
var f = 5;
// find value by consecutive sum of the given list
var a = [1, 2, 3, 4, 5, 5, 6, 5, 1, 2, 1, 2];
// result is a list of index range of values, that match sum value (f)
var result = findConsecutiveSum(f, a);
// debug -> Array [ "2+3=5", "5=5", "5=5", "5=5", "2+1+2=5" ]
console.log(checkResult(result, a, f));

jsFiddle

In addition:

Negative values are not accepted, zeros are accepted.
Note that summation is reset after a match is found, then search continues from the current position. Another option could be to not reset summation and to continue search from the last lookback position. An example is shown here.


texts: Better way to validate user input in cakephp

texts:
I'm trying to find a way to make my code easeier to read, so i found that major part of the code is validation trough if, ifelse:

    if (!$this -> is_valid_username($username)) {
        $this -> Session -> setFlash('Enter valid client username, Error 1.', 'default', array(), 'errorlogaddclient');
        $this -> redirect('/dashboard/settings');
        exit ;
    }
    if (!$this -> is_valid_password($password) || !$this -> is_valid_defpass($password)) {
        $this -> Session -> setFlash('Enter valid password, Error 2.', 'default', array(), 'errorlogaddclient');
        $this -> redirect('/dashboard/settings');
        exit ;
    }
    if ($this -> is_already_client($user)) {
        $this -> Session -> setFlash("User is already someone's client, Error 3", 'default', array(), 'errorlogaddclient');
        $this -> redirect('/dashboard/settings');
        exit ;
    }//ect

so what is proper/better way to do this


texts:
I wrote a method that will start OpenVPN on a config file, and then wait to be connected.

It relies on OpenVPN using Local Area Connection 2, which hurts code reusability, but I'm not sure how to do it any other way.

private static async void StartOpenVPN(string configFile)
{
    // Start OpenVPN on the config file...
    Process.Start("openvpn-gui", $"--connect {configFile}");

    // OpenVPN uses Local Area Connection 2.
    var adapter =
        NetworkInterface.GetAllNetworkInterfaces()
            .First(networkInterface => networkInterface.Name == "Local Area Connection 2");

    // Wait for Local Area Connection 2 to be operational...
    while (adapter.OperationalStatus != OperationalStatus.Up)
    {
        await Task.Delay(100);
        adapter =
            NetworkInterface.GetAllNetworkInterfaces()
                .First(networkInterface => networkInterface.Name == "Local Area Connection 2");
    }

    Console.WriteLine("Connected!");
}

Is there a more effective/efficient/elegant way to start OpenVPN on a config file, and then wait to be connected?


texts:
I am having some difficulty with commenting my code for a Python password cracking application I have created. I have commented on the majority of the code. However, I was wondering if anyone could suggest anymore comments I need as my instructor is really stick on me commenting my code.

import time
import string

#Variables
max_attempts = 999999999 #the number of attempts the system makes for a brute-force attack
start       = time.time() #monitors the time length
chars       = list(string.printable) #all the possible ascii characters which the system uses to determine the password
base        = len(chars) #the base for conversion
n           = 0 #number of attempts
solved      = False
password    = input("Enter your password:") #the feature which allows the user to enter in their chosen password

print(chars) #record of previous password attempts

# converts number N base 10 to a list of digits base b
def numberToBase(n, b):
    digits = []
    while n: # takes n and the finds the modulus, the remainder of n % b
        digits.append(int(n % b)) # then it will append that to a list
        n //= b # following on it will then divide n into b
    return digits[::-1] #returns those digits into reverse order from -1, the end to the beginning

# checks if the user has inputted empty text/numbers/symbols
if password == '':

    print('Your password is empty')
    solved = True

elif password == chars[n]:
    print('Your password is ' + chars[n])
    solved = True

else:
    n = 1

#Begins systematically checking the password
if not solved:
    while n < max_attempts:
        list = numberToBase(n, base)
        print(list)
        word = ''
        for c in list: #loop through each of the characters in the list
            word += str(chars[c]) #adds the characters from the list to a word
        print(word)
        if password == word: #checks if the password equals to the word the system has generated
            solved = True # if the generation is correct the password will then commence to print statements
            print('***Results***')
            print('Password: ' + word)
            print('Attempts: ' + str(n))
            print('Time: ' + str((time.time() - start)) + ' sec')
            break #stops the loop
        else:
            n += 1 #however if the password generation isn't correct, we increment with n

# the password is beyond max_attempts
if not solved:
    print('Unsolved after ' + str(n) + ' attempts!')


texts:
I insert a value into a SQLite database and return the id of the last inserted value as a result of the method.

I asked a question on Stackoverflow and I found this solution to my problem. Now I would like to get feedback if there is a simpler, smarter and/or safer way to do that:

int MyRepository::Insert(std::shared_ptr<MyObject> myObject)
{
  if(myObject == nullptr) { return -1; }

  sqlite3_exec(_connection, "BEGIN TRANSACTION;", NULL, NULL, NULL);

  std::string query = R"(
     INSERT INTO myObject (EquipmentId, ExerciseId ) VALUES (?1, ?2);
  )";

  int lastInsertedId = -1;
  sqlite3_stmt* sqlStatement;
  sqlite3_prepare_v2(_connection, query.c_str(), -1, &sqlStatement, nullptr);

  sqlite3_bind_int (sqlStatement, 1, myObject->GetEquipmentId());
  sqlite3_bind_int (sqlStatement, 2, myObject->GetExerciseId() );

  int returnCode = sqlite3_step(sqlStatement);

  if (returnCode != SQLITE_DONE)
  {
    throw SqliteException(returnCode, std::string(sqlite3_errmsg(_connection)));
  }

  query = "SELECT last_insert_rowid()";

  returnCode = sqlite3_prepare_v2(_connection, query.c_str(), -1, &sqlStatement, NULL);

  if (returnCode != SQLITE_OK)
  {
    throw SqliteException(returnCode, std::string(sqlite3_errmsg(_connection)));
  }

  returnCode = sqlite3_step(sqlStatement);

  if(returnCode == SQLITE_ROW)
  {
    lastInsertedId = sqlite3_column_int(sqlStatement, 0);
  }

  sqlite3_exec(_connection, "COMMIT;", NULL, NULL, NULL);

  sqlite3_finalize(sqlStatement);

  return lastInsertedId;
}


texts: Dice rolling simulator, any ideas on implementing any features?

texts:
This is one of my mini project of dice rolling and I want to improve it further with more advanced Python. Maybe you have any ideas to improve the code itself?

This code will ask the minimum and maximum number for the dice from the user and the number of times it will roll them, giving random numbers.

import random
#Size choosing for dice
while True:
    #Choosing the minimum number
    Min = input("Please input the minimum number of your dice: ")
    try:
        Min = int(Min)
    except ValueError:
        print("Invalid input")
        continue
    #Choosing the maximum number
    Max = input("Please input the maximum number of your dice: ")
    try:
        Max = int(Max)
    except ValueError:
        print("Invalid input")
        continue
    #Check if the minimum and maximum is valid
    if Min > Max:
        print("Minimum is bigger than Maximum.\n Please reinput data...")
        continue
    elif Min == Max:
        print("Minimum is equaled to Maximum,\n Please reinput data...")
        continue
    print(f"Your dice is from {Min} to {Max}.")
    break

#Random number generater
while True:
    Rollcount = input("How many times do you want to roll the dice: ")
    try:
        Rollcount = int(Rollcount)
        break
    except ValueError:
        print("Invalid input")
        continue
for i in range(0,Rollcount):
    roll = random.randint(Min,Max)
    print(roll)


texts:
I have a sort of database with a many-to-many association between tags and files. For various reasons, I decided to forgo a junction table in favor of having the left and right tables store the associated values in the tables themselves. However I've ended up writing code like this:

GHashTable *tagdb_get_tag_files (tagdb *db, int tag_code)
{
    return g_hash_table_lookup(db->reverse, GINT_TO_POINTER(tag_code));
}

GHashTable *tagdb_get_file_tags (tagdb *db, int file_id)
{
    return g_hash_table_lookup(db->forward, GINT_TO_POINTER(file_id));
}

void tagdb_remove_tag (tagdb *db, int id)
{
    GHashTable *its_files = g_hash_table_lookup(db->reverse, GINT_TO_POINTER(id));
    if (its_files == NULL)
    {
        return;
    }

    GHashTableIter it;
    gpointer key, value;
    g_hash_table_iter_init(&it, its_files);
    if (g_hash_table_iter_next(&it, &key, &value))
    {
        tagdb_remove_tag_from_file(db, id, key);
    }
    g_hash_table_remove(db->reverse, GINT_TO_POINTER(id));
}

void tagdb_remove_file(tagdb *db, int id)
{
    GHashTable *its_tags = g_hash_table_lookup(db->forward, GINT_TO_POINTER(id));
    if (its_tags == NULL)
    {
        return;
    }

    GHashTableIter it;
    gpointer key, value;
    g_hash_table_iter_init(&it, its_tags);
    if (g_hash_table_iter_next(&it, &key, &value))
    {
        tagdb_remove_file_from_tag(db, id, key);
    }
    g_hash_table_remove(db->forward, GINT_TO_POINTER(id));
}

Where only a few identifiers change, but basically the same thing happens, just on different sides. Is there a simpler, less error prone way to do this in c? Maybe with macros?