texts:
I need to make a function like these two, but at least an order of magnitude faster in python.
Any tips or tricks?

These functions inputs are nested lists, like: request_parameters = [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, [110, 111, 112, 113, 114]]

Their output should be: [[1, 2, 3, 4, 5, 110], [1, 2, 3, 4, 5, 111], [1, 2, 3, 4, 5, 112], [1, 2, 3, 4, 5, 113], [1, 2, 3, 4, 5, 114]]

OR
a numpy.ndarray:

[[ 1  2  3  4  5 110]
 [ 1  2  3  4  5 111]
 [ 1  2  3  4  5 112]
 [ 1  2  3  4  5 113]
 [ 1  2  3  4  5 114]]

A unit test is on the way...

input:

request_parameters = [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, [110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180]]

Output:

[[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 110]
...
...
...
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 180]]

import numpy as np

request_parameters = [1, 2, 3, 4, 5, [10, 11, 12, 13, 14]]

def transform_nested_list(request_parameters: list) -> np.ndarray:
    """
    Generate np.ndarray from a nested list
    """
    abc_ids = np.asarray(request_parameters[-1])
    #print(abc_ids)

    all_except_id = np.asarray(request_parameters[0:-1])
    #print(all_except_id)

    all_subrequest = np.hstack([all_except_id, abc_ids[0]])
    for element in abc_ids[1:]:
        row = np.hstack([all_except_id, element])
        all_subrequest = np.vstack([all_subrequest, row])
    #print(all_subrequest)
    #print(type(all_subrequest))
    return (all_subrequest)

import copy

def old_transform_nested_list(request_parameters: list) -> list:
    abc_ids = np.asarray(request_parameters[-1])
    all_except_id = (request_parameters[0:-1])

    request_list = []
    subrequest = [all_except_id]
    for single_id in abc_ids:
        #print(single_id)
        subrequest = copy.deepcopy(all_except_id)

        subrequest.append(single_id.astype(int))
        request_list.append(subrequest)
    #print(request_list)
    #print(type(request_list))
    return request_list

import datetime

loop = 10000
start = datetime.datetime.now()
for i in range(loop):
    transform_nested_list(request_parameters)
end = datetime.datetime.now()
print((end-start).total_seconds())

start = datetime.datetime.now()
for i in range(loop):
    old_transform_nested_list(request_parameters)

end = datetime.datetime.now()
print((end-start).total_seconds())

  >
  1.111902,
  0.886634
  [Finished in 2.2s]

Got a bit better results, but still not good enough:

import itertools
def flatten(container):
    for i in container:
        if isinstance(i, (list,tuple)):
            for j in flatten(i):
                yield j
        else:
            yield i

def old_tuple_transform_nested_list(request_parameters: list) -> list:
    abc_ids = np.asarray(request_parameters[-1])

    all_except_id = (request_parameters[0:-1])

    request_list = []
    subrequest = tuple(all_except_id)
    for single_id in abc_ids:
        toupled_subrequest = tuple([subrequest, [single_id]])
        chain = list(itertools.chain(*toupled_subrequest))

        subrequest_list = list(flatten(chain))

        request_list.append(subrequest_list)
    #print(request_list)
    #print(type(request_list))
    return request_list

A better version for longer lists:

def longer_vector_transformrequest(requestparameters: list) -> list:
    ids = np.asarray(requestparameters[-1])
    allexceptid = np.asarray(requestparameters[0:-1])
    subrequest = np.append(allexceptid, 0)

    allsubrequest = np.empty((len(ids),len(requestparameters)))
    for i in range(len(ids)):
        subrequest[-1] = ids[i]
        allsubrequest[i] = subrequest
    return allsubrequest


texts: Writing a class that represents a sorted list of filenames

texts:
I have a question:

  Write a class that represents a sorted list of filenames. The filenames are sorted by most recently added first. Duplicates are not allowed.

And I wrote this solution:

public class RecentlyUsedList

{

    private readonly List<string> items;

    public RecentlyUsedList()

    {

        items = new List<string>();

    }

    public void Add(string newItem)

    {

        if (items.Contains(newItem))

        {

            int position = items.IndexOf(newItem);

            string existingItem = items[position];

            items.RemoveAt(position);

            items.Insert(0, existingItem);

        }

        else

        {

            items.Insert(0, newItem);

        }

    }

    public int Count

    {

        get

        {

            int size = items.Count;

            return size;

        }

    }

    public string this[int index]

    {

        get

        {

            int position = 0;

            foreach (string item in items)

            {

                if (position == index)

                    return item;

                ++position;

            }

            throw new ArgumentOutOfRangeException();

        }

    }

}

Now, other person asked me, do the code review of your own code and tell the answers of following questions:

  Three operations are required:

  How long is the list?
  Access filename at a given position
  Add a filename to the list; if it already exists in the list it gets moved to the top otherwise the new filename is simply prepended to the
  top.

I got confused and tried to look on Google but I didn't get much from there. What would be the best answers to these questions?


texts: Insert dynamic parameters to sqlite database statements

texts:
I want to insert parameters dynamically to statements at sqlite.
I now write as follows:

            tx.executeSql('SELECT Data from Table Where something = "'+ anyvariable+ '"',[],successFn, errorCB);

But I guess there is a better (cleaner) method to do it.. Any ideas?


texts: Conversion of a simple Python Neural Network to a Haskell implementation

texts:
I started with this code and modified and expanded it in Python. As an exercise/challenge to myself I decided to covert the original to Haskell. I either write imperatively or functionally. This is the first time I have tried converting from one logic to another.  I ran into a lot of little issue along the way. I aimed to just get it to work and I want to make it work better now.

import Data.List
import System.Random
import Data.Matrix hiding (transpose, trace)
import Debug.Trace

flipSign::Num a => a -> a
flipSign x = (-1) * x

nonlin:: Bool -> Double ->   Double
nonlin True x = x*(1.0-x)
nonlin False x =  1.0 / (1.0 + (exp $ flipSign x))

randomList :: (Random a) => Int -> [a]
randomList seed = randoms (mkStdGen seed)

sample:: [[Double]]
sample = map (map fromIntegral)[ [0,0,1], [0,1,1], [1,0,1], [1,1,1] ]
answers:: [[Double]]
answers = transpose $ map (map fromIntegral) [[0,0,1,1]]

syn0:: [[Double]]
syn0 = [[x] | x<- take 3 (randomList 42 :: [Double])]

dotp:: [[Double]] -> [[Double]] -> [[Double]]
dotp x y = toLists newMatrix
    where
        mx = fromLists x
        my = fromLists y
        newMatrix = multStd mx my

nextGeneration::[[Double]] -> [[Double]] -> ([[Double]], [[Double]]) -> ([[Double]],[[Double]])
nextGeneration x labels syn0_l1 = (new_syn0, l1)
    where
        l0 = x
        syn0 = fst syn0_l1
        l1 = map (map $ nonlin False) $ dotp l0 syn0
        l1_error = zipWith (zipWith (-)) labels l1
        l1_delta = zipWith (zipWith (*)) l1_error $ map (map (nonlin True)) l1
        new_syn0 = zipWith (zipWith (+)) syn0 $ dotp (transpose l0) l1_delta

generations::([[Double]] -> [[Double]]) -> [[Double]] -> Int -> [[Double]]
generations _ end 0 = end
generations fun weights count = generations fun (fun weights) (count - 1)

main = print $ snd $ iterate (nextGeneration sample answers ) (syn0, [[]] ) !!10000


texts: Priority Queue (Binary Search Tree) Implementation

texts:
I have made a Priority Queue implemented as a Binary Search Tree. I would appreciate comments related to optimization and proper functionality, but any comments/critiques are welcome.

PQ.h:

#ifndef PQ_H
#define PQ_H

#include <iostream>

struct Node
{
    int value;
    Node * left;
    Node * right;
    Node(int value)
    : value(value), left(NULL), right(NULL)
    {

    }
};

class PQ
{
    private:
        Node * root;
        void Push(int value, Node * node);
        int Pop(Node * node, Node * parent);
        void DeletePQ(Node * node);
    public:
        PQ();
        ~PQ();
        void Push(int value);
        int Pop();
        void DeletePQ();
        bool IsEmpty();
};

#endif

PQ.C:

#include "PQ.h"

PQ::PQ()
{
    root = NULL;
}

PQ::~PQ()
{
    DeletePQ();
}

void PQ::DeletePQ()
{
    DeletePQ(root);
}

void PQ::DeletePQ(Node * node)
{
    if(node != NULL)
    {
        DeletePQ(node->left);
        DeletePQ(node->right);
        delete node;
    }
}

void PQ::Push(int value)
{
    if(root != NULL)
    {
        Push(value, root);
    }
    else
    {
        root = new Node(value);
    }
}

void PQ::Push(int value, Node * node)
{
    if(value < node->value)
    {
        if(node->left != NULL)
        {
            Push(value, node->left);
        }
        else
        {
            node->left = new Node(value);
        }
    }
    else
    {
        if(node->right != NULL)
        {
            Push(value, node->right);
        }
        else
        {
            node->right = new Node(value);
        }
    }
}

int PQ::Pop()
{
    int value;
    if(root != NULL)
    {
        if(root->right != NULL)
        {
            value = Pop(root->right, root);
        }
        else
        {
            value = root->value;
            if(root->left != NULL)
            {
                Node * temp = root;
                root = root->left;
                delete temp;
            }
            else
            {
                delete root;
                root = NULL;
            }
        }
    }
    else
    {
        value = -1;
    }
    return value;
}

int PQ::Pop(Node * node, Node * parent)
{
    int value;
    if(node->right != NULL)
    {
        value = Pop(node->right, node);
    }
    else
    {
        value = node->value;
        if(node->left != NULL)
        {
            parent->right = node->left;
        }
        else
        {
            parent->right = NULL;
        }
        delete node;
    }
    return value;
}

bool PQ::IsEmpty()
{
    bool isEmpty;
    if(root == NULL)
    {
        isEmpty = true;
    }
    else
    {
        isEmpty = false;
    }
    return isEmpty;
}


texts:
Every once in a while I need to get some random computer thing done; so I write something to do it for me. This is one of those. It needed to be able to send text to, and receive text from, a server - without blocking. I am asking for feedback with the premise of what kind of code this is: A one-use hack.

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <ctype.h>

#define BUFLEN 1024

volatile static int run = 1;

void sendx(int sd) {
    int sent, i;
    char buffer[BUFLEN], ch;
    do {
        i = 0;
        do {
            ch = getc(stdin);
            buffer[i] = ch;
            i++;
        } while (ch != '\n' && i < BUFLEN);
        sent = write(sd, buffer, i);
    } while (sent == i && run);
}

void recvx(int sd) {
    char nothing[] = { '?' };
    int len, i;
    char buffer[BUFLEN];
    do {
        len = read(sd, buffer, BUFLEN);
        i = 0;
        while (i < len) {
            if (isprint(buffer[i]))
                write(1, buffer + i, 1);
            else write(1, nothing, 1);
            i++;
        }
    } while (len > 0 && run);
    close(sd);
    nothing[0] = '\n';
    write(0, nothing, 1);
    fflush(stdin);
}

int main(int argc, char **argv) {
    int sd, pid;
    struct sockaddr_in addr;

    memset(&addr, 0, sizeof(struct sockaddr));

    assert(argc == 3);
    sd = socket(AF_INET, SOCK_STREAM, 0);
    addr.sin_family = AF_INET;
    assert(inet_pton(AF_INET, argv[1], &addr.sin_addr) > 0);
    addr.sin_port = htons(atoi(argv[2]));
    assert(sd > -1);
    assert(connect(sd, (struct sockaddr *)&addr, sizeof(addr)) > -1);
    pid = fork();
    assert(pid > -1);
    if (pid == 0)   sendx(sd);
    else        recvx(sd);
    run = 0;
    return 0;
}


texts: "Human" interfaces with two implementation classes

texts:
The Helloworld class executes all of the methods. Human is the interface, and Nate & Ryan are two classes that implement the Human interface. Are there any deficiencies or faults that my code contains that could help me in the long run?

public class Helloworld{

    public static void main(String[] args) {

        Human ryan = new Ryan();
        ryan.setHeight(12);
        System.out.println("Ryan's height is " + ryan.getHeight());

        Human nate = new Nate();
        nate.setHeight(32);
        System.out.println("Nate's height is " + nate.getHeight());

        nate.hit(ryan);

        /*
         * OUTPUT --------------------------------------
         *
         * Ryan's height is 12
         * Nate's height is 32
         * Nate has hit Ryan
         *
         */

    }

}

interface Human{

    public void sleep();
    public void eat();
    public void wakeUp();
    public void walk();
    public void hit(Human name);
    public void setHeight(int height);
    public int getHeight();
    public String getName();

}

class Nate implements Human{

    int height = 0;
    final String name = "Nate";

    public String getName() {
        return this.name;
    }

    public void setHeight(int height) {
        if(height > 0) {
            this.height = height;
        }else {
            System.out.println("You can't set Nate's height to less than 0.");
        }
    }
    public int getHeight() {
        return this.height;
    }
    public void sleep() {
        System.out.println("Nate has fallen asleep");
    }
    public void eat() {
        System.out.println("Nate has eaten");
    }
    public void wakeUp() {
        System.out.println("Nate has woken up");
    }
    public void walk() {
        System.out.println("Nate is walking");
    }
    public void hit(Human name) {
        System.out.println("Nate has hit " + name.getName());
    }

}

class Ryan implements Human{

    int height = 0;
    final String name = "Ryan";

    public String getName() {
        return this.name;
    }

    public void setHeight(int height) {
        if(height > 0) {
            this.height = height;
        }else {
            System.out.println("You can't set Ryan's height to less than 0.");
        }
    }
    public int getHeight() {
        return this.height;
    }
    public void sleep() {
        System.out.println("Ryan has fallen asleep");
    }
    public void eat() {
        System.out.println("Ryan has eaten");
    }
    public void wakeUp() {
        System.out.println("Ryan has woken up");
    }
    public void walk() {
        System.out.println("Ryan is walking");
    }
    public void hit(Human name) {
        System.out.println("Ryan has hit " + name.getName());
    }

}


texts: Program to check an item's price against available credit

texts:
This is a working program to check an item's price against available credit. I'm trying to simplify this program to the bare minimum. It would require to run so I'll be better able to understand each part of the 'if' and 'else' processes. Is there a simpler way to write a program that accomplishes the task below? I'm new to C#, just trying to figure this stuff out.

  Write a program named CheckCredit that prompts users to enter a purchase price for an item.
  If the value entered is greater than a credit limit of $8,000, display you have exceeded the credit limit; otherwise, display Approved.

using static System.Console;

namespace CheckCredit
{
    class Program
    {
        static void Main(string[] args)
        {
            const double CreditCheck = 8000;
            string userInput;
            double price;

            WriteLine("This is a program designed to check an item's price
            against your amount of available credit.");
            WriteLine("Your credit limit is $8,000.00.\n");

            do
            {
                Write("Please type the item's price:");
                userInput = ReadLine();
                if (!double.TryParse(userInput, out _))
                {
                    WriteLine("Invalid input, please enter a whole or decimal number.");
                    userInput = null;
                }
            } while (!double.TryParse(userInput, out price));

            if (price > CreditCheck)
            {
                WriteLine(" You have exceeded the credit limit", price);
            }

            else if
            (price == CreditCheck)
            {
                WriteLine(
                "Approved.(*)\n\n\n"
                +
                "(*) It is exactly your credit limit.");
            }
            else
            {
                WriteLine("Approved.");
            }
            ReadKey();
        }
    }
}


texts: Is the following service layer correctly implemented with multiple repositories?

texts:
I'm new to design patterns and specifically the Service Layer implementation. I need some clarification on where to use Service Layer calls.

Below is an example of what I'm dealing with.  I have data from 2 different repositories so I'm not quite certain when/where I'm supposed to call up any additional information that I need to build my Business Model.

I would like for it to do the following:

Find Car in Repository
Get Picture from another Repository
Update Url within Model to be used for Presentation Layer.

What i'm stuck with is I'm not sure if that logic belongs in the Car Model or it should be handled by a Service layer and within the service layer all of this gets combined.  Hopefully this isn't too confusing. Below I added what I thought was relevant.

Business Model/Logic:

public class Car
{
    private readonly IFileSystemService _service;
    public Car(IFileSystemService service)
    {
        _service = service;
    }

    public int id { get; set; }
    public string model { get; set; }
    public int year { get; set; }
    public Image GetImageFile(IGetImageService imgService);
}

Within the Service Layer:

public void GetImageFile(int carId)
{
    Image imgfile = _Repository.GetPhysicalFileLocation(carId);
    // ...
}

Repository 1:

public Car GetCar(int carId)
    {
        Car myCar = this.GetCar(carId);
        // ...
    }

Repository 2:

public Car GetPictureForCar(int carId)
    {
        Car myCar = this.GetFileForCar(carId);
        // ...
    }


texts:
This is how I create am Nginx virtual host for a WordPress webapp. I did best to keep it as minimal as I can while having a working webapp. Please review it:

#!/bin/bash
domain="$1" && test -z "$domain" && exit 2
drt="/var/www/html"

cat <<-EOF > "$s_a/$domain.conf"
    server {
        root ${drt}/${domain};
        server_name ${domain} www.${domain};
        index index.php index.html index.htm;
        location / {
                try_files $uri $uri/ /index.php?q=$uri&$args;
            }
        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
            }
        location ~* \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ {
            expires 365d;
        }
    }
EOF


texts: Applying a string-identified effect on an image

texts:
Task:

Given an image object and an effect identifier (string), apply the effect identified by the string on the image. The library of effects can grow as the program grows.

Code 1:

def apply_fx(img, fx):
    if fx == 'sepia':
        return sepia(img)
    elif fx == 'b&w':
        return contrast(grayscale(img), 2)
    elif fx == 'faded':
        return faded(img)
    elif fx == 'hdr':
        return hdr(img)

Code 2:

effects = {
    'sepia': sepia,
    'b&w': lambda x: contrast(grayscale(x), 2),
    'faded': faded,
    'hdr': hdr
}

def apply_fx(img, fx):
    return effects[fx](img)

Opinion: I personally lean toward the second approach.

Note: the concern here generalizes to: dictionary of lambda functions vs if-elif in such scenarios.

Extra code: as suggested by @PeilonRayz.

sepia_filter = np.array([[.393, .769, .189],
                         [.349, .686, .168],
                         [.272, .534, .131]])

def sepia(img):
    sepia_img = np.dot(img, sepia_filter.T)
    return sepia_img / np.max(sepia_img)


texts:
I have this function to remove nodes that matches a certain criteria in the list. Initially when I wrote it, head node was not deleted if head->value was >= delete_value, but other nodes in the list were deleted, so I decided to write the last if statement to only delete and amend the list if head->value was >= delete_value.
It works, but I'm not sure if this is normal?

void remove(List * & head, double value)
{
   if (head == NULL)
   {
    cout << "Empty List";
    return;
   }

   if (head != NULL && head->value != delete_value)
   {
    List* temp1 = head;
    List* temp2 = temp1->next;

       while (temp2 != NULL)
       {
          if (temp2->value >= delete_value)
          {
            List* temp3 = temp2;
            temp2 = temp2->next;
            temp1->next = temp2;
            delete temp3;
          }
          else
          {
            temp1 = temp2;
            temp2 = temp2->next;
          }
       }
   }

   //This deletes head node, if value is greater than or equal to delete_value
   if (head != NULL && head->value >= delete_value)
   {
    List*temp = head;
    head = head->next;
    delete temp;
   }
return;
}


texts: Simple hashing code with excessive conditional statements

texts:
Any thoughts on my code? It's a simple hashing code that runs from the command line.

There just appears to be a lot of condition if / elif entries in both of the main functions (hashingmethod and hashcalculator).

# hashcalculator.py

import sys
import hashlib

args = len(sys.argv)

def inputVerification():
    if sys.argv[1] == "--help":
        scriptHelp()
    elif args < 5:
        print "You have failed to execute the command correctly"
        print "Please type 'hashcalculator --help' for more information"
    else:
        filename = sys.argv[2]
        hashingMethod(filename)

def scriptHelp():
    print "\n"
    print "----------------------------------------"
    print "\tWelcome to Hash Calculator"
    print "----------------------------------------"
    print "\n"
    print "--help"
    print "\n"
    print "In order to calculate the hash value of a file, your command line syntax"
    print "must be written as below:-"
    print "\n"
    print "\thashcalculator -f [file] -h [hash method]"
    print "\teg. hashcalculator -f notepad.exe -h SHA1"
    print "\n"
    print "The recognised hashing methods are MD5, SHA1, SHA224, SHA256, SHA384 and SHA512"

def hashingMethod(filename):
    hashmethod = sys.argv[4].upper()
    if hashmethod == "MD5":
        hashCalculator(filename, "md5")
    elif hashmethod == "SHA1":
        hashCalculator(filename, "sha1")
    elif hashmethod == "SHA224":
        hashCalculator(filename, "sha224")
    elif hashmethod == "SHA256":
        hashCalculator(filename, "sha256")
    elif hashmethod == "SHA384":
        hashCalculator(filename, "sha384")
    elif hashmethod == "SHA512":
        hashCalculator(filename, "sha512")
    else:
        print "You have not entered a valid hashing method"
        print "Please review the help document"
        scriptHelp()

def hashCalculator(filename, hashmethod):
    with open(filename, 'rb') as f:
        if hashmethod == "md5":
            m = hashlib.md5()
        elif hashmethod == "sha1":
            m = hashlib.sha1()
        elif hashmethod == "sha224":
            m = hashlib.sha224()
        elif hashmethod == "sha256":
            m = hashlib.sha256()
        elif hashmethod == "sha384":
            m = hashlib.sha384()
        elif hashmethod == "sha512":
            m = hashlib.sha512()
        else:
            scriptHelp()
        while True:
            data = f.read(8192)
            if not data:
                break
            m.update(data)
        print "\n\n"
        print "The %s hash of file %s is:" % (hashmethod.upper(), filename)
        print "\n", m.hexdigest()

if __name__ == "__main__":
    inputVerification()


texts: Detecting if image taken by camera is too dark

texts:
I am trying to build functionality to check if an image taken by the camera is too dark. So I added the following 2 functions to a utility class:

public static boolean checkIfImageIsTooDark(BitmapRegionDecoder bitmapRegionDecoder)
{
    if(bitmapRegionDecoder == null) {
        Timber.e("Expected bitmapRegionDecoder was null");
        return false;
    }

    int loadingBitmapHeight = bitmapRegionDecoder.getHeight();
    int loadingBitmapWidth = bitmapRegionDecoder.getWidth();

    boolean isImageTooDark = true;

    int checkBitmapWidth = loadingBitmapWidth / 10;
    int checkBitmapHeight = loadingBitmapHeight / 10;
    int topBitmapPosition = 0;
    int leftBitmapPosition = 0;

    while((checkBitmapWidth <= loadingBitmapWidth) && (leftBitmapPosition < checkBitmapWidth)) {
        while((checkBitmapHeight <= loadingBitmapHeight) && (topBitmapPosition < checkBitmapHeight)) {
            Rect bitmapRect = new Rect(leftBitmapPosition,topBitmapPosition,checkBitmapWidth,checkBitmapHeight);
            Timber.d("left: " + leftBitmapPosition + " right: " + checkBitmapWidth + " top: " + topBitmapPosition + " bottom: " + checkBitmapHeight);

            Bitmap processBitmap = bitmapRegionDecoder.decodeRegion(bitmapRect,null);

            if(!checkIfImageIsTooDark(processBitmap)) {
                isImageTooDark = false;
                break;
            }

            topBitmapPosition = checkBitmapHeight;
            checkBitmapHeight += (checkBitmapHeight < (loadingBitmapHeight - checkBitmapHeight)) ? checkBitmapHeight : (loadingBitmapHeight - checkBitmapHeight);
        }

        if(!isImageTooDark) {
            break;
        }

        topBitmapPosition = 0;
        checkBitmapHeight = loadingBitmapHeight / 10;
        leftBitmapPosition = checkBitmapWidth;
        checkBitmapWidth += (checkBitmapWidth < (loadingBitmapWidth - checkBitmapWidth)) ? checkBitmapWidth : (loadingBitmapWidth - checkBitmapWidth);
    }

    return isImageTooDark;
}

public static boolean checkIfImageIsTooDark(Bitmap bitmap) {
    if(bitmap == null)
    {
        Timber.e("Expected bitmap was null");
        return false;
    }

    int[] brightnessHistogram = new int[256];

    for(int i = 0; i < bitmap.getHeight(); i++) {
        for(int j = 0; j < bitmap.getWidth(); j++) {
            int pixel = bitmap.getPixel(j,i);

            int r = Color.red(pixel);
            int g = Color.green(pixel);
            int b = Color.blue(pixel);

            int brightness = (int)(0.2126 * r + 0.7152 * g + 0.0722 * b);
            brightnessHistogram[brightness]++;
        }
    }

    int allPixelsCount = bitmap.getWidth() * bitmap.getHeight();

    //counting pixels with brightness less than 10
    int darkPixelCount = 0;
    for(int i = 0; i < 10; i++)
    {
        darkPixelCount += brightnessHistogram[i];
    }

    //if more than 70% pixels are too dark then image is too dark
    return darkPixelCount > allPixelsCount * 0.70;
}

The brightness histogram approach I found over here -> https://stackoverflow.com/a/35914745/3287853. And it works quite well.

The only problem however is that processing an image takes way too much time. I tried it on my phone which produces 4160x3120 and it takes close to a minute to get a result off it. Also, the 4 loops don't look great and I think there should be a better way to make this work, personally.

I am using an AsyncTask to do this in the background so one improvement that I could think of is to break up the task across multiple threads.

I could also compress the image initially bringing it down to a certain limit of width and height while attempting to maintain its aspect ratio and then process the image. However I wonder if that would actually help in reducing the amount of time taken at all.


texts:
As per the definition given in lecture, ADT is,

With reference to this definition, I would like to call SList class an ADT following 6 invariants:

Multiple users of SList class should be consistent in usage with same SList instance. For example multiple users may insert items in same shopping list.
No runtime exceptions while using SList class when list is empty.
SList size member variable is always correct.
SList is never circularly linked list.
SList never returns SListNode, instead it return only an item.
Methods of the SlistNode class can be modified in future without any affect to SList class users. I guess this is nothing but encapsulation.

The below two classes will be part of a package and be used by classes from other packages:

class SListNode{
    Object item;
    SListNode next;
    public SListNode(){
        this.item = null;
        this.next = null;
    }
    public SListNode(Object item, SListNode next){
        this.item = item;
        this.next = next;
    }
    public SListNode(Object item){
        this(item,null);
    }
    public void insertAfter(Object item){
        this.next = new SListNode(item,this.next);
    }
    public SListNode nth(int position){
        if(position ==1){
            return this;
        }else if((position < 1) || (this.next == null)){ /* error checking */
            return null;
        }else{
            SListNode tempNode = this.next.nth(position-1);
            return tempNode;
        }
    }

}

public class SList {
    private SListNode head; // First node in list.
    private int size; // Number of items in list.
    public SList() { // Here’s how to represent an empty list.
        head = null;
        size = 0;
    }
    public void insertFront(Object item) {
        head = new SListNode(item, head);
        size++;
    }
    public void insertEnd(Object item){
        SListNode lastNode = this.head;
        while(lastNode.next != null){
            lastNode = lastNode.next;
        }
        lastNode.next = new SListNode(item,lastNode.next);
        size++;
    }
    public void insertAt(Object item, int position){
        if (position == 1){
            insertFront(item);
            size++;
        }else if(position < 1){
            System.exit(1);
        }else{
            SListNode currentNode = this.head.nth(position);
            if(currentNode != null){
                currentNode.insertAfter(item);
                size++;
            }else{
                System.exit(1); //position value exceeds
            }
        }
    }
    public Object nth(int position){
        if(position < 1){
            return null;
        }else{
            SListNode tempNode = this.head.nth(position);
            if(tempNode != null){
                return tempNode.item;
            }
            else{
                return null;
            }
        }
    }

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

My question:
With reference to SList class as shown above, Can you please confirm if my interpretation of definition of ADT is correct?
If the interpretation is wrong, What code changes would you like to see, to call SList as an ADT?

Note: I am yet to learn exception-handling, interfaces, inheritance, polymorphism and composition in class.


texts:
I've got this code that I found in a project and I'm wondering how can it be done better:

- (void) setAlpha:(float)alpha {
    if (self.superview.tag == noDisableVerticalScrollTag) {
        if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleLeftMargin) {
            if (self.frame.size.width < 10 && self.frame.size.height > self.frame.size.width) {
                UIScrollView *sc = (UIScrollView*)self.superview;
                if (sc.frame.size.height < sc.contentSize.height) {
                    return;
                }
            }
        }
    }
    if (self.superview.tag == noDisableHorizontalScrollTag) {
        if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleTopMargin) {
            if (self.frame.size.height < 10 && self.frame.size.height < self.frame.size.width) {
                UIScrollView *sc = (UIScrollView*)self.superview;
                if (sc.frame.size.width < sc.contentSize.width) {
                    return;
                }
            }
        }
    }

    [super setAlpha:alpha];
}


texts:
I have implemented the "Find the N longest lines in a file" problem from CodeEval quoted below.

I got a full 100 score and 182ms execution time of their data set on the site so I consider the code to be working and effective. What I'm wondering is, is there something I can do to make this faster than it already is? Did I miss anything? Any other comments?

  Write a program which reads a file and prints to stdout the specified
  number of the longest lines that are sorted based on their length in
  descending order. Input sample:

  Your program should accept a path to a file as its first argument. The
  file contains multiple lines. The first line indicates the number of
  lines you should output, the other lines are of different length and
  are presented randomly. You may assume that the input file is
  formatted correctly and the number in the first line is a valid
  positive integer.

  For Example:

2
Hello World
CodeEval
Quick Fox
A
San Francisco

  Output sample:

  Print out the longest lines limited by specified number and sorted by
  their length in descending order.

  For example:

San Francisco
Hello World

The code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class NLongestLines {

    private final static Comparator<String> CMP = new Comparator<String>() {
        @Override
        public int compare(String arg0, String arg1) {
            return arg1.length() - arg0.length();
        }
    };

    private static void insertSorted(List<String> list, String string) {
        int max = list.size();
        int min = 0;
        int pivot = min + (max - min) / 2;

        // Binary search for insertion point.
        while (min < max) {
            int c = CMP.compare(string, list.get(pivot));
            if (c <= 0) {
                max = pivot;
            } else {
                min = pivot + 1;
            }
            pivot = min + (max - min) / 2;
        }

        list.add(min, string);
    }

    public static void main(String[] args) throws Exception {
        try (FileReader fr = new FileReader(args[0]);
             BufferedReader reader = new BufferedReader(fr)) {
            List<String> longestLines = new ArrayList<>();

            String line = reader.readLine();
            {
                int numLongestLines = Integer.parseInt(line);
                while (numLongestLines > 0 && (line = reader.readLine()) != null) {
                    numLongestLines--;
                    line = line.trim();
                    insertSorted(longestLines, line);
                }
            }

            int shortestLongLength = findShortestLongLine(longestLines);
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.length() > shortestLongLength) {
                    insertSorted(longestLines, line);
                    longestLines.remove(longestLines.size() - 1);
                    shortestLongLength = findShortestLongLine(longestLines);
                }
            }

            for (String longLine : longestLines) {
                System.out.println(longLine);
            }
        }
    }

    private static int findShortestLongLine(List<String> longestLines) {
        return longestLines.get(longestLines.size() - 1).length();
    }
}

Edit/Addendum:

I have implemented and benchmarked the proposed solutions by Simon Forsberg (TreeSet) and RolfL (LinkedList).

The results can be seen here. The executive summary is that the original algorithm is significantly faster than the proposals in just about all test cases.

The source used for testing can be found here. Needs µbench from here.


texts: Bouncing ball - for swing event handling tutorial

texts:
This is a sample program that I intend to post as part of a series of beginner level Java tutorials.  Please provide any feedback on improvements that would make example more clear or illustrate/emphasize best practices.  The example drawns a ball object to a panel on a mouse click and then moves it randomly with another mouse click.

Class BouncingBall

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/*
 * this class will add a red ball to a canvas or play area, when a button is clicked and
 * then move about randomly when another button is clicked
 *
 * jmergenthaler 10/1/2011
*/

public class BouncingBall {

private JFrame frame = new JFrame();
private JPanel actionPanel = new JPanel();
private JPanel playarea = new JPanel();
private JButton btnNew = new JButton("Add Red Ball");
private JButton movebtn = new JButton("Move it");

//constructor
BouncingBall(){
    buildTheGUI();
}

public void buildTheGUI(){
    frame.setLayout( new BorderLayout());
    btnNew.addActionListener( new ButtonClickHandler() );
    movebtn.addActionListener( new MoveButtonClickHandler() );
    actionPanel.add(btnNew);
    actionPanel.add(movebtn);
    frame.add(BorderLayout.NORTH,actionPanel);
    frame.add(BorderLayout.SOUTH,playarea);
    frame.setSize(500, 500);
    frame.setVisible(true);
}

public static void main(String args[]){
    new BouncingBall();
}

class ButtonClickHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){

        //create initial Ball object add to the frame
        frame.add(new Ball() );
        //draw
        frame.validate();
    }
}

class MoveButtonClickHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){

        //polymorphic behavior, calling the Ball constructor differently
        frame.add(new Ball(1) );
        //redraw
        frame.validate();
    }
}// end class MoveButtonClickHandler
}//end class BouncingBall

class 2 - the Ball class

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;

class Ball extends JPanel{

//private instance variables avail. only avail to methods in this class
private int x,y,w,h;

//constructor
Ball(){
    this.x = 200;
    this.y = 200;
    this.w = 100;
    this.h = 100;
}

//constructor with different behavior
Ball(int a){
    Random rand = new Random();

    this.w = 100;
    this.h = 100;
    this.x = rand.nextInt(300);
    this.y = rand.nextInt(300);
}

//draw the ball
//@override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.setColor(Color.RED);
    g.fillOval(x, y, h, w);
}

}//end class Ball


texts: Stack implementation in python using jupyter

texts:
This is my first program in Python: a stack implementation.

class Stack:
    items =[];
    index =-1;

    def isEmpty(self):
        return  self.index >=0;

    def push(self,item):
            self.index  +=1;
            print(self.index);
            self.items.insert(self.index,item);

    def pop(self):

        if self.index<0:
            raise Exception(" no items in list");
        else:
            del self.items[self.index];
            self.index -=1;

    def peek(self):
        print(self.index);
        if self.index >-1:
            return self.items[self.index];

stackobj = Stack();
stackobj.push("solomon");
stackobj.push("helloworld")
stackobj.pop();

print(stackobj.peek())

Even though this program works I'm still confused as to whether I've written the program in the right way. I am also not sure when to use the self operator.


texts:
The method receives an unformatted string and it needs to put line breaks after ';' or before 'i)' and 'i.', where i - integer.
If received a string like '; 1)', then it should add only one line breaker after ';' and before '1)'.

// This is ugly - needs to be refined and refactored
private static String format(String unformattedStr) {
    Pattern p1 = Pattern.compile("(\\;\\s*)");
    Matcher matcher1 = p1.matcher(unformattedStr);

    String formattedStr1;
    if (matcher1.find()) {
        formattedV1 = matcher1.replaceAll("$1\\\\n");
    } else {
        formattedV1 = unformattedStr;
    }

    Pattern p2 = Pattern.compile("(\\d+\\)|\\d+\\.)");
    Matcher matcher2 = p2.matcher(formattedV1);
    String formattedV2;

    if (matcher2.find()) {
        formattedV2 = matcher2.replaceAll("\\\\n$1");
    }
    else {
        formattedV2 = formattedV1;
    }

    String formattedV3 = formattedV2.replaceAll("\\\\n\\s*(\\\\n)+", "\\\\n");
    return formattedV3;
}


texts:
How can this be improved,to make it easier to maintain? There is so much boilerplate being thrown around, so is it possible to use annotations? I've seen one example from Stack Overflow, but it ended up using reflection in order to call the method.

I was already planning on somehow annotating these "variables" in order to automatically produce the documentation, to prevent the documentation going out of date.

GitHub

public class TownyChatFormatter {
private static StringReplaceManager<LocalTownyChatEvent> replacer = new StringReplaceManager<LocalTownyChatEvent>();

static {
    replacer.registerFormatReplacement(Pattern.quote("{worldname}"), new TownyChatReplacerCallable() {
        @Override
        public String call(String match, LocalTownyChatEvent event) throws Exception {
            return String.format(ChatSettings.getWorldTag(), event.getEvent().getPlayer().getWorld().getName());
        }
    });
    replacer.registerFormatReplacement(Pattern.quote("{town}"), new TownyChatReplacerCallable() {
        @Override
        public String call(String match, LocalTownyChatEvent event) throws Exception {
            return event.getResident().hasTown() ? event.getResident().getTown().getName() : "";
        }
    });


texts:
Tell me how to speed up the removal of empty folders / files ?

string[] dirs = Directory.EnumerateDirectories(str1, "*", SearchOption.AllDirectories).ToArray();
DirectoryInfo dirInfo = new DirectoryInfo(str1);
for (int i = dirs.Length - 1; i >= 0; i--)
{
   if (Directory.EnumerateFileSystemEntries(dirs[i]).Count() == 0)
       Directory.Delete(dirs[i], true);
}
foreach(string pathToFile in Directory.GetFiles(str1))
{
     if (new FileInfo(pathToFile).Length == 0)
     {
          try
          {
              File.Delete(pathToFile);
          }
          catch(Exception ex)
          {
             // error
          }
     }
}

Deletes files not from all folders.


texts: Overriding scrolling behavior for navigation elements

texts:
I am new to JavaScript, and trying to ensure the i write the best possible code instead of "copy & paste".

I hope i am asking correctly, want to know if my code I have written is done correctly or could it be done better, the code works, so nothing wrong with the end result, just not sure if I'm on the right track.

$(document).ready(function() {
"use strict";

var menu_btn = $('a.menu-trigger');
var menu     = $('#main_nav > ul');
var w        = $(window).width();

// Adding the ScrollTo Function on the menu items

$('#main_nav > ul a[href^="#"],.logo a[href^="#"]').on('click', function(e) {

    var target = $( $(this).attr('href') );

    if(target.length ) {

        e.preventDefault();
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 1000);
    }

    if (w < 768) {
        $('#main_nav > ul').css('display', 'none');
    }
});

// Create the Sticky Header

$(window).scroll(function() {
    if ($(this).scrollTop() > 1){
        $('.header-inner').addClass("sticky");
    }else{
        $('.header-inner').removeClass("sticky");
    }
});

// Mobile Menu Functionality

menu_btn.on('click', function(e) {
    e.preventDefault();
    menu.slideToggle ();
});

$(window).resize(function () {

    if (w > 768 && menu.is(':hidden')) {
        menu.removeAttr('style');
    }
});

});


texts: Handling session resources in MY_Controller with Codeigniter

texts:
I've added a function that checks if the user is trying to use/access something which requires a session. I'd love to hear some criticisms of my choice of design.

class MY_Controller extends CI_Controller {

    function __construct() {
        parent::__construct();
        if(!$this->input->is_ajax_request()) {
            if(!$this->session->userdata('is_logged_in')) {
                $this->load->view('header_public_view');
                if($this->login_required())
                  //do something, redirect etc..
            }
            else {
                $this->load->model('user_model');
                $data['user'] = $this->user_model->get_user($this->session->userdata('userid'));
                $this->load->view('header_user_view', $data);
            }
        }

    }

    function login_required() {
        if($this->uri->total_segments() > 3)
            $request = $this->uri->segment(3);
        else
            $request = $this->uri->segment(2);
        foreach(unserialize(SESSION_RESOURCES) as $required) {
            if($request == $required)
                return true;
        }
    }

}


texts:
I am trying to multithread a for loop, and this works so far. How can it be improved? Have I done anything incorrectly?

The work is broken up into blocks and the block variable is the amount of objects to process per thread.

Test.class

public class Test extends MultiThreaded {

    public static void main(String args[]) {

        List<TestObject> values = new ArrayList<TestObject>();

        for(int i = 1;i < 7;i++)
            values.add(new TestObject(String.valueOf(i)));

        int block = 2;
        int cursor = 0;

        List<TestObject> objectList = new ArrayList<TestObject>();

        for(TestObject v : values) {
            cursor++;
            objectList.add(v);

            if(cursor < block)
                continue;

            final List<TestObject> objectListCopy = new ArrayList<TestObject>();
            objectListCopy.addAll(objectList);

            Task task = new Task() {
                @Override
                public void run() {
                    for(TestObject o : objectListCopy)
                        o.print();
                }
            };

            startTask(task);
            objectList.clear();

            cursor = 0;
        }

        while(MultiThreaded.processing()) { continue; }

        System.out.println("move on");
    }

    public static class TestObject {
        String line;

        public TestObject(String string) {
            this.line = string;
        }

        public void print() {
            System.out.println(line);
        }
    }

}

MultiThreaded.class

public class MultiThreaded {

    public static HashSet<Task> tasks = new HashSet<Task>();

    public static class Task extends Thread {
        public boolean running;
        public void run(){
            return;
        }
    }

    public static void startTask(Task task) {
        task.start();
        tasks.add(task);
    }

    public static Task getTask(int id) {

        for(Task task : tasks){
            if(task.getId() == id)
                return task;
        }

        return null;
    }

    public static boolean processing() {

        boolean processing = false;

        for(Task task: tasks){
            if(task.isAlive())
                processing = true;
        }

        return processing;
    }

}

OUTPUT

1
2
5
6
3
4
move on


texts: Flattening XML and selecting nodes based on input to convert to CSV

texts:
I have some XML that I want to flatten based on its XPath. The task is to acquire certain nodes that are passed as input. That said, I have to get to parent nodes and look for nodes that might be part of the configuration. I am avoiding lists in a given iteration.

This is my code:

from lxml import etree

tree = etree.parse("sample.xml")
path = "/DATA_DS/G_1"

def getNodesDict(node_element, nodes_to_pick):
    some_dict = {}
    for element in node_element:
        if not isinstance(element, list):
            if element.tag in nodes_to_pick:
                some_dict[element.tag] = element.text

    return some_dict

def fetchNodesListBasedOnXpath(Xpath, tree, selected_nodes):
    """

    :param Xpath:
    :param tree:
    :param selected_nodes:
    :return:
    """
    temp_list = []
    temp_list1 = []
    element_split = Xpath.split('/')
    for i in range(len(element_split), 1, -1):
        path = "/".join(element_split[0:i])
        try:
            element = tree.xpath(path)
            for j, node_element in enumerate(element):
                value = getNodesDict(node_element, selected_nodes)
                if len(temp_list) > 0 and len(temp_list) - 1 > j:
                    for k, item in enumerate(temp_list):
                        dall = {}
                        dall.update(value)
                        dall.update(item)

                        if item:
                            temp_list1.append(dall)
                    temp_list = []
                else:
                    temp_list.append(value)
        except:
            pass

nodes_to_pick = ['SUBSCRIPTION_ID', "PRODUCT_NUMBER", "SUBSCRIPTION_ID1", "SALES_PRODUCT_TYPE1"]

fetchNodesListBasedOnXpath(path, tree, nodes_to_pick)

This is my sample XML:

<DATA_DS>
    <SUBSCRIPTION_ID1>300000031070490</SUBSCRIPTION_ID1>
    <SALES_PRODUCT_TYPE1>SUBSCRIPTION</SALES_PRODUCT_TYPE1>
    <G_1>
        <SUBSCRIPTION_ID>300000031070490</SUBSCRIPTION_ID>
        <PRODUCT_NUMBER>1</PRODUCT_NUMBER>
        <SALES_PRODUCT_TYPE>SUBSCRIPTION</SALES_PRODUCT_TYPE>
        <PRODUCT_NAME>Demo4</PRODUCT_NAME>
        <STATUS>ORA_EXPIRED</STATUS>
        <START_DATE>2019-06-01T00:00:00.000+00:00</START_DATE>
        <END_DATE>2019-06-01T00:00:00.000+00:00</END_DATE>
    </G_1>

    <G_1>
        <SUBSCRIPTION_ID>300000031070491</SUBSCRIPTION_ID>
        <PRODUCT_NUMBER>4</PRODUCT_NUMBER>
        <SALES_PRODUCT_TYPE>SUBSCRIPTION</SALES_PRODUCT_TYPE>
        <PRODUCT_NAME>Demo4</PRODUCT_NAME>
        <STATUS>ORA_ACTIVE</STATUS>
        <START_DATE>2019-06-01T00:00:00.000+00:00</START_DATE>
        <END_DATE>2020-05-31T00:00:00.000+00:00</END_DATE>
    </G_1>
    <G_1>
        <SUBSCRIPTION_ID>300000031070492</SUBSCRIPTION_ID>
        <PRODUCT_NUMBER>2</PRODUCT_NUMBER>
        <SALES_PRODUCT_TYPE>SUBSCRIPTION</SALES_PRODUCT_TYPE>
        <PRODUCT_NAME>Demo4</PRODUCT_NAME>
        <STATUS>ORA_CLOSED</STATUS>
        <START_DATE>2019-06-01T00:00:00.000+00:00</START_DATE>
        <END_DATE>2019-06-30T00:00:00.000+00:00</END_DATE>
    </G_1>
    <G_1>
        <SUBSCRIPTION_ID>300000031070493</SUBSCRIPTION_ID>
        <PRODUCT_NUMBER>3</PRODUCT_NUMBER>
        <SALES_PRODUCT_TYPE>SUBSCRIPTION</SALES_PRODUCT_TYPE>
        <PRODUCT_NAME>Demo4</PRODUCT_NAME>
        <STATUS>ORA_ACTIVE</STATUS>
        <START_DATE>2019-06-01T00:00:00.000+00:00</START_DATE>
        <END_DATE>2019-08-31T00:00:00.000+00:00</END_DATE>
    </G_1>
</DATA_DS>


texts:
I am getting a compiler warning when running my code analysis.  It is CA2202.  It is saying that I have not properly disposed my dataset through all exception paths.  Here is the code:

    private System.Data.DataSet MyDataSet()
    {
        DataSet dat_set = new DataSet();

        using (SqlConnection conn = new SqlConnection(conn_string))
        {
            try
            {
                da_1 = new SqlDataAdapter(sql_string, conn);
                dat_set.Locale = CultureInfo.InvariantCulture;
                da_1.Fill(dat_set, "Table_Data_1");
                MainForm.wasSuccess = true;
            }
            catch (SqlException ex)
            {
                Console.Write(ex.ToString());
            }
        }

        return dat_set;
    }

Any thoughts on how to properly dispose this object?


texts: Modifying a random String stored in the clipboard

texts:
I wrote a simple program, that will make a string 'noisy' if the clipboard contains one.
What disappoints me, is that I should manually check what I got from
getClipboardString — in the Nothing case, we simply return from program, otherwise we modify the string. Is there a better way to do this kind of check?

import Data.Char (toUpper)
import System.Random (randomIO)
import System.Clipboard (setClipboardString, getClipboardString)
import Control.Monad (join)

main :: IO ()
main = do
 join $ fmap (test doNoise) getClipboardString
 where
 test :: (String -> IO ()) -> (Maybe String) -> IO ()
 test _ Nothing = return ()
 test f (Just s) = f s

 doNoise :: String -> IO ()
 doNoise s = do
  capsed <- (sequence $ map randCap s)
  setClipboardString capsed

 randCap :: Char -> IO Char
 randCap x = fmap ($ x) $ fmap choice (randomIO :: IO Bool)

 choice :: Bool -> (Char -> Char)
 choice x = if x then toUpper else id


texts: Is there a cleaner way to ensure I am not writing duplicate data?

texts:
I have the following loop which uses Idiorm to write to a table from a PHP Slim application:

foreach($jobs->get_items() as $job) {

        echo $job->get_title().'<br />';
        $jobRow = ORM::for_table('jobs')->create();
        $jobRow->guid = $job->get_id(TRUE);
        $jobRow->url = $job->get_link();
        $jobRow->description = $job->get_description();
        $jobRow->pubdate = $job->get_date();
        echo $job->get_date();

        try {
        $jobRow->save();
        } catch (exception $e) {
            continue;
        }
    }

It feels a bit hacky to be using continue in a try/ catch block. Is there a better way to avoid a MYSQL constraint violation without having to query the table? get_id() returns an md5 hash of the guid in an rss feed which is actually a unqiue URL. I have a UNIQUE index on that field in my table.


texts:
I am new to coding. Given int arrays A and B, I would like to find the maximum GCD (Greatest Common divisor) any element of A and any element of B. I am doing the following

Sorting both arrays, then
Comparing every value of array A to array B to find GCD
Using a temp number I am checking if the GCD found is bigger than previous.
Finally returning the value (i.e. temp)

The GCD(a,b) returns the Greatest Common divisor of a and b.

Note: I am not comparing elements of A array with A.

Is there any way to improve the performance of my Code?

I want to decrease the time for a large number of inputs of Arrays A and B in the for loops by applying some Conditions.

Example :

A=2,5,8,9

B=4,12,8,7,16

Now if we choose 8 from A and 8 from B we get maximum GCD i.e. 8 . And then returning The maximum GCD (i.e. 8 in my example).

   private static int GCD(int a, int b) {
    BigInteger b1 = BigInteger.valueOf(a);
    BigInteger b2 = BigInteger.valueOf(b);
    BigInteger gcd = b1.gcd(b2);
    return gcd.intValue();
    }

 public static int maximumGcd(int[] A, int[] B) {
    Arrays.sort(A);
    Arrays.sort(B);
    int temp = 0;
    for (int i = A.length-1; i >0; i--) {
        for (int j = A.length-1; j >0; j--) {
            int tempGcd = GCD(A[i],B[j]);
            if ( tempGcd > temp){
                temp = tempGcd;
            }
        }
    }
    return temp;
}


texts: Extension method to retrieve list of days in the current week

texts:
I want to get all days of the current week (from Monday to Sunday) with a custom time. To do this, I have written an extension method for TimeSpan:

public static DateTime[] Daily(this TimeSpan ts)
{
    var days = DayOfWeek.Monday - DateTime.UtcNow.DayOfWeek;
    var startDate = DateTime.UtcNow.AddDays(days);
    List<DateTime> dates = new List<DateTime>();

    for(var i = 0; i < 7; i++)
    {
        dates.Add(startDate.Date + ts);
        startDate = startDate.AddDays(1);
    }

    return dates.ToArray();
}

As an example of how it would be used, new TimeSpan(17, 0, 0).Daily() will return:

23/01/2016 17:00:00
24/01/2016 17:00:00
25/01/2016 17:00:00
26/01/2016 17:00:00
27/01/2016 17:00:00
28/01/2016 17:00:00
29/01/2016 17:00:00

Any suggestions on ways to improve my code?


texts: Loading interstitial adMob in different threads

texts:
I want to load Interstitial AdMob after 5 second, after the Activity started, in another Thread. Is this code right, or I'm duplicating Runnables? Is there a better way?

    Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setActivityImmersiveMode();
    setContentView(R.layout.activity_normal_mode);

    // loading ads
    handler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadInterstitialAd();
                }
            }, 5000);

        }
    };

    Thread thread = new Thread(runnable);
    thread.setName("AdThread");
    thread.start();

}


texts:
I've implemented the following prop. test:

  use ExUnit.Case, async: true
  use Quixir

      ptest [half_width: positive_int(), median: int(min: ^half_width)], trace: true, repeat_for: 500 do
        ptest half_width: positive_int(), median: int(min: ^half_width) do
          result = Pullapi.Numbers.median_range(median, half_width)
          f..l = result

          assert l - f == 2 * half_width
        end
      end

with the function:

  @doc """
  Returns a range specified by a median and half-width.

  ## Examples
      iex> Pullapi.Numbers.median_range(10, 4)
      6..14
  """
  @spec median_range(integer, integer) :: Range.t()
  def median_range(median, half_width) when half_width > 0 and median >= half_width do
    min = median - half_width
    max = median + half_width
    min..max
  end

Have I identified the key invariant and properties that should be tested here?
I believe I've implicitly tested that the enumerable is an ordered range by pattern matching the returned data structure.


texts: Stream Exercise: average delta of the yearly average temperature per country

texts:
a Temperature calss is given (not allowed to modify it):

public class Temperature {
    private final LocalDate date;
    private final double temperature;
    private final String city;
    private final String country;
    // getters   are available
}

There is a pre-implemented method called stream() with gives me a  non-null stream of these objects.

I'm tasked to find the average delta of the yearly average temperature per country.

A delta is the difference  between the average of year \$y_i\$ and year \$y_{i+1}\$

In addition, the average over all countries should be stored in the key Globally.

The purpose of these activity is to learn about streams. So loops are forbidden.

criteria: performance > brevity > readability

I've came up with two approaches:

using TreeMap, problem it's O(n*log n)

public Map < String, Double > avgTemperatureDeltaPerYearPerCountry() {

 Function < Temperature, Integer > getYear = x -> x.getDate().getYear();

 var answer = stream().collect(groupingBy(Temperature::getCountry,
  collectingAndThen(Collectors.groupingBy(getYear, TreeMap::new,
    Collectors.toList()), x -> {
    Function < Map.Entry < Integer,
    List < Temperature >> ,
    Double > average =
    y -> y.getValue().stream().mapToDouble(Temperature::getTemperature)
    .average().getAsDouble();

    return (average.apply(x.lastEntry()) -
     average.apply(x.firstEntry())) / Math.max(x.size() - 1, 1);
   }

  )
 ));

 answer.put("Globally", answer.values().stream().collect(averagingDouble(i -> i)));
 return answer;

}

using teeing, problem it calculates the average for all years instead of only for the first and last one.

public Map < String, Double > avgTemperatureDeltaPerYearPerCountry() {

 Function < Temperature, Integer > getYear = x -> x.getDate().getYear();

 var answer = stream().collect(groupingBy(Temperature::getCountry,
  teeing(
   groupingBy(getYear, averagingDouble(Temperature::getTemperature)),
   teeing(maxBy(Comparator.comparing(getYear)),
          minBy(Comparator.comparing(getYear)), Map::entry),
   (a, b) -> (a.get(getYear.apply(b.getKey().get())) -
   a.get(getYear.apply(b.getValue().get()))) / Math.max(a.size() - 1,1)
  )

 ));

 answer.put("Globally", answer.values().stream().collect(averagingDouble(i -> i)));
 return answer;

}

How can I improve thise code, is there a better approach?
Ist it possible to calculate and add the global answer in the same pass?

csv file for test data: https://gofile.io/?c=ugWXIG

Temperatures class to turn the csv file into a stream of Temperature Objects (not my code):  https://ideone.com/GXLhwH

Result:

{Globally=0.041800897436956246, Cyprus=0.015007500000000036, Portugal=0.024267619047619073, Iceland=0.035724166666666675, Russia=0.05631454594017095, Greece=0.030444285714285754, Austria=0.047424333333333346, Sweden=0.03479516666666667, Netherlands=0.03418625000000002, Ireland=0.026464999999999995, Poland=0.0498942543859649, Slovenia=0.04946666666666665, Slovakia=0.056125416666666685, France=0.03514935185185184, Croatia=0.04781805555555557, Romania=0.05889966666666666, Hungary=0.05899083333333333, Ukraine=0.07034451388888886, Moldova=0.06559138888888888, Belarus=0.062140104166666654, Switzerland=0.03716116666666666, Albania=0.02697416666666669, Spain=0.02474883333333331, Turkey=0.03446887254901967, Belgium=0.03550976190476192, Norway=0.023666875000000004, Finland=0.04395483333333333, Denmark=0.034530416666666654, Italy=0.032463908730158766, Montenegro=0.046323333333333314, Germany=0.03924569958847737, Estonia=0.057730833333333356}


texts: Custom algorithm for hashing and un-hashing password


texts: Retrieving localized Days of Week in PHP : setlocale VS IntlDateFormatter

texts:
I'm trying to find a good way to dynamically print a selection of localized days of week without resorting to an hard-coded array per language, leveraging locale mechanisms instead.

Up until now, I've tried 2 methods which both have their weaknesses.

Input Example :

$dows_input = array(0, 1, 2, 4, 6);

Which represent Sunday, Monday, Tuesday, Thursday and Saturday values. Those are not necessary always the same days on each call.

NB : Which locale is used is simplified in our methods below, as it's normally coming from a session variable depending on the end-user language setting.

Method 1 : via setlocale + strftime

function via_setlocale($dows_input) {
  $defaultLocale = Locale::getDefault();
  $days = "";
  foreach($dows_input as $dow) {
    setlocale(LC_TIME, "fr_CA.utf8"); //Either set this for a Unix-based server
    //setlocale(LC_TIME, "french"); //Or this for a Windows server
    $t = strftime('%A', strtotime('next Sunday +' . $dow . ' days'));
    setlocale(LC_TIME, $defaultLocale);
    $days .= $t . ",";
  }
  return substr($days, 0, -1);
}

Method 2 : VIA IntlDateFormatter

function via_dateformatter($dows_input) {
  $formatter = new IntlDateFormatter(
                'fr_CA',
                IntlDateFormatter::NONE,
                IntlDateFormatter::NONE,
                DateTimeZone::UTC,
                IntlDateFormatter::GREGORIAN,
                'EEEE' //Day of the week, localized, complete
              );
  $days = array_map(
    function($dow) use($formatter) {
        return $formatter->format(strtotime('next Sunday +' . $dow . ' days'));
    },
    $dows_input
  );
  return implode(",", $days);
}

Method 1 comes with the usual problems associated with setlocale in a multi-threaded environment as it is per process, leading to unpredictable behaviours if not called and reset on every call to a locale-based function.

Method 2 takes about 3 to 4 times longer to execute from my tests than Method 1, but is thread-safe. Intl extension must be available on the host system.

As for now I've opted for a single call to Method 2 (with a fallback to Method 1 if extension is not available) with all days of the week stocked in memory once through the whole request, so the speed factor is less of a issue over different $dow_inputs.

Any thoughts on how to make this better? Is there another alternative I have not thought of you could share? Bonus point for the more portable solution out there, as it is meant to run on multiple typical, run-of-the-mill shared hosting servers with PHP 5.3+ environments.


texts:
This function checks if the EndDate of my grid is valid or not. If it is not valid, it turns the bgcolor of the cell to red color with cell-error class.

I need some help in optimizing this block of code. It looks dirty right now.

function onAccrualEndDateChange(current) {
var endDate = $(current).val();
if (endDate != "") {
    var actualEndDate = endDate;
    if (actualEndDate != null) {
        var tempEndDate = parseInt(actualEndDate.getMonth() + 1) + "/" + actualEndDate.getDate() + "/" + actualEndDate.getFullYear();
        if (ValidateDate(tempEndDate)) {
            var startDate = $(current).closest("tr").find("input[id$='StartDate']").val();
            if (startDate != "") {
                var actualStartDate = startDate;
                if (actualStartDate != null) {
                    var tempStartDate = parseInt(actualStartDate.getMonth() + 1) + "/" + actualStartDate.getDate() + "/" + actualStartDate.getFullYear();
                    if (ValidateDate(tempStartDate)) {
                        if (actualStartDate.getDate() > actualEndDate.getDate() || actualStartDate.getMonth() > actualEndDate.getMonth() || actualStartDate.getFullYear() > actualEndDate.getFullYear()) {
                            $(current).closest("td").addClass("cell-error");
                        } else {
                            $(current).closest("td").removeClass("cell-error");
                        }
                    }
                    else {
                        $(current).closest("td").addClass("cell-error");
                    }
                }
                else {
                    $(current).closest("td").addClass("cell-error");
                }
            } else {
                $(current).closest("tr").find("input[id$='StartDate']").closest("td").addClass("cell-error");
            }
        }
        else {
            $(current).closest("td").addClass("cell-error");
        }
    }
    else {
        $(current).closest("td").addClass("cell-error");
    }
} else {
    $(current).closest("td").removeClass("cell-error");
}
}

This is the code to validate the date:

function ValidateDate(date) {
//This validates date with leap year in mm/dd/yyyy or mm/d/yyyy or m/dd/yyyy or m/d/yyyy date format.
var regex = new RegExp("^(((0?[1-9]|1[012])/(0?[1-9]|1\\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\\d)\\d{2}|0?2/29/((19|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$");

return (date.match(regex));
}


texts: Handling lazy-loading webpages using vba

texts:
After a long try I've been able to create a script in vba which can successfully handle webpages with lazy-load. It can reach the bottom of a slow loading webpage if the hardcoded number of the loop is set accurately. I tried with few such pages and found it working flawlessly. The one I'm pasting below is created using finance.yahoo site. It can parse the title of different news after going down to a certain level of that page according to the loop I've defined. Now, what I wanna expect to have is do the same thing without using hardcoded delay what I've already used in my script. Thanks in advance for any guidance to the improvement.

Here is what I've written:

Sub Web_Data()
    Dim IE As New InternetExplorer, html As HTMLDocument
    Dim storage As Object, posts As Object

    With IE
        .Visible = True
        .navigate "https://finance.yahoo.com/"
        Do While .readyState <> READYSTATE_COMPLETE: Loop
        Set html = .document
    End With

    Application.Wait Now() + TimeValue("00:00:005")

    For scroll_down = 1 To 10
        Set storage = html.getElementsByClassName("StretchedBox")
        html.parentWindow.scrollBy 0, 99999
        Application.Wait Now() + TimeValue("00:00:005")
    Next scroll_down

    For Each posts In storage
        Row = Row + 1: Cells(Row, 1) = posts.ParentNode.innerText
    Next posts
    IE.Quit
End Sub

Reference to add to the library:

1. Microsoft Internet Controls
2. Microsoft HTML Object Library


texts: Follow-up: Script to create symlinks for dotfiles in a Git repository

texts:
This is a follow up to my previous question on Code Review. I did try to implement most of feedback provided by thiagoalessio.

This is what my updated code looks like:

#!/usr/bin/env bash

RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
RESET=$(tput sgr0)

is_symlink_dest_equal_to() { test "$(readlink $1)" == "$2"; }
can_create_dir() { mkdir -p "$1"; }
is_directory() { test -d "$1"; }
file_exists() { test -e "$1"; }
is_symlink() { test -L "$1"; }

create_symlink() {
  file_loc="$1"
  symlink_loc="$2"

  ln -s "$file_loc" "$symlink_loc"
  echo "Created a symlink $symlink_loc -> $file_loc"
  return 0
}

invalid_file_error() {
  file_loc="$1"
  symlink_loc="$2"

  echo "${RED}WARNING${RESET}: Failed to link $symlink_loc to $file_loc"
  echo "${RED}         ${RESET}$file_loc does not exist"
  return 1
}

handle_non_existing_symlink_directory() {
  file_loc="$1"
  symlink_loc="$2"
  symlink_dir=$(dirname "$symlink_loc")

  if ! can_create_dir "$symlink_dir" ; then
    echo "${RED}WARNING${RESET}: Failed to link $symlink_loc to $file_loc"
    echo "${RED}         ${RESET}Could not create folder $symlink_dir/"
    return 1
  else
    create_symlink "$file_loc" "$symlink_loc"
  fi
}

handle_wrong_existing_symlink() {
  file_loc="$1"
  symlink_loc="$2"
  current_dest=$(readlink "$symlink_loc")

  echo "It seems like $symlink_loc already is symlink to $current_dest."
  read -p "Do you want to replace it? [Y/N] " -n 1 -r
  if [[ $REPLY =~ ^[Yy]$ ]]
  then
    echo
    echo "Removing current symlink..."
    unlink "$symlink_loc"
    create_symlink "$file_loc" "$symlink_loc"
    return
  fi
}

handle_existing_symlink() {
  file_loc="$1"
  symlink_loc="$2"

  if is_symlink_dest_equal_to "$symlink_loc" "$file_loc" ; then
    echo "--> $symlink_loc -> $file_loc ${GREEN}exists${RESET}."
    return 0
  else
    handle_wrong_existing_symlink "$file_loc" "$symlink_loc"
  fi
}

handle_delete_previous_file() {
  file_loc="$1"
  symlink_loc="$2"

  printf "\\nDeleting %s...\\n" "$symlink_loc"
  rm -rf "$symlink_loc"
  create_symlink "$file_loc" "$symlink_loc"
}

handle_move_previous_file() {
  file_loc="$1"
  symlink_loc="$2"

  printf "\\nMoving %s to ~%s/.other..." "$symlink_loc" "$HOME"
  mkdir "$HOME/.other"
  mv "$symlink_loc" "$HOME/.other"
  create_symlink "$file_loc" "symlink_loc"
}

handle_existing_non_symlink() {
  file_loc="$1"
  symlink_loc="$2"

  echo "It seems like $symlink_loc already exists."
  read -p "Do you want to [d]elete, [m]ove (-> $HOME/.other/) or [k]eep $symlink_loc? " -n 1 -r
  if [[ $REPLY =~ ^[Dd]$ ]]
  then
    handle_delete_previous_file "$file_loc" "$symlink_loc"
  elif [[ $REPLY =~ ^[Mm]$ ]]; then
    handle_move_previous_file "$file_loc" "$symlink_loc"
  else
    printf "\\nKeeping %s...\\n" "$symlink_loc"
    return 0
  fi
}

handle_existing_file() {
  file_loc="$1"
  symlink_loc="$2"

  if is_symlink "$symlink_loc"; then
    handle_existing_symlink "$file_loc" "$symlink_loc"
  else
    handle_existing_non_symlink "$file_loc" "$symlink_loc"
  fi
}

custom_link() {
  file_loc="$1"
  symlink_loc="$2"

  if ! file_exists "$file_loc"; then
    invalid_file_error "$file_loc" "$symlink_loc"
  elif file_exists "$symlink_loc"; then
    handle_existing_file "$file_loc" "$symlink_loc"
  else
    symlink_dir=$(dirname "$symlink_loc")

    if ! is_directory "$symlink_loc"; then
      handle_non_existing_symlink_directory "$file_loc" "$symlink_loc"
    else
      create_symlink "$file_loc" "$symlink_loc"
    fi
  fi
}

custom_link "$HOME/.dotfiles/bash/.bash_profile" "$HOME/.bash_profile"
custom_link "$HOME/.dotfiles/bash/.bashrc" "$HOME/.bashrc"
custom_link "$HOME/.dotfiles/nvim/init.vim" "$HOME/.config/nvim/init.vim"
custom_link "$HOME/.dotfiles/tmux/.tmux.conf" "$HOME/.tmux.conf"

I'm not sure whether the outsourcing of that many methods makes sense/the code more readable. What do you think? How can I further improve my code?


texts: Function to produce unique random numbers

texts:
I've been learning Haskell for a few weeks after coming from a C# background. I've written a function to return a number of unique Ints from a specified range:

module MrKWatkins.Random (
    uniqueRandomInts
) where

import System.Random
import qualified Data.IntSet as I

uniqueRandomInts :: RandomGen g => (Int, Int) -> Int -> g -> ([Int], g)
uniqueRandomInts range@(min, max) n rng
    | n < 0             = error "n must be positive"
    | n > max - min + 1 = error "n is too large for range"
    | otherwise         = recursion n I.empty ([], rng)
    where
        recursion n used (xs, rng)
            | n == 0          = (xs, rng)
            | I.member x used = recursion n used (xs, rng')
            | otherwise       = recursion (n-1) (I.insert x used) (x:xs, rng')
            where
                (x, rng') = randomR range rng

Then to produce 5 numbers in the (inclusive) range 1 -> 10 the call would be something like:

uniqueRandomInts (1, 10) 5 $ mkStdGen 42

Firstly I have a few specific questions:

I've prefixed my module name with MrKWatkins to distinguish it as my module (much as I would with a namespace in C#). Is this common practice, or would I be better with a single word for the module name that is more descriptive?
I've done some pre-condition checking on the parameters, throwing exceptions if they're not satisfied. Is this common practice in Haskell, and is this the best way to do it?
I've used a nested function for the recursion. Would I be better off separating this out into a top level function that I don't export from the module?
I've reused some variable names in the recursion function, hiding the ones from the parent scope. Should I use different names instead?

On top of those if there is any advice on style, better ways to implement the above or just general advice would be greatly appreciated.


texts: Web API 2 Controller for third party services for multiple organizations

texts:
I'm putting together some RESTful services using ASP.NET Web API. This is the first time I have done this, so I'm looking for general feedback on this controller to make sure I'm not doing anything that doesn't make sense or that will be confusing to future maintainers of the code.

The factory is brought in using MEF, it's an already existing piece of code that just brings in any implementation of an interface that is available in the MEF container.

Imports System.Net
Imports System.Web.Http
Imports myContract
Imports System.ComponentModel.Composition

<Export>
Public Class OrgVendorServicesController
    Inherits ApiController

    <Import(GetType(IMySystemBusinessObjectFactory))>
    Private MySystemFactory As IMySystemBusinessObjectFactory

    ' GET api/OrgVendorServices
    Public Function GetAllOrgVendorServices() As IHttpActionResult
        Dim ovsColl As IOrgVendorServiceCollection = MySystemFactory.GetInstance(Of IOrgVendorServiceCollection)()
        ovsColl.ReadAll()
        Return Ok(ovsColl)
    End Function

    ' GET api/OrgVendorServices/5
    Public Function GetOrgVendorService(ByVal id As Integer) As IHttpActionResult
        Dim ovs As IMySystemOrgVendorService = MySystemFactory.GetInstance(Of IMySystemOrgVendorService)()
        ovs.OrgVendorServiceId = id
        ovs.Read()
        Return Ok(ovs)
    End Function

    Public Function GetCurrentOrgVendorServiceByServiceandOrg(legacyIdNumber As String, serviceId As String) As IHttpActionResult
        Return GetOrgVendorServiceByServiceandOrg(legacyIdNumber, serviceId, Nothing)
    End Function

    Public Function GetOrgVendorServiceByServiceandOrg(legacyIdNumber As String, serviceId As String, asOfDate As DateTime?) As IHttpActionResult
        Dim ovs As IMySystemOrgVendorService = MySystemFactory.GetInstance(Of IMySystemOrgVendorService)()
        legacyIdNumber = legacyIdNumber.Replace("-", "")
        If Not Regex.IsMatch(legacyIdNumber, "^\d{8}$") Then
            Return Content(HttpStatusCode.BadRequest, New With {.Message = String.Format("{0} is not a valid legacy Id number", legacyIdNumber)})
        End If
        ovs.ReadByServicelegacyIdNumberAndDate(legacyIdNumber, serviceId, asOfDate)
        If ovs Is Nothing Then
            Return Content(HttpStatusCode.NotFound, New With {.Message = String.Format("Vendor not found for {0} for service {1}", legacyIdNumber, serviceId)})
        End If
        Return Ok(ovs)
    End Function

    Public Sub PostOrgVendorService(<FromBody()> ByVal value As IOrgVendorService)
        Dim ovs As IMySystemOrgVendorService = MySystemFactory.GetInstance(Of IMySystemOrgVendorService)()
        ovs.OrgVendorServiceId = value.OrgVendorServiceId
        ovs.Read()
        ovs.Refresh(value)
        ovs.Save()
    End Sub

    Public Sub PutOrgVendorService(ByVal id As Integer, <FromBody()> ByVal value As IOrgVendorService)
        Dim ovs As IMySystemOrgVendorService = MySystemFactory.GetInstance(Of IMySystemOrgVendorService)()
        ovs.OrgVendorServiceId = id
        ovs.Read()
        ovs.Refresh(value)
        ovs.Save()
    End Sub

    Public Sub DeleteOrgVendorService(ByVal id As Integer)
        Dim ovs As IMySystemOrgVendorService = MySystemFactory.GetInstance(Of IMySystemOrgVendorService)()
        ovs.OrgVendorServiceId = id
        ovs.DELETE()
    End Sub
End Class


texts: Reading separate components of 8.3 filename into proper filename in C

texts:
I need to read an archive file format which stores filenames as 8 characters for the name (null-terminated if less than 8 characters, not otherwise), immediately followed by 3 characters for the extension (i.e. without a dot). So basically, I need to read the components and add a dot between the name and extension (name.ext).

Is this the way to go, or is there a better/more common way of doing it?

#include <stdio.h>  // (f)printf, fopen, fseek, ftell, fread, fclose
#include <stdlib.h> // calloc, free

void read_filename(FILE *arc, char *filename)
{
    // read file name
    if(8 != fread(&filename[0], 1, 8, arc))
    {
        fprintf(stderr, "ERROR: Failed reading file name at 0x%08X\n", ftell(arc));
        exit(EXIT_FAILURE);
    }

    // find the "real" end of the name and append a dot
    int c;
    for(c=0; c < 8 && filename[c] != '\0'; c++);
    filename[c] = '.';

    // read extension into the offset of the dot + 1
    if(3 != fread(&filename[c+1], 1, 3, arc))
    {
        fprintf(stderr, "ERROR: Failed reading file extension at 0x%08X\n", ftell(arc));
        exit(EXIT_FAILURE);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2) return 1;

    // open the archive
    FILE *arc = fopen(argv[1], "rb");
    if(arc==NULL)
    {
        fprintf(stderr, "ERROR: Could not open file.\n");
        exit(EXIT_FAILURE);
    }

    // seek to 0x28, which is the offset of the first filename
    fseek(arc, 0x28, SEEK_SET);

    // allocate cleared memory for the file name
    char *filename = (char *)calloc(12, 1);

    // read the file name into the memory block allocated
    read_filename(arc, filename);

    printf("First filename: %s...", filename);

    free(filename);
    fclose(arc);

    return 0;
}

An example of a filename might look like this (hex dump):

0x00000028   46 49 4C 45 4E 41 4D 00 65 78 74 00   FILENAM ext

the space in the example above is a null byte.

or it can look like this:

0x00000028   46 49 4C 45 4E 41 4D 45 65 78 74 00   FILENAMEext

in this example there is no null terminator for the name -- as mentioned before, the extension always immediately follows the first 8 bytes.


texts:
I've created a mini project where the user will enter the total weight of the coins and the program will compute how many coins they have and how many wrappers they'll need. I initially found this challenge in a subreddit named r/beginnerprojects

def coinEstimator():

    ##########################################
    # Intro text                        ######
    ##########################################

    print("Welcome to the coin estimator.")
    print("Please enter the type of coins: ")
    print("1. Cent")
    print("2. Nickel")
    print("3. Dime")
    print("4. Quarter")

    ##############################################
    # Setting up variables for the user's input ##
    ##############################################

    userChoose = int(input("Enter: "))

    ##############################################################
    # Conditionals for different types of coin the user wants.  ##
    ##############################################################

    if userChoose == 1:             # Conditionals for Cents
        totalWeight = float(input("What is the total weight of your cents in grams?\n"))

        (cointValue, dimeWrapper) = cointEstSol(totalWeight, "Cent")

        print("The total cents you have is {0}. You need {1} wrapper(s)".format(cointValue, dimeWrapper))

    elif userChoose == 2:           # Conditionals for Nickel
        totalWeight = float(input("What is the total weight of your nickels in grams?\n"))

        (cointValue, dimeWrapper) = cointEstSol(totalWeight, "Nickel")

        print("The total nickels you have is {0}. You need {1} wrapper(s)".format(cointValue, dimeWrapper))

    elif userChoose == 3:           # Conditionals for Dime
        totalWeight = float(input("What is the total weight of your dimes in grams?\n"))

        (cointValue, dimeWrapper) = cointEstSol(totalWeight, "Dime")

        print("The total dimes you have is {0}. You need {1} wrapper(s)".format(cointValue, dimeWrapper))

    elif userChoose == 4:           # Conditionals for Quarter
        totalWeight = float(input("What is the total weight of your quarters in grams?\n"))

        (cointValue, dimeWrapper) = cointEstSol(totalWeight, "Quarter")

        print("The total quarters you have is {0}. You need {1} wrapper(s)".format(cointValue, dimeWrapper))

def cointEstSol(weight, coins):

    ########################################################
    ## Setting up variables for the solution of coins    ###
    ########################################################

    coinWeight = {"Cent": 126, "Nickel": 199, "Dime": 113, "Quarter": 226}     # Dictionary for the different weights of coins
    coinCountWrap = {"Cent": 50, "Nickel": 40, "Dime": 50, "Quarter": 40}      # Dictionary for the amount of coins that can be put in a wrapper

    cointValue = weight // coinWeight[coins]                                   # Solution to compute how many coins we have

    if cointValue < coinCountWrap[coins]:                                      # Conditionals for how many wrappers would be needed.
        coinWrapper = 1
    else:
        coinWrapper = cointValue // 50
        coinWrapper += 1

    return (cointValue, coinWrapper)                                           # Returning the total amount of coins and wrapper

coinEstimator()

Please tell me what areas i need to improve. As you can see my code is crude and was not beautifully written.

Honest review would be needed. Any shortcuts, codes that need amendments or just a way to improve this code would be appreciated.

Extra inquiry:
Although i don't think this would be the appropriate place to ask this questions but i want this to be made as object oriented programming approach. I don't know how, so if you guys can convert this code to OOP, that would be great. I wanted to know how python experts would approach this in an OOP style. It's okay if you don't answer this.


texts: Parsing HTML knock-off for answering queries for values

texts:
I wrote a code to parse an HTML knock-off from HackerRank, and I would like a review. Mostly I hope to get better at STL and code style. But any tips would be very welcome.

Sample input that I would read from cin to parse and answer queries:

  4 3
  <tag1 value = "HelloWorld">
  <tag2 name = "Name1">
  </tag2>
  </tag1>
  tag1.tag2~name
  tag1~name
  tag1~value

My code:

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <iterator>

int main() {
    std::string scope, cin_buffer, name;
    std::string::iterator strg_it;
    int lines, querrys;
    std::map<std::string,std::string> variables;

    std::cin >> cin_buffer;
    lines = atoi(cin_buffer.c_str());
    std::cin >> cin_buffer;
    querrys = atoi(cin_buffer.c_str());

    for (int lines_processed=0; lines_processed<lines; ++lines_processed){
        std::cin >> std::ws;
        while (std::cin.peek()!= '\n'){
            std::cin >> cin_buffer;
            if (cin_buffer.at(0)=='<' && cin_buffer.at(1)!='/'){
                strg_it = remove_if( begin(cin_buffer), end(cin_buffer),
                                    [](unsigned char c){return c=='<' || c=='>';});
                cin_buffer.erase(strg_it, end(cin_buffer));
                if (scope.length()>0){
                    scope += "." + cin_buffer;
                }else{
                    scope = cin_buffer;
                }
            }else if (cin_buffer.at(0)=='<' && cin_buffer.at(1)=='/'){
                int length_to_erase = (scope.length())-(cin_buffer.length()-3);
                scope.erase(length_to_erase);
                if (scope.back()=='.'){
                    scope.erase(scope.length()-1);
                }
            }else{
                name = scope + "~" + cin_buffer;
                std::cin >> cin_buffer;
                std::cin >> cin_buffer;
                strg_it = remove_if( begin(cin_buffer), end(cin_buffer),
                                    [](unsigned char c){return c=='"' || c=='>';} );
                cin_buffer.erase(strg_it, end(cin_buffer));
                variables[name]=cin_buffer;
            }
        }
    }

    for (int querry_number=0; querry_number<querrys; ++querry_number){
        std::cin >> cin_buffer;
        if (variables.find(cin_buffer)!=end(variables)){
            std::cout << variables[cin_buffer] << std::endl;
        }else{
            std::cout << "Not Found!" << std::endl;
        }
    }
    return 0;
}


texts: Restricting search to a user's own department, if the user is not a manager

texts:
I hate having almost two identical blocks do almost the exact same thing.

I am working with Entity Framework 4.4.0.0
Asp.Net MVC

Right now if the user is a "manager" I want to show them the entire list, if they are a normal user or a Team Lead.  I only want to show them their specific department.  The only different from both model is that one add's a where and the other does not.

public ActionResult Index()
{
    AD_CurrentUserProfile currentUP = new ActiveDirectory().GetUserProfile(User.Identity.Name.Split("\\".ToCharArray())[1].ToString());

    IQueryable<IPACS_DT_MasterList> model;

    if (currentUP.currentUser.isManager)
    {
        model = (from d in db.IPACS_Department
                        join f in db.IPACS_Function on d.departmentID equals f.departmentID
                        join pg in db.IPACS_Process on f.functionID equals pg.functionID
                        join sop in db.IPACS_Procedure on pg.processID equals sop.processID
                        select new IPACS_DT_MasterList
                        {
                            departmentID = d.departmentID,
                            functionID = f.functionID,
                            processID = pg.processID,
                            procedureID = sop.procedureID,
                            departmentName = d.name,
                            functionName = f.name,
                            processName = pg.name,
                            procedureName = sop.name,
                            owner = sop.owner
                        });
    }
    else
    {
        model = (from d in db.IPACS_Department
                        where d.name == currentUP.currentUser.department // only change
                        join f in db.IPACS_Function on d.departmentID equals f.departmentID
                        join pg in db.IPACS_Process on f.functionID equals pg.functionID
                        join sop in db.IPACS_Procedure on pg.processID equals sop.processID
                        select new IPACS_DT_MasterList
                        {
                            departmentID = d.departmentID,
                            functionID = f.functionID,
                            processID = pg.processID,
                            procedureID = sop.procedureID,
                            departmentName = d.name,
                            functionName = f.name,
                            processName = pg.name,
                            procedureName = sop.name,
                            owner = sop.owner
                        });
    }

    return View(model);
}


texts: Resolve alias' original item using bookmarkData

texts:
This is my first Objective-C++ code, so I'm a bit lacking in the knowledge of methods.

I need to resolve a macOS alias and get its original location. I have access to the C string, which is the file path (in a human readable form). It also needs to be verified in this code itself that it is a true alias, and contains bookmark data.

const char *class::resolveAliasFromURL(const char *filepath) const{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    char filepath[] = "/Users/me/alias"; /*you need to make an alias here*/
    NSError *error = nil;
    NSString *string = [[NSString alloc] initWithUTF8String:filepath];
    NSURL *url = [NSURL fileURLWithPath:string];
    NSData *bmdata = [NSURL bookmarkDataWithContentsOfURL:url error:&error];
    if (!error) { /*needs better error catching*/
        NSLog(@"Error: %@",error);
    }
    else {
        NSLog(@"URL: %@",url); // Useless; sanity check
    }

    error = nil;
    BOOL isstale = NO;
    BOOL *isStalePointer = &isstale;
    char ref[] = "";
    NSString *relString = [[NSString alloc] initWithUTF8String:ref];
    NSURL *relativeURL = [NSURL URLWithString:relString];
    NSURLBookmarkResolutionOptions option = NSURLBookmarkResolutionWithoutUI;
    NSURL *actual = [[NSURL alloc]
        initByResolvingBookmarkData:bookmarkData
                            options:option
                      relativeToURL:relativeURL
                bookmarkDataIsStale:isStalePointer
                              error:&error]; /*resolved NSURL object file://<some numbers>*/

    char resolved[100]; /*resolved path in C; need to get length of the string, not arbitrarily 100 */
    strcpy(resolved, [actual fileSystemRepresentation]);
    printf(" %s\n",resolved);

    /*Need to check if the resolved object is a file or a directory*/

    [pool drain];
    return tempPath;
}

bookmarkDataWithContentsOfURL:

+ (NSData *)bookmarkDataWithContentsOfURL:(NSURL *)bookmarkFileURL
                                    error:(NSError * _Nullable *)error;

initByResolvingBookmarkData

- (instancetype)initByResolvingBookmarkData:(NSData *)bookmarkData
                                    options:(NSURLBookmarkResolutionOptions)options
                              relativeToURL:(NSURL *)relativeURL
                        bookmarkDataIsStale:(BOOL *)isStale
                                      error:(NSError * _Nullable *)error;

Is there some improvements I can make given the goal and constraints?


texts: Displaying pagination links, maybe with links to first and last page

texts:
I've been researching if this is possible, but I've drawn a blank, I'm wondering if it's possible to optimize these for and if statements together?

<?php
// calculate total number of pages
$total_pages = ceil($total_rows / $records_per_page);

// range of links to show
$range = 2;

// display links to 'range of pages' around 'current page'
$initial_num = $page - $range;
$condition_limit_num = ($page + $range)  + 1;
?>

<?php if ($page>1) : ?>

            <a href='<?php echo $page_url; ?>' title='Go to the first page.'>
                First Page

<?php endif; ?>

<?php
for ($x = $initial_num; $x<$condition_limit_num; $x++) :
    if (($x > 0) && ($x <= $total_pages)) :
        if ($x == $page) : ?>

            <?php echo $x; ?> (current)

        <?php else : ?>

            <a href='<?php echo $page_url; ?>page=<?php echo $x; ?>'><?php echo $x; ?>

        <?php
        endif;
    endif;
endfor;
?>

<?php if ($page<$total_pages) : ?>

            <a href='<?php echo $page_url; ?>page=<?php echo $total_pages; ?>' title='Last page is <?php echo $total_pages; ?>'>
                Last Page

<?php endif; ?>


texts:
I created a simple app with Backbone and Marionette. In a view I created an onRender function.
    I created a page that displays a Report with a date filter, using a select tag and affect to an input when the select tag is chosen.
    I made that with Backbone and JQuery. And for date I'm using Moment.js and Pikaday.js.

This is a part of my code

var selectdate = $('#publicdate',this.el)[0];
selectdate.addEventListener("change",function(){
    var value = selectdate.value;
    var date1 = $('#date1',this.el)[0];
    var date2 = $('#date2',this.el)[0];
    if(value==="today"){
        date1.value = moment().add('days').format('DD-MM-YYYY')
        date2.value = moment().add('days').format('DD-MM-YYYY')
        $(date1).attr('disabled',true);
        $(date2).attr('disabled',true);
    } else if(value==="yesterday"){
        date1.value = moment().add(-1,'days').format('DD-MM-YYYY')
        date2.value = moment().add(-1,'days').format('DD-MM-YYYY')
        $(date1).attr('disabled',true);
        $(date2).attr('disabled',true);
    } else if(value==="thismonth"){
        date1.value = moment().add('month').startOf('month').format('DD-MM-YYYY')
        date2.value = moment().add('month').endOf('month').format('DD-MM-YYYY')

        $(date1).removeAttr('disabled',true);
        $(date2).removeAttr('disabled',true);
    } else if(value==="lastmonth"){
        date1.value = moment().add(-1,'month').startOf('month').format('DD-MM-YYYY')
        date2.value = moment().add(-1,'month').endOf('month').format('DD-MM-YYYY')
        $(date1).attr('disabled',true);
        $(date2).attr('disabled',true);
    }
})

Is that code is already clean? Is there another way to make that code shorter? Like using a function or something.


texts: My implementation of the Union-Find data structure in MATLAB

texts:
I was assigned the connected components labeling (CCL) algorithm and in order to implement the CCL algorithm I first had to implement the Union-Find algorithm.

This is my try at it, any review and tip would be greatly appreciated

classdef UnionFind < handle
   properties
       PARENT = containers.Map('KeyType', 'double', 'ValueType','any');
   end
   methods
       % Constructor Function
%        function obj = UnionFind(items)
%            for i = 1:5
%                obj.PARENT(items(i)) = items(i);
%            end
%        end
       % Add Item Function
       function addItem(obj, itemToAdd)
          obj.PARENT(itemToAdd) = itemToAdd;
       end
       % Find Function
       function root = Find(obj, itemToFind)
          while (obj.PARENT(itemToFind) ~= itemToFind)
             obj.PARENT(itemToFind) = obj.PARENT(obj.PARENT(itemToFind));
             itemToFind = obj.PARENT(itemToFind);
          end
          root = itemToFind;
       end
       % Union Function
       function Union(obj, setOne, setTwo)
          obj.PARENT(setOne) = setTwo;
       end
   end
end


texts: Extract specified field value from filename using positional indexing

texts:
I have some filenames, and they each have data contained in them at specific locations in the string. I want a function that returns the value of the data specified by field. The doctest illustrates.

I'd like a nicer, easier-to-understand way to do this.

If possible, but secondarily, I'd like to be able to give the data in different types, according to which field they are, rather than just the string value.

def get_field_posn_list(field):
    """List containing field position indices in filename"""
    return({'place': [-11],
            'year': range(-10, -7),
            'session': [-6]}[field])

def get_field_str(fn, field):
    """Get the string value of field stored in string fn
    >>> get_field_str('/path/to/file/Z998-5.asdf', 'session')
    '5'
    """
    val = ''.join([fn[i] for i in get_field_posn_list(field)])
    return val


texts: Python decorator to support static properties

texts:
Classes in Python do not have native support for static properties. A meta-class can rather easily add this support as shown below. Are there any problems programmers might experience if they use this implementation?

#! /usr/bin/env python3
class StaticProperty(type):
    def __getattribute__(cls, name):
        attribute = super().__getattribute__(name)
        try:
            return attribute.__get__(cls, type(cls))
        except AttributeError:
            return attribute

    def __setattr__(cls, name, value):
        try:
            super().__getattribute__(name).__set__(cls, value)
        except AttributeError:
            super().__setattr__(name, value)

class Test(metaclass=StaticProperty):
    __static_variable = None

    @property
    def static_variable(cls):
        assert isinstance(cls, StaticProperty)
        return cls.__static_variable

    @static_variable.setter
    def static_variable(cls, value):
        assert isinstance(cls, StaticProperty)
        cls.__static_variable = value

    def __init__(self):
        self.__value = None

    @property
    def value(self):
        assert isinstance(self, Test)
        return self.__value

    @value.setter
    def value(self, value):
        assert isinstance(self, Test)
        self.__value = value

def main():
    print(repr(Test.static_variable))
    Test.static_variable = '1st Hello, world!'
    print(repr(Test.static_variable))

    instance = Test()
    print(repr(instance.value))
    instance.value = '2nd Hello, world!'
    print(repr(instance.value))

    assert Test._Test__static_variable == '1st Hello, world!'
    assert instance._Test__value == '2nd Hello, world!'

if __name__ == '__main__':
    main()

My first inclination is that the property class should be sub-classed as static_property and should be checked for in StaticProperty.__new__ to ensure it is being used properly.