texts: Making a priority queue using a Heap. Without using queue or heapq

texts:
I have to implement a priority queue using a heap without any library / package for priority queue or heap. I made a BinHeap class which is a min heap, and I made a priority queue class with enqueque, dequeque methods that uses it. The priority queue class works fine but i'm not sure if the code its correct. Can you please help me?
Thanks

#class Min Heap
class BinHeap:
    #constructor
    def __init__(self):
        self.heapList = [0]     #heap can be represented as a list, initialize list [] = 0
        self.currentSize = 0    #initialize size = 0

    #swap last appended element with the parent or right child if needed, until (min) heap structure is mantained
    def percUp(self,currentSize):
        while currentSize // 2 > 0:
          if self.heapList[currentSize] < self.heapList[currentSize // 2]:                                                                      #if last appended elem < parent
             self.heapList[currentSize // 2], self.heapList[currentSize] = self.heapList[currentSize], self.heapList[currentSize // 2]          #swap them

          if self.heapList[currentSize] < self.heapList[currentSize-1]:                                                                         #if right child < left child
              self.heapList[currentSize], self.heapList[currentSize-1] = self.heapList[currentSize-1], self.heapList[currentSize]               #swap them

          currentSize = currentSize // 2                                                                                #continue to check until the root

    #insert node in the right place, if needed, swap with parent
    def insert(self,k):
      self.heapList.append(k)
      self.currentSize = self.currentSize + 1
      self.percUp(self.currentSize)

    #delete greater node
    def delMax(self):
        return self.heapList.pop()

#priority queque class
class priority_queque():
    def __init__(self):
        self.heap = BinHeap()

    def enqueque(self, val):
        self.heap.insert(val)

    def dequeque(self):
        self.heap.delMax()

    #print all pqueque
    def print(self):
        print(self.heap.heapList)

ci = priority_queque()
ci.enqueque(9)
ci.enqueque(5)
ci.enqueque(6)
ci.enqueque(2)
ci.enqueque(3)
ci.print()
ci.dequeque()
ci.print()

#output
#[0, 2, 3, 6, 5, 9]
#[0, 2, 3, 6, 5]


texts:
Apologies in advance for my english...
We have a list of categories and a list of doctors, you need to output as follows:

category1

item1
item2
item3

category2

item1
item2
item3

Here is what I was able to write:
function renderChatList() {
    let xhttp = new XMLHttpRequest();
    let categoriesArr = [];

    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        categoriesArr = JSON.parse(this.responseText);

        categoriesArr.forEach((category) => {
          getDoctorsGroup(category.id, category.title);
        });
      }
    };
    xhttp.open(
      "POST",
      "http://localhost/domen/api/readCategories.php",
      true
    );
    xhttp.send();
  }
  renderChatList();

  function getDoctorsGroup(id, title) {
    let xhttp = new XMLHttpRequest();
    let doctorsArr = [];

    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        doctorsArr = JSON.parse(this.responseText);
        let html = "";

        html += '
';
        html += '
';
        html += `<span class="text">${title}</span>`;
        html += '';
        html += '
';
        html += '
';
        doctorsArr.forEach(doctor => {
          if(doctor.category == id) {
            html += '
';
            html += '
';
            html += `<img src="images/dist/doctors/${doctor.avatar}" alt="${doctor.name}">`;
            html += '
';
            html += '
';
            html += `<h3 class="member-name truncate-text-item">${doctor.name}</h3>`;
            html += `<p class="member-job truncate-text-item">${doctor.job}</p>`;
            html += '
';
            html += '
';
          }
        })
        html += '
';
        html += '
';

        // Insert group into list
        const container = document.querySelector(".chat-list_members");
        container.insertAdjacentHTML("beforeend", html);

      }
    }
    xhttp.open(
      "POST",
      "http://localhost/domen/api/readDoctors.php",
      true
    );
    xhttp.send();
  }

is it possible to optimize the code, or improve?


texts:
Here's a small function to check if the property starts with [ or { and parse the value from a sting into JSON or an array. Properties might be a string or intiger also.

import { mapValues } from 'lodash'

export function resolveValues (data) {
  return mapValues(data, item => {
    if (item.match(/^\[/) || item.match(/^\{/)) return JSON.parse(item)
    return item
  })
}


texts: How can I enhance my linkedlist implementation in java?

texts:
I recently implemented Linked List on my own. I did not use generics as I am still learning. How can I improve it:

package datastructures;

class LinkedList
{
    Node head = null;
    Node tail = null;
    int size = 0;

    public void add(int data)
    {
        Node n = new Node();
        n.setElement(data);
        if(head == null){head = n; tail = n;}
        else
        {
            tail.setNext(n);
            tail = n;
        }
        size++;
    }

    public void size()
    {
        System.out.println("Size of the list is " + size);
    }

    public void addFront(int data)
    {
        Node n = new Node();
        n.setElement(data);

        if(head == null)    {   head = n; tail = n;   }
        else
        {
            n.setNext(head);
            head = n;
        }
        size++;
    }

    public void addLast(int data)
    {
        Node n = new Node();
        n.setElement(data);

        if(head == null){head = n; tail = n;}
        else
        {
            tail.setNext(n);
            tail = n;
        }
        size++;
    }

    public void removeFirst()
    {
        if(size==0){return ;}
        else
        {
            Node n = head.getNext();
            head = n;
        }
        size--;
    }

    public void removeLast()
    {
        if(size==0){return ;}
        else
        {
            Node tmp , prev = null;
            tmp = head;

        while(tmp != null)
        {
            if(tmp.getNext() == tail){prev = tmp;}
            tmp = tmp.getNext();
        }
            tail = prev;
            tail.setNext(null);
        }
        size--;
    }

    public void printList()
    {
        Node cNode = head;
        while(cNode != null)
        {
            System.out.println(cNode.getElement()+" ");
            cNode = cNode.getNext();
        }
        System.out.println("");
    }

    public static void main(String args[])
    {
        LinkedList l = new LinkedList();
        l.add(1);
        l.add(2);
        l.add(3);
        l.add(4);
        l.add(5);
        l.add(6);
        l.add(7);
        l.add(8);
        l.addLast(9);
        l.addFront(0);
        l.printList();

        System.out.println("Head Node is "+l.head.getElement());
        System.out.println("Tail Node is "+l.tail.getElement());
        l.size();

        System.out.println("\\\\\\\\\\\\\\\\Before removing the first element////////");
        System.out.println("");

        System.out.println("\\\\\\\\\\\\\\\\After removing the first element and removing the last element////////");
        System.out.println("");

        l.removeFirst();
        l.removeLast();
        l.printList();
        System.out.println("Head Node is "+l.head.getElement());
        System.out.println("Tail Node is "+l.tail.getElement());
        l.size();
    }

}
class Node
{
    int data;
    Node next;

    public void setElement(int data)
    {
        this.data = data;
    }

    public int getElement()
    {
        return data;
    }

    public Node getNext()
    {
            return next;
    }

    public void setNext(Node n)
    {
        this.next = n;
    }

}


texts: Hamburger menu with Javascript - clearing state

texts:
I wanted a menu that is always a hamburger, regardless of screen size. Plus it has to be activated by click, not hover.
Any comments / review will be appreciated.
Pls let me know if this is not worded properly / off topic etc.
Please see Codepen
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Sample website</title>
    <link rel="stylesheet" type="text/css" href="css/test.css">

 &#9776;

Menu 1

Menu 1-1

Menu 1-2

Menu 1-3

Menu 1-4

Menu 2

Menu 2-1

Menu 2-2

Menu 2-3

Menu 2-4

Menu 3

Menu 3-1

Menu 3-2

Menu 3-3

Menu 3-4

#menuBar > ul  {
    display: none;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 10em;

}

li {
    list-style-type:none;
    margin: 1px;
    padding: 1px;
}

li:first-child {
    background: grey;
    color: #fff;
}

li:not(:first-child) {
    display: none;
}

.menuHamburger {
    font-size: 2em;
}

function hideAllButFirstChild(parentId) {

    var children = document.getElementById(parentId).children;
    for (var i=0; i < children.length; i++) {

       if (children[i].style.display=='' || children[i].style.display=='none') {

       children[i].style.display="block";

       // but set its children to none?

       } else {

            // block all except first
            if (i != 0) { children[i].style.display="none"; }

        }

     }

}


texts: Reusable VBA macro to prevent Excel from destroying the data (+ backup capacity)

texts:
My goal is to prepare the Excel file (see the download link at the end) I would share with my non-technical colleagues, so that they enter some data into it and then I was able to automatically generate CSV without having to manually change format of dates, leading zeros and in other special cases (this CSV I will later use to test another app).

This is my first program in VBA. I understand I did a lot of stupid things, and I would love to be humiliated... But with reasons, so I can improve. I am happy that this implementation allows me to achieve my goal so far, but I think it might be unstable in case if my colleagues try harder (unconsciously) to break it.

In the code below I am trying to change all cells to text format, keeping their values as they are displayed and replacing all the empty cell values by - character "-". Also, I try to remove the duplicated double quotes which might appear.

Please, tell me, how would you improve it to preserve the behavior and make it more transparent? Would you use such tool and why?

Sub PrepareForCSV()

Call CreateBackup
Dim cell1 As Range
Set cell1 = ActiveWorkbook.ActiveSheet.UsedRange
'PART 1:
'Goal: to accomplish setup described here - https://stackoverflow.com/questions/165042/stop-excel-from-automatically-converting-certain-text-values-to-dates

For Each cell1 In cell1
'The check below would help, but it does not work because of Excel internal behaviour
' If (InStr(1, cell1.Value, "=") = 0) Then
'    'cell1.Value = "=" & cell1.Value
'    cell1.NumberFormat = "@"
'inserting - sign to avoid blank cells within UsedRange
'if the cell is empty and format is not text
If cell1.Value = "" And cell1.NumberFormat <> "@" Then
    cell1.Value = "=" & """" & "-" & """"
    cell1.NumberFormat = "@"
'if the cell is empty and format is text
ElseIf cell1.Value = "" And cell1.NumberFormat = "@" Then
    cell1.Value = "-"
    cell1.NumberFormat = "@"
'if the cell starts with double quote followed by = sign and format is not text
 ElseIf (InStr(1, cell1.Value, """=") = 0 And cell1.NumberFormat <> "@") Then
    cell1.Value = "=" & """" & cell1.Value & """"
    cell1.NumberFormat = "@"
'if the cell starts with double quote and format is not text
 ElseIf (InStr(1, cell1.Value, """") = 0 And cell1.NumberFormat <> "@") Then
    cell1.Value = "=" & """" & cell1.Value & """"
    cell1.NumberFormat = "@"
 Else
'probably the code bellow is not needed:
'    If cell1.Value <> "" Then
''        cell1.Value = "=" & """" & cell1.Value & """"
''        cell1.NumberFormat = "@"
'    Else
'        cell1.Value = "=" & """" & "-" & """"
'        cell1.NumberFormat = "@"
'    End If
 End If
Next

'PART 2: replace all unwanted characters
Dim fnd As Variant
Dim rplc As Variant
'replace characters which may cause errors when csv is imported
fnd = ":"
rplc = "!"
  ActiveWorkbook.ActiveSheet.Cells.Replace What:=fnd, Replacement:=rplc, _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
 'replace duplicated double quotes
  ActiveWorkbook.ActiveSheet.Cells.Replace What:="""""", Replacement:="""", _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
  'replace duplicated double quotes for the second time, in case if they are still there
  ActiveWorkbook.ActiveSheet.Cells.Replace What:="""""", Replacement:="""", _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
End Sub

The entire package for review and testing (I separated macros from XLSX for security reasons - you can merge them on your machine) - workbook with supporting macros, mainly backup-restore sheet capacity which allows to play with PrepareForCSV with ease leveraging the backup capacity - with all the credit to @aevanko for his answer https://stackoverflow.com/a/6993228/4778011


texts: Extract three letter pattern from a given list

texts:
The code takes a list of names and extracts the three letter pattern from the names. Then return the list of names as a value in the dictionary with key as a pattern.  The list name has a fixed naming pattern like three letter Spp in the example. It can extent like App, Bpp, Cpp etc..

How can I improve this code?

import sys
import re

def uniquelist(scaffold_names_list):
    unique_names = []
    for name in scaffold_names_list:
        pattern_name = re.search(r"[A-Z]{1}[a-z]{2}", name)
        unique_names.append(pattern_name.group())
    unique_names = list(set(unique_names))
    return unique_names

def uniquepattern(scaffold_names_list):
    unique_names = uniquelist(scaffold_names_list)
    dct = {}

    for singlepattern in unique_names:
        dct['%s' % singlepattern] = []

    for singelelist in scaffold_names_list:
            number = re.search(r"[A-Z]{1}[a-z]{2}", singelelist)
            number = number.group()

            for singlepattern in unique_names:
                if number == singlepattern:
                    dct[singlepattern].append(singelelist)

    return dct

scaffold_names_list = ['Spp1Aa1', 'Spp1Aa1', 'Spp2Aa1', 'Spp3Aa1', 'Spp4Aa1', 'Spp5Aa1']
patterns = uniquepattern(scaffold_names_list)
print(patterns)

{'Spp': ['Spp1Aa1', 'Spp1Aa1', 'Spp2Aa1', 'Spp3Aa1', 'Spp4Aa1', 'Spp5Aa1']}


texts:
I have a invoiceList which is a List<Map<String:String>> and am trying to find out if all the invoices have same SENDER_COUNTRY and CLIENT_COUNTRY or not. If not, it will add the message to a JSON array.

[
    [INVOICE_DATE:20150617, INVOICE_NUMBER:617151,SENDER_COUNTRY:USA, CLIENT_COUNTRY:USA]
    [INVOICE_DATE:20150617, INVOICE_NUMBER:617152,SENDER_COUNTRY:CAD, CLIENT_COUNTRY:MEX]
    [INVOICE_DATE:20150617, INVOICE_NUMBER:617153,SENDER_COUNTRY:CAD, CLIENT_COUNTRY:MEX]
]

JSONArray jsonArray = new JSONArray();
def senderCountry = invoiceList[0]['SENDER_COUNTRY']
def clientCountry  = invoiceList[0]['CLIENT_COUNTRY']
invoiceList.each{ it ->
if(it['SENDER_COUNTRY'] != senderCountry)
  jsonArray.add((new JSONObject()).put("SENDER_COUNTRY","Multiple sender Countries Associated"));
 if(it['CLIENT_COUNTRY'] != clientCountry)
  jsonArray.add((new JSONObject()).put("CLIENT_COUNTRY","Multiple Client Countries Associated"));
}

I feel this code can be refactored/optimized to a better version in Groovy. Can someone please help me with it?


texts: Message handling: Should a test/spec do it?

texts:
I am currently implementing an app that uses an architecture based on features & usecases and message sending.

Features are created with message handler passed in.
To test the feature, a handler intercepting the resulting message, must be passed in.

I came up with 2 solutions, both currently being present in the project's code:

use an object implementing the message handling protocol and offering a callback.

import Quick
import Nimble
@testable import LibExample

class Mock {
    class MessageHandler: MessageHandling {

       init(callBack: @escaping (Message) -> ()) {
            self.callBack = callBack
        }

        let callBack: (Message) -> ()

        func handle(msg: Message) {
            callBack(msg)
        }
    }
}

class SettingsFeatureSpec: QuickSpec {
    override func spec() {
        describe("the SettingsFeature UseCase") {
            var sut: SettingsFeature!

            var messageHandler: Mock.MessageHandler!
            var receivedModes: [TransportOption]!

            beforeEach {
                receivedModes = []
                messageHandler = Mock.MessageHandler {
                    if case .feature(.settings(.useCase(.transport(.action(.didActivate(let m)))))) = $0         {
                        receivedModes.append(m)
                    }
                }
                sut = SettingsFeature(with: messageHandler)
            }

            afterEach {
                receivedModes = nil
                messageHandler = nil
                sut = nil
            }

            it("switches transport modes") {
                sut.handle(feature: .settings(.useCase(.transport(.action(.activate(.udp))))))
                sut.handle(feature: .settings(.useCase(.transport(.action(.activate(.tcp))))))
                sut.handle(feature: .settings(.useCase(.transport(.action(.activate(.tls))))))
                sut.handle(feature: .settings(.useCase(.transport(.action(.activate(.udp))))))

                expect(receivedModes) == [.udp, .tcp, .tls, .udp]
            }
        }
    }
}

have the test/spec implement the the message handling

import Quick
import Nimble
@testable import LibExample

class UserHandlingSpec: QuickSpec, MessageHandling {

    var loggedInUser:User!
    var loggedOutUser:User!

    func handle(msg: Message) {
         switch msg {
        case .feature(.userHandling(.useCase(.login(.action(.logInConfirmed(let user)))))):
            self.loggedInUser = user
        case .feature(.userHandling(.useCase(.logout(.action(.logOutConfirmed(let user)))))):
            self.loggedOutUser = user
        default:
            break
        }
    }

    override func spec() {
        describe("the UserHandling Feature") {
            var sut: UserHandlingFeature!

            beforeEach {
                sut = UserHandlingFeature(with: self)
            }

            afterEach {
                sut = nil
                self.loggedOutUser = nil
                self.loggedInUser = nil
            }

            it("logs in user"){
                sut.handle(feature: .userHandling(.useCase(.login(.action(.logIn("pinky", "password"))))))

                expect(self.loggedInUser.name) == "pinky"
            }

            it("logs out user"){
                sut.handle(feature: .userHandling(.useCase(.logout(.action(.logOut(User(name:"the brain")))))))

                expect(self.loggedOutUser.name) == "the brain"
            }
        }
    }
}

Which one would be the preferred way and why?


texts:
I've implemented a command line todo list in Haskell. I've run hlint and build with -Wall, but is there anything else I can improve?

module Main where

import Control.Applicative ((<$>))
import Prelude.Unicode
import System.IO (IOMode(ReadMode, WriteMode), utf8, hClose, hGetContents, hPutStr, hSetEncoding, openFile)
import System.IO.Error (tryIOError)
import Text.Read (readMaybe)

type TodoList = [String]

options :: [(Char, String, Maybe (TodoList -> IO TodoList))]
options =
    [ ('c', "create new item", Just createItem)
    , ('d', "delete item", Just deleteItem)
    , ('x', "delete everything", Just . const $ return [])
    , ('l', "load file", Just loadFile)
    , ('s', "save to file", Just saveToFile)
    , ('q', "quit", Nothing)
    ]

main :: IO ()
main = do
    putStrLn "TODO-LIST\n"
    _ <- loop []
    return ()

loop :: TodoList -> IO TodoList
loop todos = do
    putStrLn "----------------------------"
    putStrLn "You have to do these things:"
    putStrLn ∘ unlines $ zipWith (\i e -> show i ++ ": " ++ show e) ([0..] :: [Integer]) todos
    input <- askForInput
    case filter (\(c, _, _) -> c == input) options of
        [(_, _, action)] -> case action of
            Nothing   -> return todos
            Just func -> func todos >>= loop
        _                -> putStrLn "action not found" >> loop todos

askForInput :: IO Char
askForInput = do
    putStrLn "Select an action"
    putStrLn ∘ unlines $ map (\(char, desc, _) -> char : ") " ++ desc) options
    line <- getLine
    case line of
        [c] -> return c
        _   -> askForInput

createItem :: TodoList -> IO TodoList
createItem todos = do
    putStrLn "enter a description of the new item:"
    (: todos) <$> getLine

deleteItem :: TodoList -> IO TodoList
deleteItem todos = do
    putStrLn "enter the number of the item you want to delete"
    line <- getLine
    case readMaybe line of
        Nothing -> deleteItem todos
        Just n  -> case removeAt n todos of
            Nothing  -> deleteItem todos
            Just val -> return val
    where
        removeAt :: Int -> [a] -> Maybe [a]
        removeAt n _ | n < 0 = Nothing
        removeAt _ []        = Nothing
        removeAt 0 (_:xs)    = Just xs
        removeAt n (x:xs)    = (x :) <$> removeAt (n-1) xs

loadFile :: TodoList -> IO TodoList
loadFile todos = do
    putStrLn "enter the file you want to load"
    line <- getLine
    eitherExOrFile <- tryIOError $ openFile line ReadMode
    case eitherExOrFile of
        Left _     -> loadFile todos
        Right file -> do
            hSetEncoding file utf8
            eitherExOrContents <- tryIOError $ hGetContents file
            case eitherExOrContents of
                Left _        -> loadFile todos
                Right content -> return (todos ++ lines content)

saveToFile :: TodoList -> IO TodoList
saveToFile todos = do
    putStrLn "enter the filename to save your todolist. The file will be overwritten."
    line <- getLine
    eitherExOrFile <- tryIOError $ openFile line WriteMode
    case eitherExOrFile of
        Left _     -> saveToFile todos
        Right file -> do
            hSetEncoding file utf8
            result <- tryIOError . hPutStr file $ unlines todos
            case result of
                Left _  -> putStrLn "couldn't write to file"
                Right _ -> hClose file
            return todos

I'm a little bit worried about the code duplication in readFile / saveToFile and the nested case of.


texts:
I've made this simple function for reading N bits from an unsigned char*  (with a possible offset) and I'm willing to share it here, get a review, suggestions for improving it, etc...

typedef struct bits_t {
    unsigned char *data;
    unsigned int len;
} bits_t;

bits_t *read_bits(unsigned char *src, int bits_offset, int nbits){

    unsigned int curr_bit, curr_byte, remaining_to_read, bit_position_in_byte;

    curr_bit = curr_byte = 0;
    remaining_to_read = nbits;

    bits_t *bits = malloc(sizeof(bits_t));

    bits->len = nbits;
    bits->data = calloc(1, bits->len);

    for(curr_bit = 1; curr_bit <= nbits; curr_bit++){
        if(curr_bit >= bits_offset && remaining_to_read){
            curr_byte = (curr_bit - 1) / 8;
            bit_position_in_byte = (curr_bit - 1) - (curr_byte * 8);
            bits->data[remaining_to_read - 1] = read_bit(src[curr_byte], bit_position_in_byte);
            remaining_to_read--;
        }
    }

    return bits;
}

Main:

unsigned char *x = "oo";
bits_t *bits = read_bits(x, 0, 16);
for(i = 0; i < bits->len; i++){
    printf("%d", bits->data[i]);
}

Result: 0110111101101111


texts: Code for saving / loading a class object

texts:
As I was advised, I broke my code into 2 classes. Could you take a look at the repository class and report what problems this code has

public class JsonSharedPreferences {
private static Gson gson = new Gson();
private Context context;

public JsonSharedPreferences(Context context) {
    this.context = context.getApplicationContext();
}

public <T> T loadObject(Class<T> classType, String key) {
    SharedPreferences settings = context.getSharedPreferences(key, Context.MODE_PRIVATE);
    String json = settings.getString(key, null);
    return gson.fromJson(json, classType);
}

    public <T> void saveObject(T objective, String key) {
        SharedPreferences settings = context.getSharedPreferences(key, Context.MODE_PRIVATE);
        String json = gson.toJson(objective);
        settings.edit().putString(key, json).apply();
    }
}


texts: Transform and transpose byte[] of 32bit image data in 24bit array image data

texts:
I would like to know if someone can think about a better solution for doing this stuff.

I have an array of raw bitmap data in 32bit format (RGBA). I need to transform and transpose this array into a 24bit format by eliminating the alpha component.

Additionally I need to transform the data by aligning the red component in the first part of the result array, the green in after the first 1/3 and the blue after the 2/3  because I'm doing a RLE compression after.

By doing this alignment, I have a better compression because there is more chance to have red, green and blue component alignment between pixels.

I'm using unsafe and fixed pointer to do that. I'm getting something like 11ms to process for a 8.3M array length. It seems to be low but I'm doing a realtime screengrabbing and every ms is counting.

(I bypass unsafe and fixed byte* stuff):

byte* actualpointeur = actual == (IntPtr)pd1 ? pd1 : pd2; // it s the pointer on my source 32bit array
// pd24b is a pointeur to my reception array at the right size...
byte* redindexp = pd24b;
byte* greenindexp = pd24b+(datain24format.Length / 3);
byte* blueindexp = pd24b+((datain24format.Length / 3) * 2);
for (int i = 0; i < datalenght; i += 4, actualpointeur+=4, redindexp++, greenindexp++, blueindexp++)
{
    *redindexp= *(actualpointeur);
    *greenindexp = *(actualpointeur+1);
    *blueindexp = *(actualpointeur+2);
}


texts: Python proper abstract class and subclassing with attributes and methods

texts:
The goal of the code below is to have an abstract base class that defines simple methods and attributes for the subclasses. This is part of an application that provides the code base for others to develop their own subclasses such that all methods and attributes are well implemented in a way for the main application to use them. The application shall never create more than one object of each subclass, since they are supposed to implement everything correctly to be called upon. Ideally, instantiating objects of the subclasses would not even be necessary, but is needed as it is in order to check if the abstract methods are implemented.

However, Python seems to be different and awkward when it comes to classes in comparison with other programming languages (initialization, attributes, properties), and I am not very sure if the solution below is the most appropriate. It seems too much complicated to achieve the aforementioned purpose. In addition, another function (not in the code below) must be made to properly check (make sure that they are of a certain type) the attributes of the subclasses.

Any thoughts?

from abc import ABC, abstractmethod

class abstract_attribute(object):
    """taken from http://stackoverflow.com/questions/32536176/how-to-define-lazy-variable-in-python-which-will-raise-notimplementederror-for-a/32536493#32536493"""
    def __get__(self, obj, type):
        # Now we will iterate over the names on the class,
        # and all its superclasses, and try to find the attribute
        # name for this descriptor
        # traverse the parents in the method resolution order
        for cls in type.__mro__:
            # for each cls thus, see what attributes they set
            for name, value in cls.__dict__.items():
                # we found ourselves here
                if value is self:
                    # if the property gets accessed as Child.variable,
                    # obj will be done. For this case
                    # If accessed as a_child.variable, the class Child is
                    # in the type, and a_child in the obj.
                    this_obj = obj if obj else type

                    raise NotImplementedError(
                         "%r does not have the attribute %r "
                         "(abstract from class %r)" %
                             (this_obj, name, cls.__name__))

        # we did not find a match, should be rare, but prepare for it
        raise NotImplementedError(
            "%s does not set the abstract attribute <unknown>", type.__name__)

class Base(ABC):
    # attr1 and attr2 must be properly (be of a certain type) implemented by subclasses
    # abstract_attribute() checks if the attribute is present in the subclass
    attr1 = abstract_attribute()
    attr2 = abstract_attribute()

    @abstractmethod
    def method():
        pass

    # a class property that does not change from instance to instance
    @property
    def prop(self):
        return self.prop
    @prop.setter
    @classmethod
    def prop(self, prop):
        self.prop = prop

class Sub(Base):
    # attr1 and attr2 must be implemented otherwise and exception is thrown upon accessing them
    attr1 = something
    attr2 = somethingElse
    # method must be implemented otherwise an exception is thrown upon instantiation
    def method():
        print("must be implemented by subclasses")


texts:
I am quite new to Java and I wanted to try and make a smoking calculator that tells the user how much they would save over a certain time period. I would appreciate if someone could tell me where they would improve my code and what other features they would add?

Should I always use objects when coding in java even for a basic program like this one?

import java.util.Scanner;

public class Calculator {
    public static void main(String args[]) {

        Scanner scan = new Scanner(System.in);

        //Packets
        System.out.println("How many packets do you smoke a week?");
        double packets = scan.nextDouble();

        //cost
        System.out.println("How much is each packet?");
        double cost = scan.nextDouble();

        //weekly
        double weekly;
        weekly = (cost*packets);
        System.out.println("In one week you would save: €" + weekly);

        //monthly
        double monthly;
        monthly = (weekly*4);
        System.out.println("In one month you would save: €" + monthly);

        //threeMonths
        double threeMonths;
        threeMonths = (weekly*12);
        System.out.println("In three months you would save: €" + threeMonths);

        //sixMonths
        double sixMonths;
        sixMonths = (weekly*26);
        System.out.println("In six months you would save: €" + sixMonths);

        //yearly
        double yearly;
        yearly = (weekly*52);
        System.out.println("In one year you would save: €" + yearly);

        //user input
        System.out.println("Enter a number of years and see how much you will save over that time period...");
        double user = scan.nextDouble();
        double userInput;
        userInput = (yearly*user);
        System.out.println("You would save €" + userInput + " in " + user + " years.");

          scan.close();
    }
}


texts:
In this program I was required to calculate the Harmonic Average using an assembly program with a C driver.

Harmonic mean is defined as:

$$ \frac{n}{\dfrac{1}{x_1} + \dfrac{1}{x_2} + \cdots + \dfrac{1}{x_n}}$$

where \$n = \$ number of inputs and \$x_i = \$ a real number.

I would like to know if:

My code follows common practices.
My code is formatted correctly.
If comments need to be improved.
My code is straightforward; that is, I have achieved the goal with the least amount of work.
There any improvements I should make in my code.

Attached below is my program in Assembly:

;Assembly function that computs the harmonic mean
;of an array of 64-bit floating-point numbers.
;Retrieves input using a C program.
;
;Harmonic mean is defined as Sum(n/((1/x1) + (1/x2) + ... + (1/xn)))
;
;   expects:
;       RDI - address of array
;       RSI - length of the array
;   returns
;       XMMO - the harmonic average of array's values

global harmonicMean

section .data
    Zero dd 0.0
    One dd 1.0

section .text
    harmonicMean:
        push rbp
        mov rbp, rsp              ;C prologue

        movss xmm10, [Zero]       ;Holds tally of denominator
        cvtsi2ss xmm0, rsi        ;Take length and put it into xmm0 register

        .whileLoop:
            cmp rsi, 0            ;Is the length of array 0?
            je .endwhile
            call addDen           ;Compute a denominator value and add it to sum
            add rdi, 4            ;Add size of float to address
            dec rsi               ;Decrease the length
            jmp .whileLoop
        .endwhile:

        divss xmm0, xmm10

        leave
        ret

    ;Calculates a number in the denominator
    addDen:
        push rdi
        movss xmm8, [One]
        movss xmm9, [rdi]
        divss xmm8, xmm9
        addss xmm10, xmm8
        pop rdi
        ret


texts:
Looking for style and speed review

π PI
An estimate is \$\frac{4}{1} - \frac{4}{3} + \frac{4}{5} - \frac{4}{7} + \frac{4}{9} - \frac{4}{11} + \frac{4}{13} - \frac{4}{15} + \frac{4}{17} \$...

The average of the last two is the current best estimate

Is the estimate correct to a certain number of digits

The answer has to be between the + and - or the algorithm would just be wrong

Have to worry about rounding error so I just don't report last 3 digits

Test

decimal pi;
sw.Restart();
int count = 4;
foreach (decimal d in PI4b(24))
{
    Console.WriteLine("ms {0}  digits {1}",  sw.ElapsedMilliseconds.ToString("N0"), count);
    Console.WriteLine(d);
    Console.WriteLine("");
    count++;

}

Code

public static IEnumerable<decimal> PI4b(int digits)
{
    if (digits < 4)
    {
        digits = 4;
    }
    else if (digits > 24)
    {
        digits = 24;
    }

    decimal piAcual = 3.1415926535897932384626433832m;  // 28 after decimal
    Decimal pi = 4m, iteration = 3m, piAvg = 0m;
    Decimal piLast = 10000m;
    int match = 0;
    int matchMax = 10000;
    for (int curDigits = 4; curDigits <= digits; curDigits++)
    {
        do
        {
            piLast = piAvg;
            pi -= 4m / iteration;
            piAvg = pi;
            iteration += 2m;
            pi += 4m / iteration;
            piAvg = (pi + piAvg) / 2m;
            iteration += 2m;
            if (Decimal.Round(piAvg, curDigits + 2) == Decimal.Round(piLast, curDigits + 2))
            {
                match++;
            }
            else
            {
                if (matchMax < match)
                {
                    matchMax = match;
                }
                match = 0;
            }
        } while (match < 2 * matchMax);
        if (Decimal.Round(piAvg, curDigits) != Decimal.Round(piAcual, curDigits))
        {
            Debug.WriteLine(Decimal.Round(piAcual, curDigits));
            Debug.WriteLine(Decimal.Round(piAvg, curDigits));
            throw new Exception("wrong answer");
        }
        match = 0;
        yield return Decimal.Round(piAvg, curDigits);
    }
}


texts:
For fun, I made a function queue in JavaScript.  I named it tinyq.  You can add functions to it, and each function is passed the next function in the queue.  You can also pass parameters to the functions, and they can return values.

function q(){
    var Q = [], t = this;
    this.length = 0;
    this.add = function (f){
        Q.push(f);
        this.length++;
    };
    this.run = function(){
        var n = Q.shift();
        this.length = Q.length;
        if(typeof n === 'function'){
            var a = Array.prototype.slice;
            return n.apply(window,[function(){
                return t.run.apply(t, a.call(arguments));
            }].concat(a.call(arguments)));
        }
    };
}

Here's a simple example of its use.

var Q = new q;
Q.add(function(next, A, B){
    return A + ": "+ next(B);
});
Q.add(function(next, C){
    return C + "123";
});
console.log(Q.length); // 2
console.log(Q.run("Test", "ABC")); // "Test: ABC123"

So, what do you think of my function queue?  Any improvements, or anything I'm doing wrong?

P.S. I was also trying to make this small, any suggestions on making it smaller?


texts:
I wrote Ruby code (copied below) but was told that the code does not compile (it does on my computer) and that it does not answer the question:

  Create a class called Scrabble that implements a method called score that accepts one word as a parameter and returns the scrabble score associated with that word

The code compiles on my computer and provides the response that I believe was required.  Can anyone point out issues with the code quality? I realize I did not write any unit tests for this code.

I could add more inline comments in the code (I added comments at the top of the class which I removed from the code I copied here).

class Scrabble

  attr_reader :word

  def initialize(word)
    @word = word
  end

  def score
    letters = word.upcase.split('')

    total = 0
    letters.each do |letter|
      total += letter_scores[letter]
    end

    total
  end

# scores for each letter
  def letter_scores
    {  "A"=>1, "B"=>3, "C"=>3, "D"=>2,
      "E"=>1, "F"=>4, "G"=>2, "H"=>4,
      "I"=>1, "J"=>8, "K"=>5, "L"=>1,
      "M"=>3, "N"=>1, "O"=>1, "P"=>3,
      "Q"=>10, "R"=>1, "S"=>1, "T"=>1,
      "U"=>1, "V"=>4, "W"=>4, "X"=>8,
      "Y"=>4, "Z"=>10
    }
  end
end

puts "Type in one word for scrabble scorer"
word = gets.chomp
puts "Scrabble score for " + word + " is " + Scrabble.new(word).score.to_s


texts: React Text Highlighter HOC in TypeScript

texts:
I'm shifting my focus towards frontend as much as I can, but I'm still quite unsure if I'm writing good code or not. Please take a look

import * as React from 'react'
import { remove as removeDiacritics } from 'diacritics'

export interface HighlighterProps {
   text: string,
   highlight: string,
}

export interface HighlighterState {
   highlightedText?: string
}

const withHighlighting = <T extends HighlighterProps> (WrappedComponent: React.ComponentType<T>) => {

return class Highlightable extends React.Component<T, HighlighterState> {

    constructor(props: any) {
        super(props)
        this.componentDidMount = this.componentDidMount.bind(this)
        this.componentWillReceiveProps = this.componentWillReceiveProps.bind(this)
        this.state = {
            highlightedText: ''
        }
    }

    componentDidMount() {
        const { text, highlight } = this.props
        this.updateHighlightTextAsState({text, highlight})
    }

    componentWillReceiveProps(nextProps: any) {
        this.updateHighlightTextAsState(nextProps)
    }

    updateHighlightTextAsState = ({ text, highlight }) => {
        const highlightedText = this.createHighlightedText(text, highlight)
        this.setState({ highlightedText })
    }

    createRegexp = (searchParts: string[]) => {
        return new RegExp(searchParts.join('|'), 'gui')
    }

    createHtml = (regexp, htmlText) => {
        let unified = removeDiacritics(htmlText)
        let replaceData = []
        unified.replace(regexp, (val, offset) => {
            replaceData.unshift([val, offset])
            return replaceData.join()
        })

        for (let [val, offset] of replaceData) {
            htmlText = `${htmlText.substr(0, offset)}` +
                `<span style="font-weight:bold">${htmlText.substr(offset, val.length)}</span>` +
                `${htmlText.substr(offset + val.length)}`
        }
        return htmlText
    }

    createHighlightedText = (text, highlight) => {
        const highlightList = highlight.split(/\s+/g)
        if (highlightList.length > 0) {
            text = this.createHtml(this.createRegexp(highlightList.map(removeDiacritics)), text)
        }
        return text
    }

    render() {
        const value = this.state.highlightedText
        return <WrappedComponent {...this.props} text={value} />
    }
  }
}
export default withHighlighting

And some tests:

import React from 'react'
import { shallow, mount } from 'enzyme'
import withHighlighting from '../src/withHighlighting'

let HighlightableMockComponent
let wrapper

beforeEach(() => {
    HighlightableMockComponent = ({text, highlight}) => <div>{text}</div>
    const HighLighterComponent = withHighlighting(HighlightableMockComponent)
    wrapper = mount(<HighLighterComponent text="I would like to highlight" highlight="like" />)
})

it('should contain a highlight', () => {
    expect(wrapper.text()).toContain("span")
})

it('should place the highlight inside the wrapped component', () => {
    expect(wrapper.find('div')).toHaveLength(1)
})

it('should match snapshot', () => {
    expect(wrapper).toMatchSnapshot()
})

it('should not highlight anything in case of unmatched words', () => {
    const HighLighterComponent = withHighlighting(HighlightableMockComponent)
    wrapper = mount(<HighLighterComponent text="apple" highlight="text" />)
    expect(wrapper.text()).not.toContain('span')
})


texts:
I am quite new to Java, and I am trying to read a file into a string (or should I use byte arrays for this?). File can be anything, such as a text file or executable file etc. I will compress what I read and write it to another file.

I am thinking of using this code:

public static String readFile(File f) {
    StringBuilder sb = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new FileReader(f))) {
        String sCurrentLine;
        while ((sCurrentLine = br.readLine()) != null) {
            sb.append(sCurrentLine);
        }

    } catch (IOException e) {
        System.err.println("I/O Exception:" + e.getMessage());
        return null;
    }
    return sb.toString();
}

Does this look good to you? I was reading "Reading and writing text files" and I was a little bit confused over all the different ways one can use to read files.


texts: Shortening JPA criteria query boilerplate

texts:
I've used hibernate for a long time. Recently I started using JPA, but I can't find a short way to write a simple select in less than these seven lines (the use of criteria is a must in this project).

Is there a shorter way to build this query?

public List<Transaction> findDevolucionesByOriginalOperationId(String originalOperationId) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Transaction> cq = cb.createQuery(Transaction.class);
    Root<Transaction> root = cq.from(Transaction.class);
    Collection<Predicate>  predicates = new ArrayList<Predicate>();

    predicates.add(cb.equal(root.get("originalOperationId"), originalOperationId));

    cq.where(predicates.toArray(new Predicate[predicates.size()]));
    List<Transaction> resultado = em.createQuery(cq).getResultList();
    return resultado;
}


texts:
I'm learning PHP now, and I'm trying to find out whether or not the following code structure has any faults:

$loggedIn = false;
if (isset($_GET["userpass"])){
    if (strcmp($_GET["userpass"], $correctPassword) == 0) {
        $loggedIn = true;
    }
}

To me, it seems pretty bullet-proof. If the password isn't set, then the code doesn't execute. And if it is, then the user actually has to supply the correct password. Anything obvious I'm missing?

Note:
$correctPassword is defined in an external file, not accesible to the public

Update:
Can the user of this website explit the script so that he can log in to any arbitrary account? As in, this piece of code always sets $loggedIn = true;


texts:
I'm working on a network monitoring application, that pings an unknown number of hosts. I've made a class PingHost with a function zping and I called it with the help of a timer once every 2 seconds to let the 2 pings to finish, even if one of them gets TimedOut. But I think a better solution is to generate a new thread for every ping, so that the ping of every host would be independent.

Can anyone give me a hint how to do this?

namespace pinguin
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            PingHost caca = new PingHost();
            PingHost caca1 = new PingHost();
            this.label1.Text = caca.zping("89.115.14.160");
            this.label2.Text = caca1.zping("89.115.14.129");
        }

    }

    public class PingHost
    {
        public string zping(string dest)
        {
            Application.DoEvents();
            Ping sender = new Ping();
            PingOptions options = new PingOptions();
            options.DontFragment = true;

            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 50;
            int failed = 0;
            int pingAmount = 5;
            string stat = "";
            PingReply reply = sender.Send(dest, timeout, buffer, options);
            if (reply.Status == IPStatus.Success)
            {
                stat = "ok";
            }
            else
            {
                stat = "not ok!";
            }
            return stat;
        }
    }
}


texts: VSTO Write Dictionary To Range Extension Method

texts:
I was hoping to receive some criticism on this block of code. I wrote it to write the contents of a dictionary to excel range in VSTO. It works well. I am interested to see how people could improve it.  What would you do differently to make it more expressive, efficient?

public static void WriteToRange(this Dictionary<string, object[]> DicToRange, excel.Range toRange)
    {
       object[,] storeDictionaryData = new object[DicToRange.Max(maxValues=> maxValues.Value.Length),DicToRange.Count];

       int keyCounter=0;
       int valueCounter =0;

       foreach (var key in DicToRange.Keys)
       {
         if (keyCounter < storeDictionaryData.GetLength(1))
           {
               foreach (var value in DicToRange[key])
               {
                   if (valueCounter < storeDictionaryData.GetLength(0))
                   {
                       storeDictionaryData[valueCounter, keyCounter] = value;
                       valueCounter++;
                   }
               }

               keyCounter++;
               valueCounter = 0;
           }
       }

       dynamic rangeToFill=toRange.get_Resize(storeDictionaryData.GetLength(0), storeDictionaryData.GetLength(1));
       rangeToFill.Value = storeDictionaryData;
    }


texts: Return timeframes relevant to just-elapsed time period (financial/trading context)

texts:
I am writing trading software, and have written this utility function. Its purpose is to return a list of timeframes relevant to the just-elapsed time period. "Timeframe" here means bar or candle period.

E.g if time has just struck UTC 10:30am, the returned list will contain "1m", "3m", "5m", "m15" and "30m" strings, as those are the candles or bars that have just closed.

The first minute of a new day or week will add daily/weekly/monthly timeframe strings.

Timeframes in use are 1, 3, 5, 15 and 30 mins, 1, 2, 3, 4, 6, 8 and 12 hours, 1, 2 and 3 days, as well as weekly and monthly.

Is there a more elegant, less verbose way to achieve this?

Note: the output could also be integers instead of strings, where each timeframe is expressed as its total number of minutes.

def get_timeframes(self):
    timestamp = datetime.datetime.utcnow()
    timeframes = ["1m"]

    # 3 minute bars
    for x in range(0, 20):
        val = x * 3
        if timestamp.minute == val:
            timeframes.append("3m")

    # 5 minute bars
    for x in range(0, 12):
        val = x * 5
        if timestamp.minute == val:
            timeframes.append("5m")

    # 15 minute bars
    for x in range(0, 4):
        val = x * 15
        if timestamp.minute == val:
            timeframes.append("15m")

    # 30 minute bars
    for x in range(0, 2):
        val = x * 30
        if timestamp.minute == val:
            timeframes.append("30m")

    # 1 hour bars
    if timestamp.minute == 0:
        timeframes.append("1h")

    # 2 hour bars
    if timestamp.minute == 0 & timestamp.hour % 2 == 0:
        timeframes.append("2h")

    # 3 hour bars
    if timestamp.minute == 0 & timestamp.hour % 3 == 0:
        timeframes.append("3h")

    # 4 hour bars
    if timestamp.minute == 0 & timestamp.hour % 4 == 0:
        timeframes.append("4h")

    # 6 hour bars
    if timestamp.minute == 0 & timestamp.hour % 6 == 0:
        timeframes.append("6h")

    # 8 hour bars
    if timestamp.minute == 0 & timestamp.hour % 8 == 0:
        timeframes.append("8h")

    # 12 hour bars
    if timestamp.minute == 0 & timestamp.hour % 12 == 0:
        timeframes.append("12h")

    # 1 day bars
    if timestamp.minute == 0 & timestamp.hour == 0:
        timeframes.append("1d")

    # 2 day bars
    if (
        timestamp.minute == 0 & timestamp.hour == 0 &
            timestamp.day % 2 == 0):
                timeframes.append("2d")

    # 3 day bars
    if (
        timestamp.minute == 0 & timestamp.hour == 0 &
            timestamp.day % 3 == 0):
                timeframes.append("3d")

    # weekly bars
    if (
        timestamp.minute == 0 & timestamp.hour == 0 &
            calendar.day_name[date.today().weekday()] == "Monday"):
                timeframes.append("1w")

    return timeframes


texts: Using view for repeated subquery on a large table

texts:
I have a large table with which I need to do some analysis. The table is a log of IPs:

+-------------+---------------------+------+-----+---------+-------+
| Field       | Type                | Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+-------+
| src         | int(10) unsigned    | NO   | PRI | 0       |       |
| dst         | int(10) unsigned    | NO   | PRI | 0       |       |
| packets     | int(10) unsigned    | YES  |     | NULL    |       |
| bytes       | int(16) unsigned    | YES  |     | NULL    |       |
| capturedate | int(10) unsigned    | NO   | PRI | 0       |       |
+-------------+---------------------+------+-----+---------+-------+

Every hour the past hours, IP activity is collected. The time this happens is capturedate. At that time each IP pairing (unique source to destination) is stored along with the number of packets and bytes sent from source to destination.

I've written some code for a webpage that queries the database to get a "vertex cover". It collects all the IP pairings and displays each IP and how many other unique IPs it has communicated with.

ip | verticies
123.234.12.34 | 567
234.56.78.91 | 234

So, IP '123.234.12.34' has communicated with 567 other unique IPs (as either source or destination). With millions of records in this table efficiency is an issue.

My solution is this:

First I added a view for a subquery I would reuse:

CREATE VIEW pair AS SELECT src, dst FROM iplogs GROUP BY src, dst;

Then the actual query is...

SELECT INET_NTOA(ip) AS ip, SUM(verts) as verticies
FROM (SELECT src AS ip, COUNT(src) AS verts FROM pair GROUP BY src
UNION ALL
SELECT dst AS ip, COUNT(dst) AS verts FROM pair GROUP BY dst) B
GROUP BY ip;

Is this the most efficient way to get the results? Will the "pair" view update every time the query is made? Will "pair" be queried once or twice?


texts: How best to differentiate boolean values in a long list?

texts:
I have a large C# Dictionary of string keys and boolean values. Background on the reason for it is this: my program builds up a bunch of the same objects from two different sources, and then compares all the properties to see if there are any disparates. But I want to ignore the differences where I know one source hasn't exposed that property for comparison, so I have this array that lists the properties that are actually 'gathered'.

Then when filtering the differences before user display, I ask if(!gathered[prop]) and remove it in that case. It would throw an exception if I hadn't defined a case for the property, and I don't want to ignore that as it may just mean I neglected to specify if it was or wasn't gathered.

    public Dictionary<string, bool> TPORGatheredData = new Dictionary<string,bool>()
    {
        // Represents fields that are actually retrieved from TP data
        { "Reference", true },
        { "Title", true },
        { "Status", true },
        { "Status.State", true },
        { "OriginatorName", true },
        { "InvestigatorName", true },
        { "ManagerName", true },
        { "ObservedOn", true },
        { "RaisedOn", true },
        { "ClosedOn", true },
        { "Project", true },
        { "VariantObservedOn", true },
        { "SoftwareVersionObserved", true },
        { "AreaObservedOn", true },
        { "StageObservedOn", true },
        { "VariantAppliedTo", true },
        { "AreaAppliedTo", true },
        { "FaultClassification", true },
        { "Type", true },
        { "SecurityClassification", true },
        { "CommercialClassification", true },
        { "SecurityGroup", true },
        { "SafetyRelated", true },
        { "Description", false },
        { "Recommendations", true },
        { "Recommendations.PointNumber", true },
        { "Recommendations.Id", true },
        { "Recommendations.Type", true },
        { "Recommendations.RecommendationText", true },
        { "ClosureText", true },
    };

The problem with this is that the value of false is quite significant. How could I differentiate the false from the true here?

Two options I can think of:

I could tab align all the values but this looks ugly as the farthest extent they need to go for alignment is a bit too far to easily see which value is for which key.
assume if there's no key then the value is true (although that depends on the context making this a suitable option, and as it stands in my case not having the value may be an indicator of a field that needs checking to see if it is or isn't handled).


texts:
I'm learning Go and I wrote this for a programming challenge. It is working (building and running) but I feel the code is not what Go code should be:

The code implements the steps a podracer takes to race over a 2D map. I input a target and a speed, and the code calculate where the pod will be at the end of the turn : rotating to point toward the target & moving (counting in previous speed).

In the playTurn() method below, I call each step. I reassign results (else they are not taken into account) because of scope I think.

It feels wrong for OOP code to have to reassign each step answer to the pod's attribute. What am i missing ?

Code :

package main

import (
    "fmt"
    "math"
    "os"
    "strconv"
)
// Dot is king
type Dot struct {
    x, y int
}
// Pod is life
type Pod struct {
    position                Dot
    vx, vy, angle, nextCpID int
    hasShieldOn             bool
}

func squaredDist(a, b Dot) int {
    return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)
}
func distance(a, b Dot) float64 {
    return math.Sqrt(float64(squaredDist(a, b)))
}

func (pod Pod) getAngle(p Dot) float64 {
    d := distance(p, pod.position)
    dx := float64(p.x-pod.position.x) / d
    dy := float64(p.y-pod.position.y) / d
    a := math.Acos(dx) * 180.0 / math.Pi

    // If the point I want is below me, I have to shift the angle for it to be correct
    if dy < 0 {
        a = 360.0 - a
    }
    return a
}

func (pod Pod) diffAngle(p Dot) float64 {
    a := pod.getAngle(p)
    pangle := float64(pod.angle)

    right := 0.0
    if pangle <= a {
        right = a - pangle
    } else {
        right = 360.0 - pangle + a
    }

    left := 0.0
    if pangle >= a {
        left = pangle - a
    } else {
        left = pangle + 360.0 - a
    }

    if right < left {
        return right
    }
    return -left
}

func (pod Pod) rotate(p Dot) int {
    a := pod.diffAngle(p)

    // Can't turn more than 18° in one turn !
    if a > 18.0 {
        a = 18.0
    } else if a < -18.0 {
        a = -18.0
    }

    pod.angle += int(math.Round(a))

    if pod.angle >= 360.0 {
        pod.angle = pod.angle - 360.0
    } else if pod.angle < 0.0 {
        pod.angle += 360.0
    }
    return pod.angle
}

func (pod Pod) boost(t int) (int, int) {
    if pod.hasShieldOn {
        return pod.vx, pod.vy
    }
    pangle := float64(pod.angle)
    pod.vx += int(math.Round(math.Cos(pangle) * float64(t)))
    pod.vy += int(math.Round(math.Sin(pangle) * float64(t)))
    return pod.vx, pod.vy
}

// t shoud become a float later on
func (pod Pod) move(t int) (int, int) {
    pod.position.x += pod.vx * t
    pod.position.y += pod.vy * t
    return pod.position.x, pod.position.y
}

func (pod Pod) endTurn() (int, int) {
    // todo rounding position if needed
    pod.vx = int(float64(pod.vx) * 0.85)
    pod.vy = int(float64(pod.vy) * 0.85)
    return pod.vx, pod.vy
}

func (pod Pod) playTurn(p Dot, t int) {
    pod.angle = pod.rotate(p)
    pod.vx, pod.vy = pod.boost(t)
    pod.position.x, pod.position.y = pod.move(1)
    pod.vx, pod.vy = pod.endTurn()
    fmt.Fprintf(os.Stderr, "\nPredicted Pod position : ")
    fmt.Fprintf(os.Stderr, "\n(%d, %d) speed (%d,%d)", pod.position.x, pod.position.y, pod.vx, pod.vy)
}


texts:
Just curious if my authentication is secure enough, really. Also wondering if I should ditch the secret variable and just use password everywhere instead.

Note: the method logic must remain seperated because the same User object will have CRUD methods added at a later date.

The table structure:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `secret` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

The class:

class User {
    public $db;
    public $id;
    public $username;
    public $password;
    public $secret;
    public $signed_in = false;

    function __construct ($db) {
        $this->db = $db;
    }

    function redirect ($url) {
        header('Location: '.$url);
        die();
    }

    function exists () {
        $sql = "select * from `users` where `username`=:username";
        $stm = $this->db->prepare($sql);
        $stm->bindParam(':username', $_POST['username']);
        $stm->execute();
        $res = $stm->fetch();

        if (!empty($res['password'])) {
            if (password_verify($_POST['password'], $res['password'])) {
                $this->id = $res['id'];
                $this->username = $res['username'];
                return true;
            }
        }

        return false;
    }

    function signIn () {
        $this->secret = password_hash($_POST['password'], PASSWORD_DEFAULT);

        if ($_POST['remember']) {
            setcookie('username', $this->username, time() + 31556926, '/');
            setcookie('secret', $this->secret, time() + 31556926, '/');
        }
        $_SESSION['username'] = $this->username;
        $_SESSION['secret'] = $this->secret;

        $sql = "update `users` set `secret`=:secret where `id`=:id";
        $stm = $this->db->prepare($sql);
        $stm->bindParam(':secret', $this->secret);
        $stm->bindParam(':id', $this->id);
        $stm->execute();
    }

    function signedIn () {
        if (!empty($_COOKIE['username'])) {
            $this->username = $_COOKIE['username'];
            $this->secret = $_COOKIE['secret'];
        }
        else if (!empty($_SESSION['username'])) {
            $this->username = $_SESSION['username'];
            $this->secret = $_SESSION['secret'];
        }

        $sql = "select * from `users` where `username`=:username and `secret`=:secret";
        $stm = $this->db->prepare($sql);
        $stm->bindParam(':username', $this->username);
        $stm->bindParam(':secret', $this->secret);
        $stm->execute();
        $res = $stm->fetch();

        if ($res) {
            array_walk_recursive($res, 'sanitize');
            foreach ($res as $k => $v) {
                if (property_exists($this, $k)) {
                    $this->$k = $v;
                }
            }
            $this->signed_in = true;
        }
    }
}

How the class is used at the top of all pages in the app:

$user = new User($db); // create user object, $db is a PDO object
$user->signedIn(); // determine if they're signed in, populate $user->signed_in boolean

Signing the user in via a form:

if (isset($_POST['username'])) {
    if ($user->exists()) {
        $user->signIn();
        $user->redirect('dashboard.php');
    }
}

Any feedback is greatly appreciated. Like I said my primary concern here is security.


texts: All combinations of a string with special characters

texts:
I have written a function which generates combinations of string by replacing 1 or more characters by the symbol "*".

The code is as follows:

/**
        this following code is responsible to generate all possible combiantions of letters from a
        word with *
        for eg. word = "fin",
        wordSet --> {fin, fi*, f**, f*n, **n, ***,*in}

*/
public static void generateCombinations(Set<String> words){

        Set<String> wordSet = new HashSet<>();

        for (String word : words){

            StringBuilder asterisk = new StringBuilder("*");

            while (asterisk.length() != word.length()){

                int startIndex = 0;
                while (startIndex + asterisk.length() < word.length()) {
                    String tempWord = word.substring(0, startIndex)
                            + asterisk.toString()
                            + word.substring(startIndex +  asterisk.length());
                    wordSet.add(tempWord);
                    startIndex ++;
                }
                wordSet.add(word.substring(0, Math.abs(startIndex - asterisk.length()+1 ))+ asterisk.toString() );

                //loop condition incrementor
                asterisk.append("*");
            }
            //all *'s
            wordSet.add(asterisk.toString());
            //no *
            wordSet.add(word);
        }
        //System.out.println(wordSet);

    }

However, I think this is a highly inefficient code as I need to do the same operation for all the words in the given Set of words(Set<String> words).

Is there any faster way to generate the same result? Any improvements in the current function to enhance speed and readability?


texts: Update Virtual Property in a Code First Model using Independent Association in Entity Framework 6

texts:
I have a Model that looks like this:

public class Item
{
    public Item()
    {
        FilePaths = new List<ItemFilePath>();
    }

    public int Id { get; set; }

    public virtual ICollection<ItemFilePath> FilePaths { get; set; }
}

public class ItemFilePath
{
    public int Id { get; set; }

    public virtual Item Item { get; set; }
}

I have generated Post and Put methods in Web API 2 from this Model. The Post works as intended, however the Put method have given me a lot of trouble. The standard Put method basically just does this:

public IHttpActionResult PutItem(int id, Item item)
{
    db.Entry(item).State = EntityState.Modified;
}

This saves the Item object, but any added or deleted FilePaths are not saved. Therefore by following this and this I came up with a solution that looks almost identical to that answer:

public IHttpActionResult Put(int id, Item item)
{
    var oldItem = db.Items.Find(item.Id);
    db.Entry(oldItem).Collection(b => b.FilePaths).Load();

    var deletedFilePaths = oldItem.FilePaths.ExceptBy(item.FilePaths, x => x.FilePath).ToList();
    foreach (var filePath in deletedFilePaths)
    {
        oldItem.FilePaths.Remove(filePath);
        db.ItemFilePaths.Remove(filePath);
    }

    var addedFilePaths = item.FilePaths.ExceptBy(oldItem.FilePaths, x => x.FilePath).ToList();
    foreach (var filePath in addedFilePaths)
    {
        oldItem.FilePaths.Add(filePath);
    }

    var itemEntry = db.Entry(oldItem);
    itemEntry.CurrentValues.SetValues(item);

    db.SaveChanges();
}

This is working as intended. However I can't shake the feeling that this is overly complex for something I would expect EF to be able to do automatically. I mean this is a very simple One-To-Many relationship, and I expect we will soon be facing Objects that have more Virtual Properties, and those themselves have Virtual Properties and what then?

So my question is, is this really the best way to go about updating Virtual Properties? Or am I missing something obvious or is there something wrong with my assumption that EF should be able to handle this automatically?


texts: Counting penalties for each player by joining tables, where some of the data is null

texts:
I have a table full of player names:

I also have a table full of player penalties:

I have to list all of the players names, player numbers, and the number of penalties that they've incurred.

To do that, I'm using this code:

select players.playerno, name, ifnull(`Penalty count`, 0) as `Penalty count` from players
left join
(select players.playerno, count(players.playerno) as `Penalty count` from players, penalties
where players.playerno = penalties.playerno
group by players.playerno) as `query1`
on players.playerno = query1.playerno
order by playerno

The code works. Here's the output table:

It seems like a lot of code just to merge two tables together. Is there a better way to do it?

I've also read online that keeping the NULL is generally a better practice than changing it to zero, but would that apply in this case, since it's supposed to be the total number of penalties? It seems like NULL would give the impression of "no data" or "unknown data", but in this case the number is known to be zero.


texts:
I am having a tough time submitting this code to UVa Online judge and having it pass. I keep getting the message - Your program used more CPU time than what is allowed for this problem. That means that your algorithm is not fast enough or that it entered into an infinite loop.

The challenge: for each line of input, which contains two integers i and j, find the length of the longest collatz-sequence for all Collatz sequences starting with i, i + 1, i + 2, …, j.  You can assume that no operation overflows a 32-bit integer.

I have no idea where the problem is! Any help would be appreciated. Also, I am trying to analyze the algorithm, and I believe it should be O(n2).

 #include <iostream>
    using namespace std;

    int cycleLength(int n) {
      int i = 1;

      while (n != 1) {
        if (n % 2 == 0) {
          n = n/2;
        } else {
          n = 3*n + 1;
        }
        i++;
      }
      return i;
    }

    int main() {

      int fOriginal, sOriginal;
      int first, second, max, temp;

     while (cin >> fOriginal >> sOriginal) {

        if (fOriginal > sOriginal) {
          temp = fOriginal;
          first = sOriginal;
          second = temp;
        }

        max = cycleLength(first);

        for(int i = first + 1; i <= second; i++) {
          temp = cycleLength(i);
          if (temp > max) {
            max = temp;
          }
        }

        cout << fOriginal << " " << sOriginal << " " << max << endl;
      }

      return 0;
    }


texts:
I just picked up Async Await and I am trying to use Async Await in Console App along with TPL for querying webservices. The code works fine and I am able to get the speed using HttpClient and async. Wanted to know if I am overusing async/await and if there is anything that I should avoid and can be simplified further.

I have read Albahari's threading e-book and the following articles to understand the usage.

http://www.tugberkugurlu.com/archive/how-and-where-concurrent-asynchronous-io-with-asp-net-web-api

http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115163.aspx

https://scalablenotions.wordpress.com/2015/05/02/tpl-and-async-await-best-practices-for-the-busy-developer/

class Program
{
    public class Member
    {
        public string N { get; set; }
        public string E { get; set; }
    }

    static void Main()
    {
        List<Member> list = new List<Member>();
        Task.Run(async () => { await SubscribeMembersusingAPI(list); }).GetAwaiter().GetResult();

    }

    // Define other methods and classes here
    public static async Task SubscribeMembersusingAPI(List<Member> members)
    {
        List<string> updateemailstosubscribed = new List<string>();
        HttpClient client = new HttpClient();

        try
        {
            await Task.WhenAll(members.Select(m => SubscribeusingAPI(client, m)));
        }
        catch (Exception e)
        {
            //logger.Error("Error in Async task", e);
        }
        return;
    }

    public static async Task<bool> SubscribeusingAPI(HttpClient client, Member member)
    {
        try
        {
            List<KeyValuePair<String, String>> listkvp = new List<KeyValuePair<string, string>>();
            listkvp.Add(new KeyValuePair<string, string>("e", member.E.Trim()));
            listkvp.Add(new KeyValuePair<string, string>("n", member.N.Trim()));
            listkvp.Add(new KeyValuePair<string, string>("boolean", "true"));
            FormUrlEncodedContent formpost = new FormUrlEncodedContent(listkvp);
            var response = await client.PostAsync("", formpost);
            string responsebody = await response.Content.ReadAsStringAsync();
            if (responsebody == "1" || responsebody == "Member present")
                return true;
            else
                Console.WriteLine(string.Format("FAIL, Error while subscribing e: {0}, n: {1}, response: {2}", member.E, member.N, responsebody));
        }
        catch (Exception e)
        {
            Console.WriteLine(string.Format("FAIL, Error while subscribing e: {0}, n: {1} ", member.E, member.N), e);
        }
        return false;
    }
}


texts:
I created a class to automate some requests for an API. Can I improve this code in any way?

The code itself is very simple and easy to understand.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RestSharp;

namespace Dummie
{
    public class AutoRequest
    {
        RestClient client;

        public CancellationTokenSource Cancel;

        string captchaResult = "";

        public AutoRequest(int timeout)
        {
            client = new RestClient("http://127.0.0.1");
            client.Timeout = timeout;
            client.CookieContainer = new System.Net.CookieContainer();

            Cancel = new CancellationTokenSource();

        }

        private WebProxy ParseProxy(string proxy)
        {
            try
            {
                var p = proxy.Split(':');
                if (p.Count() > 2)
                {
                    var webproxy = new WebProxy(p[0], Convert.ToInt32(p[1]));
                    webproxy.Credentials = new NetworkCredential(p[2], p[3]);
                    return webproxy;
                }
                else
                {
                    return new WebProxy(p[0], Convert.ToInt32(p[1]));
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<bool> TestProxy(string proxy)
        {
            client.Proxy = ParseProxy(proxy);

            var request = new RestRequest("http://127.0.0.1", Method.GET);

            var response = await client.ExecuteTaskAsync(request, Cancel.Token);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return false;
            }

            return true;
        }

        public async Task<bool> CreatCookies(string apiCaptcha)
        {
            captchaResult = await SolveCaptchaAsync(apiCaptcha);

            var request = new RestRequest("http://127.0.0.1", Method.GET);

            var response = await client.ExecuteTaskAsync(request, Cancel.Token);

            if(response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception();
            }

            return true;
        }

        private async Task<string> SolveCaptchaAsync(string apiCaptcha)
        {
            TwoCaptcha.Solve solver = new TwoCaptcha.Solve();
            var result = await solver.ReCaptchaV2Async(apiCaptcha, "6LeLvl", "http://127.0.0.1");
            return result.Request;
        }

        public async Task<string> SignUp()
        {

            var request = new RestRequest("http://127.0.0.1/api_test", Method.POST);
            request.AddParameter("g-recaptcha-response", captchaResult);

            var response = await client.ExecuteTaskAsync(request, Cancel.Token);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return "[ERROR] Failed during request. Status: " + response.StatusDescription;
            }

            if (response.ResponseUri.ToString() == "http://127.0.0.1/api_test?result=ok")
            {
                return "[OK] Account Successfully Created";
            }
            else
            {
                return "[ERROR] There was an error creating your account. URI: " + response.ResponseUri.ToString();
            }
        }
    }
}


texts:
I search for rails-like way of writing NodeJS code and it's more then hard to find the right way. The code quickly become bloated and unreadable. I would like my code to be as clean as possible.

Example (common ExpressJS middleware API controller):

var User = require('../models/user'); // mongoose model

exports.updateUser = function(req, res, next) {
  User.passwordToSecretWithBcrypt(req.body.password, function(err, secret) {
    if (err) return next(err);

    User.findById(req.user.id).exec(function(err, user) {
      if (err) return next(err);
      if (!user) return next(new Error('no user found'));

      if (req.body.name) user.name = req.body.name;
      if (req.body.email) user.email = req.body.email;
      if (secret) user.secret = secret;
      user.save(function(err, user) {
        if (err) return next(err);
        if (!user) return next(new Error('user not saved'));

        res.json(user);
      });
    });
  });
};

The main question is the error handling. A simple record update in the example above has 5 error handling statements. That's crazy in my opinion and you never know exactly what kind of error you'll get so it's very hard to construct the JSON error response that is shown to a user.

Is there a better way for handling errors?

I also tried to use promises but I couldn't find a best-practice example that would show me the whole example as a chain of the find, save, create and delete Mongoose methods.

How can I convert the example above to use promises?

Would promises fix the error handling?  If so, how (question1)?


texts: Router for quering MySQL results in NodeJS

texts:
What should I consider in order to refactor the following code ?

It seems very close to proudly become a Pyramid of Doom:

router.get('/:id', function(req, res) {

    getId = req.params.id
    obj = {}

    db.con.query('SELECT * FROM employees where id=?', getId, function(err, results) {

        if (err) {
            console.log('error in query')
            return

        } else {
            try {
                obj = {
                    id: results[0].id,
                    name: results[0].name,
                    location: results[0].location
                }
                res.render('showuser')

            } catch (err) {
                res.status(500)
                res.render('error', { error: err, id: getId })
            }
        }
    })
});


texts:
I created a mega menu using flexbox, and because I'm not really into CSS, a review would be helpful.

I know it would be better to avoid the third ul-level but this is not possible, because the HTML is generated by another system. And we decided to use the second ul level as a marker for a new row in the mega menu.

With saying "Mega Menu" I mean that when you hover over "products" you will not just see a single list of sub items, but instead multiple lists. Often in "Mega Menus" they also add more content like text or pictures (not needed for me).

ul {
  width: 100%;
  display: flex;
  flex-direction: column;
  list-style: none;
  margin: 0 0 0 0;
  padding: 0;
  position: relative;
  background: red;
}
ul li {
  flex: 1 1 auto;
  display: block;
  text-align: left;
}
ul li:hover {
  background: tomato;
}
ul li:hover ul {
  display: flex;
}
ul li a {
  display: block;
  padding: 1rem 0;
}
ul li ul {
  display: none;
  left: 0;
  width: 100%;
}
ul li ul li {
  flex: 0 0 auto;
}

@media screen and (min-width: 37.5em) {
  ul {
    flex-direction: row;
  }
  ul li {
    text-align: center;
    background: green;
  }
  ul ul {
    position: absolute;
  }
  ul ul a {
    padding: 1rem;
  }
  ul ul li {
    position: relative;
    text-align: left;
  }
  ul ul li ul {
    position: relative;
  }
  ul ul li ul li {
    flex-basis: 100%;
  }
}

home

products

short

long

item 1

long item 2

whatever

superlong sub 1

s 2

    </l>

go

on


texts:
I have a method that accepts user input. Additionally, it masks passwords then the input is a password. It also bypasses the prompt of if an env variable supplies the needed input.

Apparently, my code needs refactoring, but how?

def self.gets(args)
  array = []
  args.each do |arg|
    print "#{arg.to_s.capitalize}: "
    if ENV['AWESOMEAPP_'+arg.to_s.upcase]
      array.push ENV['AWESOMEAPP_'+arg.to_s.upcase]
    else
      if arg.to_s=~/password/
        array.push STDIN.noecho(&:gets).chomp
      else
        array.push STDIN.gets.chomp
      end
    end
    print "\n"
  end
  array
end


texts:
This is a Leetcode problem -

  Given a 2D board and a list of words from the dictionary, find all
  words in the board.

  Each word must be constructed from letters of a sequentially adjacent
  cell, where "adjacent" cells are those horizontally or vertically
  neighboring. The same letter cell may not be used more than once in a
  word.

  Note:

  All inputs are consist of lowercase letters a-z.
  The values of
  words are distinct.

Here is my solution to this challenge -

class Solution:
    def __init__(self, board, words):
        self.board = board
        self.words = words

    def find_words(self, board, words):

        root = {}
        for word in words:
            node = root
            for c in word:
                node = node.setdefault(c, {})
            node[None] = True
        board = {i + 1j * j: c
                 for i, row in enumerate(board)
                 for j, c in enumerate(row)}

        found = []
        def search(node, z, word):
            if node.pop(None, None):
                found.append(word)
            c = board.get(z)
            if c in node:
                board[z] = None
                for k in range(4):
                    search(node[c], z + 1j ** k, word + c)
                board[z] = c
        for z in board:
            search(root, z, '')

        return found

Program explanation - I first build a tree of words with root root and also represent the board a different way, namely as a one-dimensional dictionary where the keys are complex numbers representing the row/column indexes. That makes further work with it easier. Looping over all board positions is just for z in board, the four neighbors of a board position z are just z + 1j ** k (for k in 0 to 3), and I don't need to check borders because board.get just returns None if I request an invalid position.

After this preparation, I just take the tree and recursively dive with it into each board position. Similar to how you'd search a single word, but with the tree instead.

Here is an example input/output -

output = Solution([
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
], ["oath","pea","eat","rain"])

print(output.find_words([
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
], ["oath","pea","eat","rain"]))

>>> ['oath', 'eat']

So, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts: Deletion button on a website that enforces database integrity

texts:
I am designing a website on which users can configure (CRUD) various objects which are mutually dependent upon other types. I am preventing a cascade delete, so let's say a Team is created in the database and some Players are created associated with that team (by ForeignKey) then the team can't be deleted.

For a user experience my plan is the following:

Have a validator on the javascript client side as pre screening so the user doesnt expect to be able to delete objects that they shouldnt be allowed to.
Have code on the server side that returns a result even if JS fails and database integrity is compromised.

The Javascript pre-screening looks like this, consider a delete button that is only visible and actionable if certain conditions are met:

<button class="btn" v-on:click="delete_()"
 v-bind:class="{'btn-inactive': selected_team.id == '' || selected_team.members != 0}"
 >Delete</button>

// in script..
delete_: function() {
  var cb = function(data) {
    this.$emit('refresh','');
  };
  this.ajax_($API_SCRIPT_ROOT + '/team', 'delete', this.selected_team, cb);
  this.display = 'main';
},

AJAX will refresh the data on success, or on fail update an error message returned by the API.

The server side looks like this:

def delete_user_resource(kind, user_id, resource_id):
    """
    Deletes an existing resource

    Args:
        kind (str): the class of resource to be created, must be permissible for the specific ``User`` subclass.
            (internal)
        user_id (int): the primary key of the ``User`` creating the resource. (internal)
        resource_id (int): the primary key of the resource class. (internal)
        **kwargs: all required additional args for creation are specified in the docstring for underlying resource
            class. (external)

    Returns:
        tuple: success boolean, string representation of state.
    """
    resource = read_user_resource(kind, user_id, resource_id)
    db.session.delete(resource)
    try:
        db.session.commit()
        return True, resource.__repr__()
    except IntegrityError as e:
        db.session.rollback()
        return False, e.statement

@api_0.route('/team', methods=['DELETE'])
@login_required
def team_delete():
    user_args = {
        "id": fields.Int(required=True),
    }
    kwargs = flaskparser.parser.parse(user_args, request)

    result = delete_user_resource(kind='team', user_id=current_user.id, resource_id=kwargs['id'])
    if result[0]:
        return jsonify({'result': 'SUCCESS', 'description': result[1]}), 201
    else:
        return jsonify({'result': 'FAILED', 'description': result[1]}), 400

Here is the function that performs a security check for read access to a resource:

def read_user_resource(kind, user_id, resource_id):
    """
    Read a resource specific to the given ``User``.

    Args:
        kind (str): the class of resource to be created, must be permissible for the specific ``User`` subclass.
            (internal)
        user_id (int): the primary key of the ``User`` creating the resource. (internal)
        resource_id (int): the primary key of the resource class specifed by kind. (internal)

    Returns:
        object: specific resource identified by unique id.
    """
    user = User.query.filter(User.id == user_id).one()

    Resource = RESOURCES2[user.type][kind]
    resource = Resource.query.filter(Resource.id == resource_id).one_or_none()
    if resource.organiser_team_id != user.organiser_team_id:
        # security error since resource does not belong to authorising user
        return None

    return resource

I think this seems a fairly reasonably and decoupled (DRY) way of coding this that is potentially testable and maintainable. Do you agree or are there gaping holes which will cause problems later?


texts: Dataframe transformation to numpy ndarray takes ages to complete

texts:
I would like to transform my dataframe into an array of fixed-sized chunks from each unique segment. Specifically, I would like to transform the df to a list of m arrays each sized (1,100,4). So at last, I would have an (m,1,100,4) array.
Since I require that the chunks be of fixed-size (1,100,4), and on splitting it is unlikely that each segment produce perfectly this size, the last rows of a segment are usually less, so should be zero-padded.
For this, I start be creating an array of this size, and populate it with all zeros. Then gradually fill in these values with df rows. This way, what's left at end of a particular segment is therefore zero-padded.
To do this, I use the function:
def transform(dataframe, chunk_size):

    grouped = dataframe.groupby('id')

    # initialize accumulators
    X, y = np.zeros([0, 1, chunk_size, 4]), np.zeros([0,])

    # loop over each group (df[df.id==1] and df[df.id==2])
    for _, group in grouped:

        inputs = group.loc[:, 'A':'D'].values
        label = group.loc[:, 'class'].values[0]

        # calculate number of splits
        N = (len(inputs)-1) // chunk_size

        if N > 0:
            inputs = np.array_split(
                 inputs, [chunk_size + (chunk_size*i) for i in range(N)])
        else:
            inputs = [inputs]

        # loop over splits
        for inpt in inputs:
            inpt = np.pad(
                inpt, [(0, chunk_size-len(inpt)),(0, 0)],
                mode='constant')
            # add each inputs split to accumulators
            X = np.concatenate([X, inpt[np.newaxis, np.newaxis]], axis=0)
            y = np.concatenate([y, label[np.newaxis]], axis=0)

    return X, y

This function does produce the intended ndarray. However, it is extremely slow. My df has over 21M rows, so the function takes more than 5hours to complete, this is crazy!
I am looking for a way to refactor this function for optimization.
Steps to reproduce the issue:
Generate a random large df:
import pandas as pd
import numpy as np
import time

df = pd.DataFrame(np.random.randn(3_000_000,4), columns=list('ABCD'))
df['class'] = np.random.randint(0, 5, df.shape[0])
df.shape
(3000000, 5)

df['id'] = df.index // 650 +1
df.head()

       A           B           C           D    class   id
0   -0.696659   -0.724940   0.494385    1.469749    2   1
1   -0.440400   0.744680    -0.684663   -1.962713   4   1
2   -1.207888   -1.003556   -0.926677   -1.455632   3   1
3   1.575943    -0.453352   -0.106494   0.351674    3   1
4   0.888164    0.675754    0.254067    -0.454150   3   1

Transform df to the required ndarray per unique segment.
start = time.time()
X,y = transform(df, 100)
end = time.time()

print(f"Execution time: {(end - start) / 60}")
Execution time: 6.169370893637339

For a 5M rows df this function takes more than 6mins to complete. In my case (>21M rows), it takes hours!!!
How do it write the function to improve speed? Maybe the notion of creating the accumulator is completely wrong.


texts: Maze path finder using Depth-First Search algorithm

texts:
I'm trying to resolve this kata from CodeWars.
Kata exercise

You are at position [0, 0] in maze NxN and you can only move in one of the four cardinal directions (i.e. North, East, South, West). Return true if you can reach position [N-1, N-1] or false otherwise.
Empty positions are marked .. Walls are marked W. Start and exit positions are empty in all test cases.

I made a simple depth first search algorithm to solve the maze and check if there exists an exit.
But I noticed that my code is too slow and so it produces Execution Timed Out error.
I'm quite sure that changing this algorithm to an heuristic one could fix this, but I don't want to do that. I want to solve this using a Deep Search Algorithm. Is possible to improve the performance of this code?
I think the problem may be in the set, which don't have a pop method, so removing an item from them is quite difficult. But using an array would even require more time to check if the item already exists there.

function pathFinder(maze) {
  // Turn maze from string to nested array
  let chart = [];
  for (let c of maze.split("\n")) {
    chart.push([...c]);
  }

  let size = chart.length;

  // Make toVisit frontier
  let toVisit = new Set();
  toVisit.add([0, 0]);

  // Check if we already are in the exit
  let end = size - 1;
  // Size 1 maze
  if (end == 0)
    return true;

  while (toVisit.size > 0) {
    // Pop value from set
    let pos = toVisit.values().next().value;
    toVisit.delete(pos);

    let [x, y] = pos;
    chart[x][y] = "*"; // Mark as visited

    // Iterate over adjancets
    for ([x, y] of [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]]) {
      // Check exit
      if (end == x && end == y)
        return true;
      // Check array out of boundary
      if (x < 0 || y < 0 || x >= size || y >= size)
        continue;
      // Check if wall or already visited
      let value = chart[x][y];
      if (value != "W" && value != "*")
        toVisit.add([x, y]);
    }
  }
  return false;
}


texts:
I am developing an application that must generate a random password for each new user in the system (initial password).

My idea is to use passwords of 16 characters long.

Would like to know if the code below is a secure way to generate passwords and if it can be improved. The system will be used by hundreds of thousands of users and security is a priority.

import java.security.SecureRandom;
import java.util.Random;

public class SecureRandomPasswordGenerator {

    private static final Random RANDOM = new SecureRandom();
    private static final String POSSIBLE_CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-+=!@#$%&*()[]{}<>:.,?";

    public String generatePassword(int length) {
        StringBuilder password = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            password.append(POSSIBLE_CHARACTERS.charAt(RANDOM.nextInt(POSSIBLE_CHARACTERS.length())));
        }
        return password.toString();
    }

}


texts: Find all distinct triples less than N that sum to S

texts:
Exercise 2.41.  Write a procedure to
  find all ordered triples of distinct
  positive integers i, j, and k less
  than or equal to a given integer n
  that sum to a given integer s.

(define (enumerate-integers i j)
  (if (= i j)
      (list j)
      (cons i (enumerate-integers (+ i 1) j))))

(define (filter f seq)
  (if (null? seq)
      null
      (if (f (car seq))
          (cons (car seq) (filter f (cdr seq)))
          (filter f (cdr seq)))))

(define (remove x seq)
  (filter (if (pair? x)
              (lambda (y) (not (member y x)))
              (lambda (y) (not (= x y)))) seq))

(define (unique-triples-less-than n)
  (let ((the-number-list (enumerate-integers 1 (- n 1))))
    (flatmap (lambda (i)
               (flatmap (lambda (j)
                          (map (lambda (k) (list i j k))
                               (remove (list i j) the-number-list)))
                        (remove i the-number-list)))
             (enumerate-integers 1 (- n 1)))))

(define (flatmap f seq)
  (accumulate append null (map f seq)))

(define (accumulate op initial seq)
  (if (null? seq)
      initial
      (op (car seq)
          (accumulate op initial (cdr seq)))))

(define (s-sum-triples-below-n n s)
  (filter (lambda (y) (= (accumulate + 0 y) s))
          (unique-triples-less-than n)))

Can this code be improved in any way?


texts:
I have created this piece of js purely for learning purposes and I was hoping you could code review to see any mistakes / improvements I can make.

Basically I have a tree structure and I will use the depth variable to work out what level of the menu I will display.

Here is the code example: http://jsfiddle.net/nqGbw/5/

HTML

The Tree

 Root

 Folder 1

Folder 1.1

Folder 1.2

 Folder 2

Folder 2.1

 Folder 2.2

Folder 2.2.1

Folder 2.2.2

Folder 2.2.3

JS

var calcDepth = function (root) {
    var $parent = $(root).parents('ul');
    var depth = 0;
    while ($parent.length > 0) {
        $parent = $parent.parents('ul');
        depth += 1;
    }
    return depth;
};

var func = function (rootUL, maxDepth) {
    var selectedUL = rootUL;
    $(selectedUL.children('li')).each(function () {
        var Me = $(this);
        if (calcDepth(Me.parent()) == maxDepth) {
            Me.hide();
        }
        if (Me.children('ul').length > 0) {
            var selectedUL = Me.children('ul');
            func(selectedUL, maxDepth);
        }
    });
};
var depth = 2; //Change this to set the depth of the menu
var selectedUL = $("ul");
func(selectedUL, depth);


texts: Adding and Retrieving Players in a simple Pre-Flop Poker Hud with Local Storage

texts:
I am building a browser based Pre-Flop HUD that for now just tracks VPIP, PFR and number of hands played for an opponent (https://pokercopilot.com/poker-statistics/vpip-pfr). I am currently using local storage to store my data. In the future I will use a better persistence strategy, add more features, and find a way to de-couple the user interface without just putting it in the functions I have now. I used an object literal approach without classes right now to try out some basic decomposition with simple functions for practice. Right now the only functionality I have is adding a player to Local Storage and getting all players from Local Storage.

Any suggestions for improvement are welcome.
But I do have a couple questions:

Is there a benefit to using Classes?  Right now I don't see the benefit of having a handle, like, player1 = new Player(arg,arg,etc...), player2 = new Player(arg,arg, etc...)...
Is there a better way to store to Local Storage? I don't think storing each player with their own key and having a ton of entries is a good idea.
In my function addPlayer() should I be calling savePlayersToStorage in my localStorageUtils.js?

Main.js file = entry point for my program

    /**********************************
 * This is the program driver, that
 * will call other functions
 * *******************************/

import { addPlayer } from "./player.js";
import {
  savePlayersToStorage,
  getPlayersFromStorage,
} from "./LocalStorageUtilsObjectLiteral.js";

function main() {
  let newPlayer = "Doug Polk";
  const localStorageKey = "stored_players";
  let players = getPlayersFromStorage(localStorageKey); //array of player objects in localStorage
  players.push(addPlayer(newPlayer));
  savePlayersToStorage(localStorageKey, JSON.stringify(players));
}

main();

Player.js addPlayer creates and returns an object literal

function addPlayer(name) {
  let player = {
    uuid: Date.now(),
    name: name,
    vpipActionCount: 0, //The number of times a player voluntarily put money into the pot Pre-Flop, whether calling or raising.
    pfrActionCount: 0, //The number of times a player raised pre-flop, this includes 3-bets.
    vpipPercentage: 0, //The percentage of hands a player has played, can be between 0 and 100%
    pfrPercentage: 0, //The percentage of hands a player has raised pre-flop, can be between 0 and 100%, but can never be higher than vpipPercentage
    totalHandsTracked: 0, //The number of hands tracked for a player

    callAction: function () {
      this.totalHands++;
      this.vpipActionCount++;
    },
    raiseAction: function () {
      this.totalHands++;
      this.pfrActionCount++;
    },
    foldAction: function () {
      this.totalHands++;
    },
    calculateVpipPercentage: function () {
      this.vpip = (this.vpipActionCount * 100) / this.totalHands;
    },
    calculatePfrPercentage: function () {
      this.pfrPercentage = (this.pfrActionCount * 100) / this.totalHands;
    },
    getVpipPercentage: function () {
      return this.vpipPercentage;
    },
    getPfrPercentage: function () {
      return this.pfrPercentage;
    },
  };
  return player;
}

export { addPlayer };

LocalStorageUtils.js Functions to get and save players to Local Storage

function savePlayersToStorage(localStorageKey, playersArray) {
  if (localStorage.getItem(localStorageKey === null)) {
    localStorage.setItem(localStorageKey);
  }
  localStorage.setItem(localStorageKey, playersArray);
}

function getPlayersFromStorage(localStorageKey) {
  if (localStorage.getItem(localStorageKey === null)) {
    localStorage.setItem(localStorageKey);
  }
  let players = JSON.parse(localStorage.getItem(localStorageKey));

  return players;
}

export { savePlayersToStorage, getPlayersFromStorage };


texts: Am I over-reacting with my page SESSIONS security?

texts:
In order to secure my page SESSIONS I have the following pages.

My questions are

Am I over-reacting with this?
Should I place the token in login.php instead of the loginForm.php ?
When a user logins, I save his IP in the DB. Should I make use of this in authentication ?

Thank you community.

Login form loginForm.php

$token = md5(uniqid(rand(),TRUE));
<input name="login" type="text" class="textfield" id="login" />
<input name="password" type="password" class="textfield" id="password" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="submit" name="Submit" value="Login" />

When the user logins login.php

$fingerprint = sha1('SECRET-SALT'.$_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].$_POST['token']);
    session_regenerate_id();
    $member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
$_SESSION['SESS_TOKEN'] = $_POST['token'];
$_SESSION['SESS_FINGERPRINT'] = $fingerprint;
session_write_close();
    header("location: index.php");
    exit();

Authenticating on every page auth.php

    session_start();
    $fingerprint = sha1('SECRET-SALT'.$_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].$_SESSION['SESS_TOKEN']);
    if( !isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')  || ($_SESSION['SESS_FINGERPRINT'] != $fingerprint) || !isset($_SESSION['SESS_TOKEN']) || (trim($_SESSION['SESS_TOKEN']) == '') ) {
        header("location: denied.php");
        exit();
    }