texts:
I would like to define some constant sequences (of bytes, specifically) in my C# library/API. Both length and content should not vary, preferably by any means (barring reflection). To this end, a byte[] array would not be sufficient, and a ReadOnlyCollection<T> can still be mutated. I have not done a full comparison yet, but this effort may be re-inventing ImmutableList<T>, in which case I would still appreciate feedback on the successes and weaknesses of this implementation. To be precise, this class is meant to be inherited by multiple derived classes, which actually define the constants.

Design & Style

I have chosen to build this class on the most primitive interface (IEnumerable<T>) that I could; partially to preserve maximal compatibility, and partially to avoid having to hide or throw NotSupportedException for certain ICollection<T> methods and such. Does this have any drawbacks?
The actual collection that contains the items is a private List<byte>.
I have implemented a couple convenience fields, AsString, Count, and Length (Length feels more appropriate for the type, but the existence of the Count<> LINQ extension made me feel both should be included for consistency). I considered get-only properties, however, this Q&A on SO points out that readonly is a more explicit modifier. Are there other pros/cons that I am missing in this specific case?
Given that I only intend to derive this class, I could mark it abstract, but could I also build it as an interface? (This would affect the readonly/get-only decision.) However, stylistically, it feels like derived classes should have an "is-a" relationship with Bytes rather than a "can-do".
I have omitted all namespace qualifiers here, as seems to be the standard in C#. However, I come mostly from Python, and global imports and polluting the global namespace are almost unbearable to me. I also don't want to see System.Collections.Generic.[...] everywhere; is it an acceptable compromise to use, for example, using CollectionsGen = System.Collections.Generic, or would this horrify C# programmers reading my code?

Code

/// <summary>
/// Implementation of an immutable collection of bytes, with some extras.
/// </summary>
public class Bytes : IEnumerable<byte>
{
    private List<byte> bytesList;
    public readonly string AsString;
    public readonly int    Count;
    public readonly int    Length; // just a synonym for Count

    // accepts values from -Length to Length-1 (similar to Python indexing).
    public byte this[int i] { get { return this.bytesList[ i>=0 ? i : i+this.Length ]; } }

    public Bytes(IEnumerable<byte> bytes)
    {
        this.bytesList = new List<byte>(bytes);
        this.AsString  = string.Join(" ", this.Select(b => $"0x{b:X2}"));
        this.Count     = this.bytesList.Count;
        this.Length    = this.Count;
    }

    public IEnumerator<byte> GetEnumerator() { return this.bytesList.GetEnumerator(); }

    IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); }

I think could generalize this to any type by defining public class MyImmutableCollection<T> : IEnumerable<T> with roughly the same body, but I have no need for that now.

Usage

var byteArray = new byte[] { 0x01, 0x02, 0x03 };
var bytesInst = new Bytes(byteArray);
byteArray[1] = 0xFF;
// observe that byteArray has changed, where bytesInst has not.
bytesInst[1] = 0xFF; // correctly generates a read-only compiler error


texts: ReentrantLock with priorities for waiting threads

texts:
I am trying to have a ReentrantLock with another way to determinate which thread will have the lock in the waiting queue. ReentrantLock implementation manages a Fair/Unfair policy, that's not what I want.

I would like to give a priority when I call the .lock() method, and this priority will determinate the order of current thread in the waiting threads queue.

I wrote a class, based on a PriorityBlockingQueue, and I'd like your opinion.

import java.util.Date;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Class to lock a resource.
 * When multiple threads are waiting for the resource to be unlocked, the one with the greatest priority will have the resource.
 * When two threads have the same priority, the first added thread will lock the resource.
 *
 */
public class PrioritizedLock {

  private PriorityBlockingQueue<PrioritizedThread> waitingQueue = new PriorityBlockingQueue<PrioritizedThread>();

  private volatile PrioritizedThread activeThread;

  private volatile Object syncStartNext = new Object();

  private volatile boolean shutdown = false;

  public PrioritizedLock() {
    startQueueWatcher();
  }

  /**
   * Starts a queue watcher, which takes PrioritizedThread from the PriorityBlockingQueue and notify them to wake them up.
   */
  private void startQueueWatcher() {
    new Thread(new Runnable() {

      @Override
      public void run() {
        while (!shutdown) {

          /*
           * Wait until a PrioritizedThread is added to the PriorityBlockingQueue
           */
          while (activeThread == null) {
            try {
              activeThread = waitingQueue.take();
            } catch (InterruptedException e1) {
              //
            }
          }

          /*
           * Notify the thread to wake up (now it has locked the resource)
           */
          synchronized (activeThread) {
            activeThread.notify();
          }

          /*
           * Wait until the resource has been released from the active thread
           */
          while (activeThread != null) {
            synchronized (syncStartNext) {
              try {
                syncStartNext.wait();
              } catch (InterruptedException e) {
                //
              }
            }
          }

        }
      }
    }).start();
  }

  /**
   * Waits until the thread is woken up by the Queue Watcher thread
   * @param thread
   */
  private void wait(PrioritizedThread thread) {
    synchronized (thread) {

      while (activeThread != thread) {
        try {
          thread.wait();
        } catch (InterruptedException e) {
          //
        }

      }
    }

  }

  static class PrioritizedThread implements Comparable<PrioritizedThread> {
    Thread thread;

    int priority;

    Date date = new Date();

    public PrioritizedThread(Thread aThread, int aPriority) {
      thread = aThread;
      priority = aPriority;
    }

    @Override
    public int compareTo(PrioritizedThread other) {
      int diffPriorities = this.priority - other.priority;

      if (diffPriorities == 0) {
        return date.compareTo(other.date);
      }
      return diffPriorities;
    }
  }

  /**
   * Waits until the resource is locked by the current thread
   * @param priority Priority of the lock, the less has the greatest priority
   */
  public void lock(int priority) {
    PrioritizedThread prioritizedThread = new PrioritizedThread(Thread.currentThread(), priority);

    waitingQueue.add(prioritizedThread);
    wait(prioritizedThread);
  }

  /**
   * Unlock the resource
   */
  public void unlock() {
    activeThread = null;

    synchronized (syncStartNext) {
      syncStartNext.notify();
    }
  }

  /**
   * Trigger a shutdown of the lock,
   */
  public void shutdown() {
    shutdown = true;
  }

}


texts:
I'm updating and old project from jQuery 1.4 to jQuery 1.7.

Can this be simplified, thus reducing the amount of code, and perhaps in such reduction, have it improved?

Having the following code:

var cartItemDel   = '<input type="hidden" class="lid" name="lineID'+ id +'" value="'+ id +'">'+token+'	',
    cartItemName  = '<input class="CartItemId" type="hidden" name="id_'+ id +'" value="'+ id +'">'+ name +'	',
    cartItemPrice = '<input class="CartItemRef" type="hidden" name="ref_'+ ref +'" value="'+ ref +'">'+ price +'&euro;	';

$(".cart-table tbody")
    .append('
'+cartItemDel+cartItemName+cartItemPrice+'
');

I've updated it to:

/*
 * ADD NEW LINE - First TD
 */
var $newLineIcon = $("", {
        src    : "components/themes/default/img/icons/cross-small.png",
        width  : "16",
        height : "16",
        alt    : "X"
    });

var $newLineLID = $("<input/>", {
        type  : "hidden",
        class : "lid",
        name  : "lineID"+ lid,
        value : lid
    });

var $newLineToken = $("", {
        class : "hidden token",
        text  : token
    });

var $newLine_firstTD = $("", { class : "del"})
    .append($newLineIcon)
    .append($newLineLID)
    .append($newLineToken);

/*
 * ADD NEW LINE - Second TD
 */
var $newLinePID = $("<input/>", {
        type  : "hidden",
        class : "CartItemId",
        name  : "id_"+ id,
        value : id
    });

var $newLinePNAME = $("", {
        class : "CartItemName",
        text  : name
    });

var $newLine_secondTD = $("")
    .append($newLinePID)
    .append($newLinePNAME);

/*
 * ADD NEW LINE - Third TD
 */
var $newLinePREF = $("<input/>", {
        type  : "hidden",
        class : "CartItemRef",
        name  : "ref_"+ ref,
        value : ref
    });

var $newLinePPRICE = $("", {
        class : "CartItemPrice",
        html  : "&euro;"
    })
    .prepend($("", {class : "lineSum", text : price}));

var $newLine_thirdTD = $("")
    .append($newLinePREF)
    .append($newLinePPRICE);

$("
")
    .append($newLine_firstTD)
    .append($newLine_secondTD)
    .append($newLine_thirdTD)
    .appendTo($(".cart-table tbody"));


texts:
From K&R exercise 1-23,

  Write a program to remove all comments from a C program. Don't forget
  to handle quoted strings and character constants properly. C comments
  don't nest.

My solution,

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

#define MAXLEN  10000   // max input length

int      get_input(char input[], int maxlen);
char * no_comments(char input[], int len);

_Bool comment_start(char input[], int idx);
_Bool   comment_end(char input[], int idx, char *comments, int cdx);

_Bool quote_start(char input[], int idx);
_Bool   quote_end(char input[], int idx);

int main(void)
{
    char input[MAXLEN];
    int len = get_input(input, MAXLEN);
    char *scrubbed = no_comments(input, len);

    printf("%s", scrubbed);
    free(scrubbed);
}

int get_input(char input[], int maxlen)
{
    int i;
    char c;

    for (i = 0; i < maxlen-1 && (c = getchar()) != EOF; i++) {
        input[i] = c;
    }
    input[++i] = '\0';

    return i;
}

char * no_comments(char input[], int len)
{
    char *scrubbed = (char *) malloc((len+1) * sizeof(char));
    int sdx = 0;    // index

    char *comments = (char *) malloc((len+1) * sizeof(char));
    comments[0] = '\0';
    int cdx = 0;    // index

    _Bool quoted = 0;

    for (int idx = 0; idx <= len; idx++) {
        if (strlen(comments) == 0) { // outside comment

            if (!quoted && comment_start(input, idx)) {
                comments[cdx++] = input[idx];
            } else {
                scrubbed[sdx++] = input[idx];
            }

            if (quoted && quote_end(input, idx)) {
                quoted = 0;
            } else if (!quoted && quote_start(input, idx)) {
                quoted = 1;
            }

        } else { // inside comment

            if (comment_end(input, idx, comments, cdx)) {
                comments[0] = '\0'; // exit comment
                cdx = 0;
            } else {
                comments[cdx++] = input[idx];
            }
        }
    }
    free(comments);

    return scrubbed;
}

_Bool comment_start(char input[], int idx)
{
    char nxt = input[idx+1];

    return input[idx] == '/' && (nxt == '*' || nxt == '/');
}

_Bool comment_end(char input[], int idx, char *comments, int cdx)
{
    char prev = comments[cdx-1];
    char cur  = input[idx];
    char nxt  = input[idx+1];

    _Bool new_style = (cdx == 1 && cur == '/') || (cdx > 1 && comments[1] == '/');
    _Bool old_style = (cdx == 1 && cur == '*') || (cdx > 1 && comments[1] == '*');

    return (new_style && nxt == '\n') || (old_style && cdx > 2 && prev == '*' && cur == '/');
}

_Bool quote_start(char input[], int idx)
{
    return input[idx] == '"' && input[idx-1] != '\'';
}

_Bool quote_end(char input[], int idx)
{
    return input[idx] == '"' && input[idx-1] != '\\';
}


texts: Checking convergence of 2-layer neural network in python

texts:
I am working with the following code:

import numpy as np

def sigmoid(x):
    return 1.0/(1.0 + np.exp(-x))

def sigmoid_prime(x):
    return sigmoid(x)*(1.0-sigmoid(x))

def tanh(x):
    return np.tanh(x)

def tanh_prime(x):
    return 1.0 - x**2

class NeuralNetwork:

    def __init__(self, layers, activation='tanh'):
        if activation == 'sigmoid':
            self.activation = sigmoid
            self.activation_prime = sigmoid_prime
        elif activation == 'tanh':
            self.activation = tanh
            self.activation_prime = tanh_prime

        # Set weights
        self.weights = []
        # layers = [2,2,1]
        # range of weight values (-1,1)
        # input and hidden layers - random((2+1, 2+1)) : 3 x 3
        for i in range(1, len(layers) - 1):
            r = 2*np.random.random((layers[i-1] + 1, layers[i] + 1)) -1
            self.weights.append(r)
        # output layer - random((2+1, 1)) : 3 x 1
        r = 2*np.random.random( (layers[i] + 1, layers[i+1])) - 1
        self.weights.append(r)

    def fit(self, X, y, learning_rate=0.2, epochs=100000):
        # Add column of ones to X
        # This is to add the bias unit to the input layer
        ones = np.atleast_2d(np.ones(X.shape[0]))
        X = np.concatenate((ones.T, X), axis=1)

        for k in range(epochs):
            if k % 10000 == 0: print 'epochs:', k

            i = np.random.randint(X.shape[0])
            a = [X[i]]

            for l in range(len(self.weights)):
                    dot_value = np.dot(a[l], self.weights[l])
                    activation = self.activation(dot_value)
                    a.append(activation)
            # output layer
            error = y[i] - a[-1]
            deltas = [error * self.activation_prime(a[-1])]

            # we need to begin at the second to last layer
            # (a layer before the output layer)
            for l in range(len(a) - 2, 0, -1):
                deltas.append(deltas[-1].dot(self.weights[l].T)*self.activation_prime(a[l]))

            # reverse
            # [level3(output)->level2(hidden)]  => [level2(hidden)->level3(output)]
            deltas.reverse()

            # backpropagation
            # 1. Multiply its output delta and input activation
            #    to get the gradient of the weight.
            # 2. Subtract a ratio (percentage) of the gradient from the weight.
            for i in range(len(self.weights)):
                layer = np.atleast_2d(a[i])
                delta = np.atleast_2d(deltas[i])
                self.weights[i] += learning_rate * layer.T.dot(delta)

    def predict(self, x):
        a = np.concatenate((np.ones(1).T, np.array(x)), axis=0)
        for l in range(0, len(self.weights)):
            a = self.activation(np.dot(a, self.weights[l]))
        return a

if __name__ == '__main__':

    nn = NeuralNetwork([2,2,1])

    X = np.array([[0, 0],
                  [0, 1],
                  [1, 0],
                  [1, 1]])

    y = np.array([0, 1, 1, 0])

    nn.fit(X, y)

    for e in X:
        print(e,nn.predict(e))

While this converges well and fast when using the tanh, it does converge much slower when using the sigmoid ( in def __init__(self, layers, activation='tanh') change tanh to sigmoid ).
I cannot find why that is. How do I improve the implementation for the sigmoid?


texts:
I've built simple math expression facet which ignores any character except numbers and operators listed below:

  plus, minus, multiply, divide, degree, left bracket, right bracket, assignment

I'm worrying about hardcoded values of the operators and numbers. I believe that loop from '0' to '9' will not fail since most compilers use ASCII. Despite that, it would be great to make the code more portable.

Is there any opportunity to improve performance? It seems like control over performance is at standard library implementation.

Note that instance of ignore_punctuation doesn't leak due to wording of facet library.

Code and use case:

#include <iostream>
#include <locale>
#include <sstream>
#include <vector>

struct ignore_punctuation :std::ctype<char>
{
    static const mask* make_table()
    {
        static std::vector<mask> v(classic_table(), classic_table() + table_size);
        for (auto& elem : v)
        {
            elem |= blank;
        }

        for (auto c = '0'; c <= '9'; ++c)
        {
            v[c] &= ~blank;
        }

        v['+'] &= ~blank;
        v['-'] &= ~blank;
        v['*'] &= ~blank;
        v['/'] &= ~blank;
        v['='] &= ~blank;
        v['^'] &= ~blank;
        v['('] &= ~blank;
        v[')'] &= ~blank;

        return &v.front();
    }

    ignore_punctuation(std::size_t refs = 0) : ctype(make_table(), false, refs) {}
};

int main()
{
    std::string s = "a+(7+1)+5-9=11ssd";

    std::istringstream input(s);
    input.imbue(std::locale(input.getloc(), new ignore_punctuation));

    std::string token;
    while (input >> token)
    {
        std::cout << token;
    }
}


texts: Python algorithm mimicking mark/sweep garbage collection

texts:
I don't have much experience with Python and would love some feedback on my implementation of this program.

I am given a file with an integer representing a number of memory-cells, followed by a list of ordered pairs representing links between either a pointer and a memory-cell, or memory-cell and a memory-cell. You could use the list to draw diagram akin to those used in text-book "which cells are marked and which are reclaimed" problems regarding mark/sweep GC.

I was tasked with creating a Python script that takes in such a list, and runs a simulated mark/sweep on it and my solution (below) is fully functional.

Here's an example input file:

6
ptr1,0
0,1
1,2
ptr2,3
3,2
4,5

And here is the script:

import sys
import re

def RepresentsInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

#recursive function that traces through a mem-node structure
#setting each node's check_flag to 1 if traversed
def node_trace(pointer, node_pointer_list, nodes_dict):
    if RepresentsInt(pointer[0]):
        if nodes_dict[pointer[0]][1] == 1:
            #returns if the current node has been traversed already
            return
        else:
            #checks the current node as marked and traversed
            nodes_dict[pointer[0]][0] = 1
            nodes_dict[pointer[0]][1] = 1

    for x in node_pointer_list:
    #recurs for each node the current node points to
        if x[0] == pointer[1] and nodes_dict[x[0]][1] == 0:
            node_trace(x, node_pointer_list, nodes_dict)

        #catches the node at the end of a chain
        if RepresentsInt(x[0]):
            if nodes_dict[x[0]][1] == 1:
                nodes_dict[x[1]][0] = 1
                nodes_dict[x[1]][1] = 1
        else:
        #catches a single-link chain from a variable to a mem-block
            nodes_dict[x[1]][0] = 1
            nodes_dict[x[1]][1] = 1

sysArgs = list(sys.argv)
inputFile = sysArgs[1]
inFile = open(inputFile)
node_pointer_list = []
nodes_dict_0 = {}      #contains node records of the format, ['mem-cell': traversed_flag, marked_flag]
                       #traversed/marked _flag is 0 if unchecked, 1 if checked

#read, parse, and store the contents of the input file
node_count = 0
for line in inFile:
    #grabs the number of nodes which is stored in the first line of the file
    if node_count == 0:
        node_count = int(line)
    else:
        #read and parse a line as required
        splitLine = line.rstrip()
        splitLine = re.split(r'[,]', splitLine)

        node_pointer_list.append([splitLine[0], splitLine[1]])

#create a dictionary for all nodes, with flags for "checked" and "traversed"
#initialized to 0
count = 0
while count < node_count:
    nodes_dict_0[str(count)] = [0, 0]
    count += 1

#simulates the mark phase of a mark-sweep algorithm using the
#reference structure described in the input file
for item in node_pointer_list:
    if not RepresentsInt(item[0]):
        #if the link begins with a variable pointer
        #follow the trace marking all nodes along the way
        node_trace(item, node_pointer_list, nodes_dict_0)

print("\nMarked: ")
for item in sorted(nodes_dict_0.items()):
    if item[1][1] == 1:
        print(item[0])

print("\nReclaimed: ")
for item in sorted(nodes_dict_0.items()):
    if item[1][1] == 0:
        print(item[0])

Running the above script with the example input file produces the following output:

Marked:
0
1
2
3

Reclaimed:
4
5

which is correct.

My question simply this: Is the way I implemented this a reasonable solution or are there egregious inefficiencies, needlessly roundabout approaches etc that wouldn't be obvious to an novice that I could improve-on beyond just providing the required functionality?

More specifically: is a recursive algorithm the best approach in python? Is using a dictionary to track the marked status of nodes the most efficient way to do so? Is the way I structured the algorithm as efficient as it could be in terms of big-O?


texts:
I am building a Go based image processing worker for my web application. I am trying to be idiomatic, but I am new to Go. Any feedback, is appreciated. This program uses bimg to generate 4 square images based on top, left, width, height, which come from a client side cropping library (croppie.js)

package main

import (
    "log"
    "os"
    "fmt"
    "strings"
    "gopkg.in/h2non/bimg.v1"
)

var sizes = [3]int{128, 256, 512}

func resizeImage(img []byte, width int, height int, name string) (err error){
    options := bimg.Options{
        Width: width,
        Height: height,
    }

    var thumb []byte

    thumb, err = bimg.Resize(img, options)
    if err != nil {
        log.Println(os.Stderr, err)
        return err
    }
    err = bimg.Write(name, thumb)
    return
}

func processImage(top, left, width, height int, filename string) (err error){
    var buffer, original []byte
    var image *bimg.Image
    var fileBaseName = strings.Split(filename, ".")[0]

    buffer, err = bimg.Read(filename)
    if err != nil {
        log.Println(os.Stderr, err)
    }

    image = bimg.NewImage(buffer)

    original, err = image.Extract(left, top, width, height)
    if err != nil {
        return err
    }

    err = bimg.Write(fileBaseName + "_original.jpg", original)
    if err != nil {
        return err
    }

    for i := 0; i < len(sizes); i++ {
        size := sizes[i]
        err = resizeImage(original, size, size, fmt.Sprintf(fileBaseName + "_%d.jpg", size))
        if(err != nil){
            log.Println(os.Stderr, err)
            return err
        }
    }
    return
}

func main() {
    err := processImage(50,50,400,400, "test2.jpeg")
    if(err != nil){
        log.Println(os.Stderr, err)
    }
}


texts:
I am generating View and setting constraints programmatically in UIViewController

import UIKit
import SnapKit

class LoginViewController: UIViewController {
    lazy var topImageView = UIImageView()
    lazy var centerStackView = UIStackView()
    lazy var phoneTextField = UITextField()
    lazy var sendOTPButton = UIButton()
    lazy var bottomStackView = UIStackView()
    lazy var separatorLine = UILabel()
    lazy var signUpButton = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()
        makeUI()
    }

    private func makeUI() {
        self.view.backgroundColor = .white
        self.view.addSubview(topImageView)
        topImageView.backgroundColor = UIColor.magenta.withAlphaComponent(0.4)
        topImageView.snp.makeConstraints {(make) -> Void in
            make.width.equalToSuperview()
            make.height.equalTo(225)
            make.topMargin.equalToSuperview()
            make.centerX.equalToSuperview()
        }

        centerStackView.translatesAutoresizingMaskIntoConstraints = false
        centerStackView.axis = .vertical
        centerStackView.distribution = .fillEqually
        self.view.addSubview(phoneTextField)
        self.view.addSubview(sendOTPButton)
        self.view.addSubview(centerStackView)
        centerStackView.addArrangedSubview(phoneTextField)
        centerStackView.addArrangedSubview(sendOTPButton)
        phoneTextField.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
        phoneTextField.delegate = self
        sendOTPButton.setTitle("Send OTP", for: .normal)
        sendOTPButton.addTarget(self, action: #selector(generateAccessToken), for: .touchUpInside)
        sendOTPButton.backgroundColor = .blue

        centerStackView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(100)
        }

        bottomStackView.translatesAutoresizingMaskIntoConstraints = false
        bottomStackView.axis = .vertical
        bottomStackView.distribution = .fillProportionally
        self.view.addSubview(separatorLine)
        self.view.addSubview(signUpButton)
        self.view.addSubview(bottomStackView)
        bottomStackView.addArrangedSubview(separatorLine)
        bottomStackView.addArrangedSubview(signUpButton)
        separatorLine.backgroundColor = .white
        signUpButton.backgroundColor = .orange
        bottomStackView.snp.makeConstraints { (make) in
            make.bottomMargin.equalTo(additionalSafeAreaInsets)
            make.width.equalToSuperview()
            make.height.equalTo(80)
        }
    }

The makeUI functions essentially creates the views, adds them to UIController's view (as a subview) and set constraints on them (AutoLayout).
But the ViewController become bulky if more UIViews are added.

My question is:

Should I move the UI code to another file (say LoginView.swift)? Or is it recommended to keep the UI code in UIViewController as they are tightly coupled?


texts: Prettify this code - combine items in a list

texts:
Can anyone help me prettify this code? The idea is to combine adjacent time spans so

[0:00-1:00, 1:00-2:00, 3:00-4:00] becomes [0:00-2:00, 3:00-4:00]

private static IEnumerable<Span> CombineAdjacentSpans(IEnumerable<Span> spans)
{
    var combined = new List<Span>();
    var list = spans.OrderBy(s => s.Start).ToList();

    var candidate = list.FirstOrDefault();
    foreach (var span in list.Skip(1))
    {
        if (span.Start == candidate.End)
        {
            candidate.End = span.End;
            continue;
        }

        combined.Add(candidate);
        candidate = span;
    }

    if (candidate != null)
        combined.Add(candidate);

    return combined;
}


texts: Showing unapproved comments in a discussion system

texts:
In my project (which is a discussion system) there are approved and unapproved comments. There's a class that tells if unapproved comments should be shown. But I cannot think of a good name for this class. Right now it's named ShowUnapproved but doesn't that sound like a Boolean? (Rather than a configuration setting.)

Is the name ShowUnapproved clear to you? Or can you think of a better name?

Here is the class:

sealed abstract class ShowUnapproved {
  def shallShow(post: Post): Boolean // a "post" is e.g. a comment
}

object ShowUnapproved {

  case object None extends ShowUnapproved {
    override def shallShow(post: Post) =
      post.someVersionApproved
  }

  case object All extends ShowUnapproved {
    override def shallShow(post: Post) = true
  }

  case class WrittenByUser(userId: String) extends ShowUnapproved {
    override def shallShow(post: Post) =
      post.userId == userId
  }
}

Here're two examples of how to use it:

PageReneder.renderPage(page, ShowUnapproved.All)
PageReneder.renderPage(page, ShowUnapproved.WrittenByUser(userId))

And what would you call instances of this ShowUnapproved class?

I'm currently naming them showUnapproved which definitively sounds like a Boolean to me, and might be confusing:

val showUnapproved = ...  // sounds like a Boolean but it is not

val anyPendingApprovalText: NodeSeq =
  if (showUnapproved.shallShow(post)) makePendingApprovalText(post)
  else Nil
  // does `showUnapproved.shallShow` above sound good to you?


texts: Formatting database results to be consumed as multiple tables by the view

texts:
In the code below, $rows is the result of database query. In the view that consumes this, I need to break the results into a separate table for each vendor.

The below creates a structure that allows this in the template, but it seems like a clunky way of doing it. Advice on how to improve it?

    $byVendor = [];
    if (sizeof($rows) < 1)
        return $byVendor;
    $vendor   = $rows[0]->AMVEND;
    $i = 0;
    foreach ($rows as $row ) {
        $currentVendor = $row->AMVEND;
        if ($currentVendor != $vendor)
            $i++;
        $byVendor[$i][] = $row;
    }
    return $byVendor;

Code used in the view:

@section('content')
@foreach($vendors as $vendor)

{{$vendor[0]->AMNAME}}

            Date/Time
            PO Number
            Item
            Qty

    @foreach($vendor as $item)

            {{$item->CREATED_AT}}
            {{$item->SOURCE}}
            {{$item->ITEM}}
            {{$item->QTY}}

    @endforeach

@endforeach
@endsection


texts: Django: Database efficiency - currently accessed twice

texts:
I have the following function that is called via signal. 1) check if incluencer exists. 2) Increase discount by +1. Currently, I hit the database twice. Is there a better way to write that? Additionally, I wonder I can check 2) all on a database level so I don't need the for-loop.

@receiver(signal=charge_succeeded)
@transaction.atomic
def create_influencer_transaction(sender, order, charge, **kwargs):
    order_exists = Transaction.objects.filter(order=order).exists()
    if order_exists:
        return None

    # 1) Check if influencer exists
    first_order_item = order.order_items.first()
    influencer = first_order_item.social_referral
    if not influencer:
        return None

    total_points_earned = order.order_items.aggregate(
        total=Sum(
            F('unit_points_earned') * F('quantity'),
            output_field=IntegerField()
        )
    )['total'] or 0

    Transaction.objects.create(
        [...]
    )

    # 2) Redeemed amount + 1
    for order_item in order.order_items.all():
        social_discount = order_item.social_discount
        if social_discount:
            social_discount.redeemed_amount = F('redeemed_amount') + 1
            social_discount.save(update_fields=['redeemed_amount'])
            break

models.py

class OrderItem(AbstractItem, AbstractDiscountItem, AbstractSocialItem):
    order = models.ForeignKey(
        [...]
    )
    social_discount = models.ForeignKey(
        'discounts.SocialDiscount',
        on_delete=models.PROTECT,
        related_name='order_items',
        null=True,
        blank=True,
    )   # PROTECT = don't allow to delete the discount if an order_item exists

class SocialDiscount(AbstractDiscount):

    event = models.OneToOneField(
        [...]
    )  # CASCADE = delete the discount if the event is deleted
    tickets = models.ManyToManyField(
        [...]
    )


texts: Is there a redundancy between the two functions of adding a start node and an end node to my graph?

texts:
I feel like there is a redundency between:
def _determine_nodes_with_no_predecessors(nodes:List[Node])->List[str]:
    """
    Given the list of nodes returns the identifiers of nodes that doesn't have any predecessor.
    """
    nodes_ids_without_prdecessors = []
    for node in nodes:
        if not node.predecessors:
            nodes_ids_without_prdecessors.append(node.id_)
    return nodes_ids_without_prdecessors

def _add_start_node(graph:Graph):

    start_node = Node.create_start_node(graph)

    graph.add_node(start_node)

    nodes_ids_without_prdecessors = _determine_nodes_with_no_predecessors(graph.nodes)

    # Its successors are the nodes without predecessors in this graph
    for node_id in nodes_ids_without_prdecessors:
        start_node.add_successor(graph.nodes[node_id])

    # Conversly, We add the `start_node` as a predecessor to the nodes without predecessors in this graph
    for node_id in nodes_ids_without_prdecessors:
        node = graph.nodes[node_id]
        node.add_predecessor(start_node)

And this one:
def _determine_nodes_with_no_successors(nodes:List[Node])->List[str]:
    """
    Given the list of nodes returns the identifiers of nodes that doesn't have any successor.
    """
    nodes_ids_without_successors = []
    for node in nodes:
        if not node.successors:
            nodes_ids_without_successors.append(node.id_)
    return nodes_ids_without_successors

def _add_end_node(graph:Graph):

    end_node = Node.create_end_node() #constructor of node

    graph.add_node(end_node)

    end_node = graph.nodes[end_node.id_]

    nodes_ids_without_successors = _determine_nodes_with_no_successors(graph.nodes)

    # Its predecessors are the nodes without successors in this graph
    for node_id in nodes_ids_without_successors:
        end_node.add_predecessor(graph.nodes[node_id])

    # Conversly, We add the `end_node` as a predecessor to the nodes without predecessors in this graph
    for node_id in nodes_ids_without_successors:
        node = graph.nodes[node_id]
        node.add_successor(end_node)

Note: Node is a class that have the attributes predecessors, successors and id_ and the class methods create_dummy_start_node, create_dummy_end_node, add_predecessor and add_successor. Graph is a class that have the attribute nodes and the method add node.
How to write less code in this case? Is it possible to write only two functions that do the whole stuff (instead of four functions)?


texts: Creating a transaction with node-pg and Express

texts:
I'm trying to write a TRANSACTION with node-postgres in an Express API. [The code below works as it's supposed to, mostly looking for what should be corrected/changed]
This would be a POST request that creates a "transaction" and updates a record in a separate table. So basically a couple of queries at once. Below is the code:
For context, db is a connection pool to a postgres db.
// @desc        Add a Transaction
// @route       DELETE /api/v1/envelopes/:id/transactions
exports.addEnvelopeTransaction = async (req, res) => {
    const { id } = req.params;
    const { title, amount } = req.body;
    const date = new Date();

    const envelopeQuery  = "SELECT * FROM envelopes WHERE envelopes.id = $1";
    const transactionQuery = "INSERT INTO transactions(title, amount, date, envelope_id)VALUES($1, $2, $3, $4) RETURNING *";
    const updateEnvQuery = "UPDATE envelopes SET budget = budget - $1 WHERE id = $2 RETURNING *";

  try {
        // Use SQL TRANSACTION
        await db.query('BEGIN');
        const envelope = await db.query(envelopeQuery, [id])
        if (envelope.rowCount < 1) {
      return res.status(404).send({
        message: "No envelope information found",
            });
        };
        const newTransaction = await db.query(transactionQuery, [title, amount, date, id]);
        await db.query(updateEnvQuery, [amount, id]);
        await db.query('COMMIT');
        res.status(201).send({
            status: 'Success',
            message: 'New transaction created',
            data: newTransaction.rows[0],
            });
  } catch (err) {
        await db.query('ROLLBACK');
    return res.status(500).send({
            error: err.message
        });
  }
};

I smell some bad code here, I can't really tell if I'm using BEGIN, COMMIT, and ROLLBACK in the appropriate places.
What should I change?


texts: Finding the numerically listed string to the center algorthim

texts:
The algorithm takes input for a string's length for L, and the number of strings altogether for X. The hamming distance is for input D. Input Z calculates the exact amount of all possible characters in the string besides the permutations for input D.

We get a set of Z amount of characters. We divide Z by D which is S. We get B possible permutations of characters that can be generated in a list of X strings. In other words, Z divided by Y groupings of the same X should uniquely have B possible permutations within the Z characters. (For the center numerical listed string based on hamming?)

If the algorithm is, correct (or I've misled). The center of Z is at the S string which should be the B permutation.

NOTE: The concept is to visualize our strings as a number line.

Here the algorithm is written in Ancient Basic from a TRS-80 computer.

0 A=1
1 INPUT "LENGTH OF STRING";L
2 INPUT "X FOR HOW MANY";X
3 INPUT "D FOR HAMMING DISTANCE";D
4 Z = X * X * 1 * L + X * D * D * D + 1
5 S = Z / D
6 B = S / D
7 Y = S / B
8 CL = D * A ≤ X ≤ B * Y
10 P=B*Y
11 PRINT "CLOSEST STRING", CL, "P=", P
12 IF S = S * D / D THEN PRINT"S = S * D / D", S * D / D
13 IF D = Z / S THEN PRINT"D = Z / S", Z / S
15 PRINT"PROOF", P, S

I also continue with the algorithm to find where the 2nd closest string, 3rd closest, 4th and so on.

16 PRINT"WOULD YOU LIKE TO FIND CUSTOM CLOSEST STRING?";R$
17 IF R$=YES$ THEN GOTO 19
18 IF R$=NO$ THEN GOTO 19
19 INPUT "ENTER # FOR CLSE STRING";RT
20 GOTO 21
21 PRINT"YOUR CLOSEST STRING"RT, S / RT
90 NQ = S / RT
91 P = RT * NQ
92 IF P = NQ THEN PRINT P, NQ, "LUCKY"


texts:
I have written a logic to find out the intersection of two arrays. Please review my logic and guide me if my logical approach is not correct.

#include<stdio.h>

void intersect(int a1[][2], int a2[][2],int row, int col)
{

 int i = 0, j= 0, x = 0, y = 0;

for(i = 0; i <row ; i++)
{
    for(j = 0 ; j < col ; j++)
    {
            for(x = 0; x < row ; x++)
            {
                for(y = 0; y < col ; y++)
                {
                    if(a1[i][j] == a2[x][y])
                        printf("%d\t",a1[i][j]);

                }
            }
    }
}
}

int main()
{
     int arr1[2][2]={{2,5},{6,8}};
     int arr2[2][2]={{1,2},{8,8}};
     int row = (sizeof(arr1)/sizeof(arr1[0]));
     int col = (sizeof(arr1[0])/sizeof(arr1[0][1]));
     intersect(arr1,arr2,row,col);
}


texts:
I need to determine a meeting date which convenes on the second Thursday of every month.

I've written the following code to do this:

//Determine next monthly meeting (occurs on 2nd thursday of each month)
define('MAX_POSSIBLE_SECOND_THURS', 14);
define('JANUARY', 1);
define('DECEMBER', 12);
define('THURSDAY', 4);

$current_month  =   intval(date('n'));
$next_month     =   $current_month == DECEMBER ? 1 : $current_month + 1;
$current_day    =   intval(date('j'));

$iThursdayCount =   0;
$month_to_use   =   $current_day <= MAX_POSSIBLE_SECOND_THURS ? $current_month : $next_month;
$year_to_use    =   $month_to_use <> JANUARY ? intval(date('Y')) : intval(date('Y')) + 1;
for ($iDay = 1; $iDay <= MAX_POSSIBLE_SECOND_THURS; $iDay++) {
        $date_to_check  =   strtotime($year_to_use.'-'.$month_to_use.'-'.$iDay);
        if(date('N', $date_to_check)== THURSDAY) {
        $iThursdayCount++;
        if ($iThursdayCount == 2)
           break;
    }
}

$next_meeting_date = $month_to_use.'/'.$iDay.'/'.$year_to_use;

echo $next_meeting_date;

Although the loop is small, it seems like a lot of work to determine the second Thursday.  Are there any improvements that can be made?  Or would you do something totally different?


texts: Computing the square root of a number using binary search

texts:
This is implemented in MIPS assembly.

I've hard-coded the initial guess, as I haven't figured out how to allow the user to input a negative or non-negative integer to then display the result back to the user.

 # Sqrt.s - Calculates Sqrt of number X by doing a binary search.

 # Result returning register is $f12

.data
x:  .float 123.0
y:  .float 0.0

one: .float 1.0
zero: .float 0.0
two: .float 2.0
precision: .float 0.000000001

counter: .word 0

intro:  .asciiz "Calculates the SQRT of the Input for X in .data
section!"
inputMSG: .asciiz "Input: "
newLine: .asciiz "\n"
resultMSG: .asciiz "Result: "
errorMSG: .asciiz "ERROR: Input for x < 0 not allowed."

.text
main:
#Initialization
l.s $f0, zero       # zero
l.s $f1, one        # one = 1.0
l.s $f2, two        # two = 2.0
l.s $f3, x          # x
l.s $f4, y          # y = result register
l.s $f18, precision
lw $t1, counter #maintains the count of how many times it has been
looped and quits after 100 iterations

li $t0, 0   #Set t0 for index of stack
add.s  $f11, $f3, $f0   #set z to x + 0
addi $sp, $sp, 4

#Print intro, with inputMSG + input X
li $v0, 4
la $a0, intro
syscall
li $v0, 4
la $a0, newLine
syscall
li $v0, 4
la $a0, inputMSG
syscall
li $v0, 2
l.s $f12, x
syscall
li $v0, 4
la $a0, newLine
syscall

#-------Algorithm Here---------

#Branch for error if x < 0
c.eq.s  $f3, $f0
bc1t    zeroError
c.lt.s  $f3, $f0
bc1t    zeroError
#-------------------------

loop:
sub.s    $f16, $f11, $f4 #$f16 = z - y

c.eq.s  $f16, $f0       #if difference is equal to zero then answer
found
bc1t loop3
c.lt.s  $f16, $f18      #if difference is less than precision, end
bc1t loop3
add.s $f13, $f11, $f4    # m = y + z
div.s  $f13, $f13, $f2   # divide m/2

#li $v0, 2
#mov.s $f12, $f13
#syscall
#Print a newline
#la $a0, newLine
#li $v0, 4
#syscall

s.s     $f13, ($sp)     # add midpoint to stack
addi    $sp, $sp, 4     #increment stack by 4
mul.s   $f6, $f13, $f13 #m * m = $f6
sub.s   $f7, $f6, $f3   #subtract m^2 - x

#branch if m^2 - x = 0, then the answer was found
c.eq.s  $f7, $f0
bc1t    loop3

beq $t1, 100, loop3 #quit the program after 100 iterations

#branch if m^2 - x < 0, then jump to loop2
c.lt.s  $f7, $f0
bc1t    loop2

#continue to loop1 if m^2 > 0

loop1:
mov.s $f11, $f13    #set z to m (new upper limit)
addi $t1, $t1, 1     #increment counter
j loop

loop2:
mov.s $f4, $f13 #set y to m (new lower limit)
addi $t1, $t1, 1     #increment counter
j loop

#----------Output Result--------------
loop3:
la $a0, resultMSG
li $v0, 4
syscall
mov.s $f12, $f13  #print result in $f12
li $v0, 2
syscall

li $v0, 10
syscall            #exit

#------------Print Error MSG for x < 0-------------
zeroError:
#Print a newline
la $a0, newLine
li $v0, 4
syscall
#Print an Error Here
la $a0, errorMSG
li $v0, 4
syscall

li  $v0, 10
syscall      #exit

.end


texts: Randomly generate a Hex Colour code and its contrasting colour using Python

texts:
I am attempting to generate a new colour and its contrasting colour with this python script.

I plan to try to make a web app that is different every time it is loaded (i.e. background and text colour)

I am wondering if there is a better and more efficient way to do this?

Here is my code:

import random

values = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
value_dict = [['A','10'],['B','11'],['C','12'],['D','13'],['E','14'],['F','15']]
start = "#"

def contrastcolour(colour):
    if colour[0] == '#':
        colour = colour[1:]
    rgb = (colour[0:2], colour[2:4], colour[4:6])
    comp = ['%02X' % (255 - int(a, 16)) for a in rgb]
    return ''.join(comp)

def startcolour():
    colour = "#"
    for i in range(6):
        x = values[random.randint(0,len(values)-1)]

        for thing in value_dict:
            if x == thing[1]:
                x = thing[0]
        colour = colour + x
    return colour

base = startcolour()
contrast = start + contrastcolour(base)

print("The colours: {0}".format([base, contrast]))

The sample output is:

The colours: ['#2EF7F3', '#D1080C']


texts: Iterate over two collections of equal length

texts:
What's the best way to iterate over two collections of equal length?

Currently I'm using this:

for(var index = 0; index < collection1.Count(); index++)
{
    var item1 = collection1[index];
    var item2 = collection2[index];
    Console.WriteLine(item1.ToString() + ", "+ item2.ToString());
}

But I'd love to be able to use a foreach instead, e.g.

foreach(item1, item2 in collection1, collection2)
{
    Console.WriteLine(item1.ToString() + ", " + item2.ToString();
}

Now, this would be sort of possible if I zipped my two collections into a dictionary, but is that the best way to go? Would that be a sufficient gain of readability while sacrificing the performance needed to build the dictionary?

Similarly, I'm not sure if a dictionary is idealistically correct here, as there may not necessarily be a link between the two collections (other than their order in the list), merely a guarantee that they both have the same length.


texts: Is this Scala/Akka idiomatic and correct for Akka 2.1?

texts:
I'm wondering if there is anything i'm overlooking in the code below. I've taken the Pi calculation example, simplified it and converted it to Akka 2.1.

More specifically, i use the ask pattern to replace the Listener actor.

So is this

A proper and valid conversion?
A reasonable approach?
And is there a better approach to waiting for a result from an optionally distributed parallel reduction of a collection? In other words, is this an Akka equivalent of collection.par.map(work).par.reduce(result) or is there a better way?

object Work extends App {
  // This is just some collection of data to process (possibly remotely).
  val collection = 1 to 10000
  val start = System.currentTimeMillis
  val system = ActorSystem(f"Work${start}%08x${hashCode}%04x")
  // The collection is converted into a stream since it could
  // potentially be huge.
  val master = system.actorOf(Props(new Master(collection.toStream)), name = "master")

  // This replaces what the Listener was doing, i think.
  implicit val timeout = Timeout(12.seconds)
  val result = Await.result(master ? Run, timeout.duration)
  println(s"\n${result}")
  system.shutdown()

  sealed trait WorkMessage
  case object Run extends WorkMessage
  case class Work(start: Int) extends WorkMessage
  case class Result(value: Double) extends WorkMessage

  sealed trait ControlMessage
  case class Complete(elapsed:Long) extends ControlMessage

  class Worker extends Actor {
    def doWork(element: Int): Double = {
      print(s" ${element}")
      return element.toDouble
    }
    def receive = {
      case Work(element) ⇒
        sender ! Result(doWork(element))
    }
  }

  class Master(work: Seq[Int]) extends Actor {
    val nrOfCPUs = Runtime.getRuntime().availableProcessors();
    val nrOfWorkers = nrOfCPUs * 4
    val workSize = work.size
    var nrOfResults: Int = _
    val workerRouter = context.actorOf(
      Props[Worker].withRouter(RoundRobinRouter(nrOfWorkers)), name = "workerRouter")

    var done: ActorRef = _
    def receive = {
      case Run ⇒
        // Save the sender for responding to the ask once all the work is processed.
        done = sender
        work.foreach(element ⇒ workerRouter ! Work(element))
      case Result(value) ⇒
        nrOfResults += 1
        if (nrOfResults >= workSize) {
          done ! Complete(System.currentTimeMillis - start)
          context.stop(self)
        }
    }

  }

}

Here's a gist with the full code and a build.sbt to try:

curl -ks https://gist.github.com/nicerobot/4751388/raw/run.sh | sh


texts:
I've implemented an algorithm found in a book. It adds 2 positive integers of equal size. How can it be improved? It is assumed that inputted data is always positive integers with an equal number of digits.

EDIT
As there are lots of comments regarding the question, I would like to rephrase it. This program tries (yes it tries, could be wrong) to simulate how humans do manual additions of 2 positive integers. This is similar to the technique students learn in (I hope..) primary schools. It is based on the book "Invitation to Computer Science". One obvious improvement to this program is adding validations. What else can be done to improve it?

class Program
{
    static void Main(string[] args)
    {
        Add2Numbers(97,47);
        Console.ReadLine();
    }

    static void Add2Numbers(int a, int b)
    {
        int carry = 0,sum=0;
        List<int> lstA = new List<int>();
        List<int> lstB = new List<int>();
        List<int> lstSum = new List<int>();

        foreach (var item in GetDigit(a))
        {
            lstA.Add(item);
        }

        foreach (var item in GetDigit(b))
        {
            lstB.Add(item);
        }

        for (int j = 0; j < lstB.Count;j++ )
        {
            sum = lstA[j] + lstB[j] + carry;
            if (sum > 9)
            {
                sum = sum - 10;
                carry = 1;
            }
            else
                carry = 0;
            lstSum.Add(sum);
        }

        if (carry > 0)
            lstSum.Add(carry);

        lstSum.Reverse();
        foreach (var item in lstSum)
        {
            Console.Write(item);
        }
    }

    static IEnumerable<int> GetDigit(int number)
    {
        while (number > 0)
        {
            yield return number % 10;
            number = number / 10;
        }
    }

}


texts:
Find an element in a MxN matrix where each row and column is sorted in ascending order.

Any comments on my code?
(I added some test cases on non square matrices which I did not copy here)

import static org.junit.Assert.*;

import org.junit.Test;

public class Sol {

  public class Coord{
    int x;
    int y;

    public Coord(int _x, int _y){
      x = _x;
      y = _y;
    }
  }

  public Coord findElt(int[][] matrix, int elt, int begin_row, int end_row,
          int begin_col, int end_col){

    if (end_row < begin_row || end_col < begin_col){
      return new Coord(-1, -1);
    }

    if (begin_row == end_row && begin_col == end_col && matrix[begin_row][begin_col] != elt){
      return new Coord(-1, -1);
    }

    int mid_row = (begin_row + end_row)/2;
    int mid_col = (begin_col + end_col)/2;
    int current = matrix[mid_row][mid_col];

    if (current == elt){
    return new Coord(mid_row, mid_col);
  }

    else{
      Coord ur = findElt(matrix, elt, begin_row, mid_row, mid_col + 1, end_col);

      if (ur.x >= 0){
        return ur;
      }

      Coord bl = findElt(matrix, elt, mid_row + 1, end_row, begin_col, mid_col);

      if (bl.x >= 0){
        return bl;
      }

      if (elt > current){
        return findElt(matrix, elt, mid_row + 1, end_row, mid_col + 1, end_col);
      }
      else{
        return findElt(matrix, elt, begin_row, mid_row, begin_col, mid_col);
      }
    }

  }

  public Coord findElt(int[][] matrix, int elt){
    return findElt(matrix, elt, 0, matrix.length-1, 0, matrix[0].length-1);
  }

  @Test
  public void test_0(){
    int[][] mat = new int[3][3];

    mat[0][0] = 1;
    mat[0][1] = 2;
    mat[0][2] = 3;
    mat[1][0] = 2;
    mat[1][1] = 3;
    mat[1][2] = 5;
    mat[2][0] = 3;
    mat[2][1] = 4;
    mat[2][2] = 7;

    assertEquals(-1, findElt(mat, 8).x);
    assertEquals(-1, findElt(mat, 8).y);
  }

  @Test
  public void test_1(){
    int[][] mat = new int[3][3];

    mat[0][0] = 1;
    mat[0][1] = 2;
    mat[0][2] = 3;
    mat[1][0] = 2;
    mat[1][1] = 3;
    mat[1][2] = 5;
    mat[2][0] = 3;
    mat[2][1] = 4;
    mat[2][2] = 7;

    assertEquals(0, findElt(mat, 1).x);
    assertEquals(0, findElt(mat, 1).y);
  }

  @Test
  public void test_2(){
    int[][] mat = new int[3][3];

    mat[0][0] = 1;
    mat[0][1] = 2;
    mat[0][2] = 3;
    mat[1][0] = 2;
    mat[1][1] = 3;
    mat[1][2] = 5;
    mat[2][0] = 3;
    mat[2][1] = 4;
    mat[2][2] = 7;

    assertEquals(1, findElt(mat, 3).x);
    assertEquals(1, findElt(mat, 3).y);
  }

  @Test
  public void test_3(){
    int[][] mat = new int[3][3];

    mat[0][0] = 1;
    mat[0][1] = 2;
    mat[0][2] = 3;
    mat[1][0] = 2;
    mat[1][1] = 3;
    mat[1][2] = 5;
    mat[2][0] = 3;
    mat[2][1] = 4;
    mat[2][2] = 7;

    assertEquals(2, findElt(mat, 7).x);
    assertEquals(2, findElt(mat, 7).y);
  }

  public static void main(String[] args){
    int N = 3;
    int[][] mat = new int[N][N];
    Sol ex = new Sol();

    mat[0][0] = 1;
    mat[0][1] = 2;
    mat[0][2] = 3;
    mat[1][0] = 2;
    mat[1][1] = 3;
    mat[1][2] = 5;
    mat[2][0] = 3;
    mat[2][1] = 4;
    mat[2][2] = 7;

    ex.test_0();
    ex.test_1();
    ex.test_2();

    Coord a = ex.findElt(mat, 4);
    System.out.println(a.x + " " + a.y);

  }
}


texts: Project Euler #19: Counting Sundays in the 20th century using Pandas

texts:
Project Euler #19 asks:

  How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

I'm hoping I wasn't too off course from the spirit of the exercise by making use of my favorite libraries: pandas.

import pandas as pd

rng = pd.date_range(start='1/1/1901', end='12/31/2000', freq='D')
count = 0
for date in rng:
    if date.day == 1 and date.weekday() == 6:
        count += 1
count

It's a rather simple problem and a rather simple solution. I just made use of the date_range function that pandas has builtin that works well with datetime objects in python.

While I don't think my usual questions apply. Some specific questions:

Is it pythonic to run the for loop as such, or would a list comprehension surrounded by a len be more pythonic, e.g. len([x for x in rng if date.day == 1 and date.weekday() == 6])? Or is something entirely else even more pythonic?
Is there a way to avoid iterating over an object as large as rng is with it's 30,000+ items to avoid memory usage? If so what would be a preferred method (just pseudo-code or however you prefer to explain.)
As my attention has been brought to how powerful itertools is when improving performance and substituting lists for generators, I'm wondering how I would improve upon the below code with itertools if there is any such a way.


texts:
I'm using the asset BestHTTP in unity and I'm downloading a few image from amazonaws to use as texture. It used to be one image, but now I have a few.

I was not able to shorten it. When I'm trying to do it in a foreach loop loop it is misbehaving.

Could someone help me to optimize this working code?

for (int i = 0; i < tzPlayInfo.Instance.bc_gametablelist.Count; i++)
{
    dealer_img += tzPlayInfo.Instance.bc_gametablelist[i].dlrimage;
    dealer_img += ",";
}
string[] newLinks = dealer_img.Split(',');

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[0]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[0].GetComponent<UITexture>().mainTexture = tex;
    }).Send();

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[1]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[1].GetComponent<UITexture>().mainTexture = tex;
    }).Send();

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[2]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[2].GetComponent<UITexture>().mainTexture = tex;
    }).Send();

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[3]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[3].GetComponent<UITexture>().mainTexture = tex;
    }).Send();


texts:
today I coded a simple API class in C# with just a WebClient instance in each void and just simple voids to do simple things, can anyone give me any support in how I can improove it? Thanks.

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

namespace uTune.Base.Api
{
    class API
    {
        /// <summary>
        /// Runs a website script vue a url.
        /// </summary>
        /// <param name="url">URL to run.</param>
        public void runScript(string url)
        {
            WebClient client = new WebClient();
            client.DownloadString(url);
        }

        /// <summary>
        /// Runs a website script with the option of multiple parameters
        /// </summary>
        /// <param name="url">URL to run.</param>
        /// <param name="parameters">A list of parameters to include.</param>
        public void runScriptWithParameters(string url, Dictionary<string, string> parameters)
        {
            string urlToRun = url;
            bool firstParam = true;

            if (parameters.Count > 0)
            {
                foreach (KeyValuePair<string, string> parameter in parameters)
                {
                    if (firstParam)
                    {
                        urlToRun += "?" + parameter.Key + "=" + parameter.Value;
                        firstParam = false;
                    }
                    else
                    {
                        urlToRun += "&" + parameter.Key + "=" + parameter.Value;
                    }
                }
            }

            runScript(urlToRun);
        }

        /// <summary>
        /// Returns the pages content after a script has been executed.
        /// </summary>
        /// <param name="url">URL to get the content from.</param>
        /// <returns>Webpages content.</returns>
        public string getScriptReturn(string url)
        {
            WebClient client = new WebClient();
            return client.DownloadString(url);
        }

        /// <summary>
        /// Returns the pages conect after a script has been executed.
        /// </summary>
        /// <param name="url">URL to get the content form.</param>
        /// <param name="parameters">Parameters included in the URL.</param>
        /// <returns>Webpages content</returns>
        public string getScriptReturnWithParameters(string url, Dictionary<string, string> parameters)
        {
            string urlToRun = url;
            bool firstParam = true;

            if (parameters.Count > 0)
            {
                foreach (KeyValuePair<string, string> parameter in parameters)
                {
                    if (firstParam)
                    {
                        urlToRun += "?" + parameter.Key + "=" + parameter.Value;
                        firstParam = false;
                    }
                    else
                    {
                        urlToRun += "&" + parameter.Key + "=" + parameter.Value;
                    }
                }
            }

            return getScriptReturn(urlToRun);
        }
    }
}


texts:
I would like some advice which relates to the "fat model skinny controller" concept in Rails.

See my show action in the Micropost controller

 def show
     @micropost = Micropost.find(params[:id])
     @tags = @micropost.tag_counts_on(:tags)
     @responses =  @micropost.responses
     @response = current_user.responses.build if member_signed_in?
     impressionist(@micropost)
     related_posts = Micropost.tagged_with(@micropost.tag_list, :on => :tags, :any => true).take(5)
     @cleaned_related_posts = Micropost.assemble_related_posts(related_posts, @micropost)
 end

This action does a number of things.
1. It shows a micropost
2. It gets all the tags (acts as taggable) from the micropost (to display them)
3. It builds the response - response form is on the same page
4. It impressions the micropost (impressionist gem)
5. Lastly, it builds a list of related microposts. I tried to clean this up by using a class method in my micropost class as follows

def self.assemble_related_posts(related_posts = [], micropost)
  @cleaned_related_posts = []
  related_posts.each do |post|
    unless post == micropost
      @cleaned_related_posts.push(post)
    end
   end
  @cleaned_related_posts
end

The related posts variable above INCLUDES the micropost being shown - no point in that, so I wrote a class method to remove it.

This show action is pretty fat, and my RubyMine keeps showing me a warning that the controller should call only one method.

I want to improve my skills (I am fairly new to Rails). Is there a "Rails way" to shift all this logic into the model.....should it be done? Are some controllers simply going to a bit on the fat side?


texts: Function with excessively complex "where" clause

texts:
I'm writing a program to differentiate functions (perform basic calculus) in Haskell. The program works, but there's one function that looks very ugly to me:

--some prerequisite definitions

--a mathematical value is either...
data Value =
    Literal Double                     --a number, such as 4, -17.5, or 2.33e27
    | Variable Symbol (Maybe Double)   --a variable, which may or may not have a known value
    | FCall                            --a function call, consisting of a function and two arguments
      {
          func :: Function,
          arg1 :: Value,
          arg2 :: Value
      }
      deriving (Eq)

--simplifies a mathematical value into a simpler form.

reduce :: Value -> Value
reduce val@(Literal _)          = val               --literals cannot be simplified
reduce (Variable _ (Just val))  = Literal val       --bound variables can be simplified to literals
reduce var@(Variable _ Nothing) = var               --unbound variables cannot be simplified
reduce fc@(FCall f a b)         =                   --simplifying functions is messy...
   if isDefined f ma mb
        then matchLiterals ma mb
        else retval
    where ra = reduce a  --reduce simplifies a Value to a Value
          rb = reduce b
          ma = eval ra   --eval converts known values to Doubles and unknown Values to Nothing
          mb = eval rb
          retval = FCall f ra rb  --returned in case of failure
          matchLiterals (Just da) (Just db) = Literal $ (impl f) da db
          matchLiterals _ _ = matchCase $ findCase (cases f) ra rb
          matchCase (Just sc) = evalCase sc ra rb
          matchCase Nothing = retval

The multitude of local functions defined in the where clause seems excessive, but I can't find a better way to handle the flow of execution. I've tried to break this up into several smaller functions, but since most of these can fail (evaluate to Nothing), I still have to use pattern matching to handle the results of these functions.

The flow of logic goes like this:

if the function is defined for the given arguments:
    if the arguments have definite known values:
        evaluate and return the function call
    else:
        look for special cases (adding 0, multiplying/diving by 1, etc.)
        if a special case was found:
            evaluate and return the result of applying the special case to the arguments
        else:
            return another FCall with possibly simplified arguments

else:
    return another FCall with possibly simplified arguments

It's possible I'm fretting over nothing (hah) and this code is perfectly fine, but it seems that this is not the optimal way to handle these conditions. Can anyone offer any advice about how I might better structure this code?


texts: Calling restful web services efficiently

texts:
I need to use this code to fetch data from web service and show them in a site properly but after I request for the webservice I am unable to load them fast. Site is loading very slow.

<?php

$jRequestURLPrefix = 'http://demo.4ds.com/rema/1.1/';

$menu_json_url  = $jRequestURLPrefix."rules/origins/b2c.json";

$menu_data      = get_json_data($menu_json_url);

/* Function get_json_data definition */

function get_json_data($json_url, $return_array = true, $print_array = false, $curl = true )
{
    $jsonString = '';
    $data       = array();
    if (!$curl)
    {
        /*
         *  if !$curl, use "file_get_contents" method
         *  to get JSON encoded string
        */
        $jsonString = file_get_contents($json_url);

    }
    else
    {
        /*
         *  if $curl, use "curl" method
         *  to get JSON encoded string
        */

        // Initializing curl
        $ch = curl_init( $json_url );

        // Configuring curl options
        $options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
        );

        // Setting curl options
        curl_setopt_array( $ch, $options );

        // Getting JSON encoded string
        $jsonString =  curl_exec($ch);
    }

    // convert the JSON encoded string into a PHP variable(array)
    //if($return_array)
        $data = json_decode($jsonString, $return_array);

    // $print_array == true, print the array
    if($print_array)
    {
        echo '<pre>';
        print_r($data);
        echo '</pre>';
    }

    return $data;

}

?>

After using the above procedure I am getting the response very slow.


texts:
My code fetches telegrams from a server periodically in the background. The server API is documented here. What do you think of the way I do multithreading by handling my _updatesList?

public class AutoUpdate
{
    public bool IsStarted { get; private set; }
    private readonly Timer _timer;

    private readonly List<Update> _updatesList;
    private readonly object _lock = new object();
    private long _lastUpdateId;

    public AutoUpdate()
    {
        _lastUpdateId = 0;
        _updatesList = new List<Update>();
        TimerCallback getUpdates = GetUpdates;
        _timer = new Timer(getUpdates, null, Timeout.Infinite,Timeout.Infinite);
        IsStarted = false;
    }

    public bool Start()
    {
        if (Monitor.TryEnter(_lock, 500))
        {
            try
            {
                _timer.Change(0, 100);
                IsStarted = true;
            }
            finally
            {
                Monitor.Exit(_lock);
            }
            return true;
        }
        return false;
    }

    public bool Stop()
    {
        if (Monitor.TryEnter(_lock, 500))
        {
            try
            {
                _timer.Change(Timeout.Infinite, Timeout.Infinite);
                IsStarted = false;
            }
            finally
            {
                Monitor.Exit(_lock);
            }
            return true;
        }
        return false;
    }

    public bool Terminate()
    {
        var stop = Stop();
        if (!stop)
            return false;
        _timer.Dispose();
        return true;
    }

    public ICollection<Update> GetLastUpdates()
    {
        lock (_lock)
        {
            //Make A Copy: for thread safety
            //Then Pass To ReadOnlyCollection
            return new ReadOnlyCollection<Update>(_updatesList.ToArray());
        }
    }

    public void RemoveFromUpdates(Update update)
    {
        lock (_lock)
        {
            _updatesList.Remove(update);
        }
    }

    private void GetUpdates(object state)
    {
        ReturnedResult<List<Update>> responseObject = null;

        if (Monitor.TryEnter(_lock))
        {
            try
            {
                HttpClient hc = new HttpClient();
                HttpContent requestContent = new ObjectContent<UpdateRequest>(new UpdateRequest(),
                    new JsonMediaTypeFormatter());
                var task =
                    hc.PostAsync(
                        "https://api.telegram.org/bot<Private Token>/getUpdates",
                        requestContent);
                if (task != null)
                {
                    var result = task.Result;
                    var jsonString = result.Content.ReadAsStringAsync().Result;
                    responseObject = JsonConvert.DeserializeObject<ReturnedResult<List<Update>>>(jsonString, new JsonSerializerSettings
                    {
                        ContractResolver = new CustomPropertyNamesContractResolver { Case = IdentifierCase.UnderscoreSeparator}
                    });
                }

                //Add To The List...
                if (responseObject != null && responseObject.Ok)
                {
                    var updateList = responseObject.Result.Where(w => w.UpdateId > _lastUpdateId);

                    //Resharper Detected: Possible multi enumeration of same list in same time
                    var list = updateList as Update[] ?? updateList.ToArray();

                    var maxId = list.Max(m => (long?) m.UpdateId) ?? 0;
                    _lastUpdateId = Math.Max(maxId, _lastUpdateId);

                    _updatesList.AddRange(list);
                }
            }
            finally
            {
                Monitor.Exit(_lock);
            }
        }
    }
}


texts:
I need automatic dependency generation to be done in my makefile. So, I have tried to write one, after googling for similar ones. I have found some ways to do that, but the problem is that they are usually too complicated for me (because of usage of sed command etc. and I want a way for me to create a makefile without the need of refering to some other makefile).

Below is a makefile I hope should do the same job i.e. automatically find out all the dependencies of the object files and build them. Could you please review this makefile and point out cases where the build may fail when it should not have?

Gpp=g++
srcs=$(wildcard *.cpp)
objs=$(srcs:.cpp=.o)
deps=$(srcs:.cpp=.d)

default:test

%.o:%.d
    $(Gpp) -c $*.cpp

%.d:%.cpp
    echo -n "$*.d ">$*.d
    $(Gpp) -MM $*.cpp>>$*.d

test: $(objs)
    $(Gpp) $^ -o $@

-include $(deps)

.PHONY:clean default

clean:
    -rm -rf *.o test *.d

One place where the makefile fails is when for example a.cpp initially included a1.h but it has been updated to exclude a1.h and a1.h file has been deleted from file-system. So, except that is there any place that this makefile fails?


texts:
I have implemented a trie in Java and I would request you to review it and suggest improvements or new features.

The code is split into 3 files.

TrieNode (individual nodes in the trie)

import java.util.HashMap;

class TrieNode {

    private char value;
    private HashMap<Character, TrieNode> children ;

    public TrieNode() {
        // TODO Auto-generated constructor stub
        children = new HashMap<>();
    }

    public TrieNode(char value) {
        this.value = value;
        children = new HashMap<>();
    }

    public char getValue() {
        return value;
    }

    public void setValue(char value) {
        this.value = value;
    }

    public HashMap<Character, TrieNode> getChildren() {
        return children;
    }

    public void setChildren(HashMap<Character, TrieNode> children) {
        this.children = children;
    }
}

Trie (the trie itself)

import java.util.Set;

public class Trie {

    private TrieNode root;

    public Trie() {
        // TODO Auto-generated constructor stub
        root = new TrieNode();
        root.setValue('$'); //arbitary node value for root
    }

    /**
     * This method will build the trie with the given set of words
     * @param wordSet
     */
    public void buildTrie(Set<String> wordSet){

        for (String word : wordSet){
            int wordLength = word.length();
            TrieNode crawl = root;
            for (int i=0;i<wordLength ;++i){
                crawl = traverseTrie(crawl, word.charAt(i));
            }
        }
    }

    /**
     * This method will traverse the trie and find out the exact position to
     * insert a particular character
     * @param node
     * @param input
     * @return
     */
    public TrieNode traverseTrie(TrieNode node,char input){
        TrieNode newNode = null;
        //if no such node exists then create one
        if (node.getChildren().get(input)==null){
            node.getChildren().put(input, new TrieNode(input));
            newNode = node.getChildren().get(input);
        }else{
            //if exist then just traverse
            newNode = node.getChildren().get(input);
        }
        return newNode;
    }

    /**
     * This method searches the trie for the given word and returns a boolean value
     * indicating it's presence or absence
     * @param word
     * @return {@link boolean} value indicating it's presence or absence
     */
    public boolean searchWord(String word) {
        // TODO Auto-generated method stub
        boolean result = true;
        int wordLength = word.length();
        TrieNode crawler = root;
        for (int i= 0 ; i< wordLength ; ++i){
            char character = word.charAt(i);
            if (crawler.getChildren().get(character) == null){
                result = false ;
                break;
            }else{
                crawler = crawler.getChildren().get(character);
            }
        }
        return result;
    }
    //getters and setters
    public TrieNode getRoot() {
        return root;
    }

    public void setRoot(TrieNode root) {
        this.root = root;
    }
}

TrieDriver (the driver program to run the trie)

import java.util.HashSet;
import java.util.Set;

public class TrieDriver {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Trie trie = new Trie();
        Set<String> dictionary = new HashSet<>();
        dictionary.add("CAT");
        dictionary.add("CATWOMAN");
        dictionary.add("CATERER");
        dictionary.add("DOT");
        dictionary.add("DOG");
        dictionary.add("DOC");
        //build the trie
        trie.buildTrie(dictionary);
        String wordToSearch = "CAX";
        //search the trie
        System.out.println("The word "+wordToSearch + " is present or not???"+
                (boolean)trie.searchWord(wordToSearch));
    }

}


texts:
This works as expected and I want to get this code reviewed so that I can improve my coding ability.

I am concerned about readability and the quality of the code

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

struct node
{
    int element;
    struct node *next;
};

struct node* mergeList(struct node *list1, struct node *list2)
{
    struct node *root = NULL, *cur = NULL;

    if(list1 == NULL)
    {
        return list2;
    }

    if(list2 == NULL)
    {
        return list1;
    }

    while( (list1 != NULL) && (list2 != NULL) )
    {
        struct node *tmp = malloc(sizeof(struct node));
        if( list1->element  < list2->element )
        {
            tmp->element = list1->element;
            tmp->next = NULL;
            list1 = list1->next;
        }
        else
        {
            tmp->element = list2->element;
            tmp->next = NULL;
            list2 = list2->next;

        }
        if(root == NULL)
        {
            root = tmp;
            cur = root;
        }
        else
        {
            cur->next = tmp;
            cur = tmp;
        }

    }

    while(list1 != NULL)
    {
        struct node *tmp = malloc(sizeof(struct node));
        tmp->element = list1->element;
        tmp->next = NULL;
        cur->next = tmp;
        cur = tmp;
        list1 = list1->next;
    }
    while(list2 != NULL)
    {
        struct node *tmp = malloc(sizeof(struct node));
        tmp->element = list2->element;
        tmp->next = NULL;
        cur->next = tmp;
        cur = tmp;
        list2 = list2->next;
    }

    return root;

}

void findMid(struct node *root, struct node **list1, struct node **list2)
{

    struct node *slow;
    struct node *fast;
    printf("\nIn Findmis\n");
    if( (root == NULL) || (root->next == NULL) )
    {
        *list1 = root;
        *list2 = NULL;
        return;
    }
    else
    {

        slow =  root;
        fast = root->next;
        while (fast != NULL)
        {
            fast = fast->next;
            if(fast!=NULL)
            {
                slow = slow->next;
                fast = fast->next;
            }

        }

        *list1 = root;
        *list2 = slow->next;
        slow->next = NULL;

    }

}

void mergeSort(struct node **root)
{
    struct node *list1, *list2;
    struct node *head = *root;
    if( ( head  == NULL) || (head->next == NULL))
    {
        return;
    }

    findMid(head, &list1, &list2);

    if(list1 != NULL)
    printf("\nList1 = %d", list1->element);
    if(list2 != NULL)
    printf("\nList2 = %d", list2->element);
    mergeSort( &list1 );
    mergeSort( &list2 );

    *root = mergeList( list1, list2 );

}

void insertNodes(struct node **root, int key)
{
    struct node *tmp = malloc(sizeof(struct node));
    tmp->element = key;
    tmp->next = *root;
    *root = tmp;

}

void printList(struct node *root)
{
    while( root!= NULL)
    {
        printf("\n%d\n", root->element);
        root = root->next;
    }

}

int main(int argc, char *argv[])
{

    struct node *root1 = NULL;

    struct node *root2 = NULL;
    insertNodes( &root1, 1);
    insertNodes( &root1, 2);
    insertNodes( &root1, 3);
    insertNodes( &root1, 4);
    insertNodes( &root1, 5);
    printList(root1);
    mergeSort( &root1);
    printList(root1);
    return 0;

}


texts: Adding or replacing a sheet in an Excel file

texts:
I have the following function and want to simplify the code to make it more readable by eliminating redundant lines:

Function AddSheet(shtName As String, Optional readOnlyFlag As Boolean = True) As Boolean  'Add new worksheet to current workbook at the end

    If readOnlyFlag And IsSheet(shtName) Then
        AddSheet = False
        Exit Function
    ElseIf Not readOnlyFlag Then
        If IsSheet(shtName) Then DeleteSheet (shtName)
        With ThisWorkbook:
            .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = shtName
        End With
        AddSheet = True
    End If

End Function

Since the first condition (If readOnlyFlag And IsSheet(shtName)) will only assign a return value of False to the function (which should already be the default, as I understand) and then exits the function, would it be acceptable to leave out that aspect of the logic and just have the following:

    If Not readOnlyFlag Then
        If IsSheet(shtName) Then DeleteSheet (shtName)
        With ThisWorkbook:
            .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = shtName
        End With
        AddSheet = True
    End If

In other words, is it best practice to be explicit like the first code block, by stating that the function returns False if that occurs, or to avoid what might be considered redundancy, by using the simplified second version?


texts: API request, conversion from 12-hour to 24-hour format and conversion from UTC to MET time

texts:
The script calls the sunrise-sunset API to get one of the possible values, then converts it to 24-Hour format and MET time (as the times from the API are 12-hour and UTC). At the end, it joins the list to a string and prints it. I know this isn't commented very well, but are there any significant flaws in this code? I neither have any experience with Python nor with programming in general, this is just for a personal project and Python seemed to be the best way to do this, so I'm open for any advice and help.

import json
import urllib.request as request

def apiGetList(key):
    """ Function twilightApiGetList(key):
        Calls the sunrise-sunset api to return the value of a given key
        Possible keys: sunrise, sunset, solar_noon, day_length, civil_twilight_begin, civil_twilight_end,
        nautical_twilight_begin, nautical_twilight_end, astronomical_twilight_begin, astronomical_twilight_end
        All times returned are a list in 12-hour format, UTC time
    """
    with request.urlopen('https://api.sunrise-sunset.org/json?lat=44.244622&lng=-7.768863&date=today') as response:
        if response.getcode() == 200:
            source = response.read()
            data = json.loads(source)
            out = list(f"{data['results'][key]}")
            if len(out) == 10:
                out.insert(0, '0')
            else:
                pass
            return(out)
        else:
            print("Not successful")
            return

def convert12To24(lst):
    """ Function convert12To24(lst):
        Converts from 12-hour format to 24-hour format, input and output types are lists
    """
    if lst[9] == "A" and "".join(lst[0:2]) == "12":
        del lst[8:12]
        lst[0:2] = '00'
    elif lst[9] == "A":
        del lst[8:12]
    elif lst[9] == "P" and "".join(lst[0:2]) == "12":
        del lst[8:12]
    else:
        del lst[8:12]
        lst[0:2] = str(int("".join(lst[0:2])) + 12)
    return(lst)

def convertUtcToMet(time):
    """ Function convertUtcToMet(time):
        Converts from UTC time to MET time by adding two hours. Input and output time is in 24-hour format, type is a list
    """
    if int("".join(time[0:2])) < 8:
        time[0:2] = str(int("".join(time[0:2])) + 2)
        time.insert(0, '0')
    elif "".join(time[0:2]) == '22':
        time[0:2] = '00'
    elif "".join(time[0:2]) == '23':
        time[0:2] = '01'
    else:
        time[0:2] = str(int("".join(time[0:2])) + 2)
    return(time)

if __name__ == "__main__":
    ctb = apiGetList("civil_twilight_begin")
    cte = apiGetList("civil_twilight_end")

    print("".join(convertUtcToMet(convert12To24(ctb))))
    print("".join(convertUtcToMet(convert12To24(cte))))


texts:
We've got this node.js code which is called by an Express route:

routes.login = (req, res) => {

  let inpEmail = req.body.email.toLowerCase(),
    inpPassword = req.body.password,
    loginFailureCount = 0;

  // find the user
  User.findOne({
      email: inpEmail
    }).exec()
    .then((user) => {

      //get existing login failure count
      loginFailureCount = user.loginFailureCount;

      if (user.isLocked && Date.now < user.lockExpiry) {
        //some logic here
      } else if (!user.emailVerified) {
        //some logic here
      } else {

        bcrypt.compare(inpPassword, user.passwordHash).then((compareResult) => {

          // check if password matches
          if (compareResult) {

            //some logic here
            setLoginFailureCount(user, loginFailureCount).then(() => {

                setLastLogin(user)
                  .then(() => {
                    //some logic here
                  })
                  .catch((err) => {
                    //some logic here
                  });
              })
              .catch((err) => {
                //some logic here
              });

          } else {

            //login failed
            loginFailureCount = loginFailureCount + 1;
            setLoginFailureCount(user, loginFailureCount)
              .then(() => {
                //some logic here
              })
              .catch((err) => {
                //some logic here
              });
          }
        });
      }
    })
    .catch((err) => {
      //some logic here
    });
}

All looks good, and we feel that the promises are not used correctly; there are multiple catch statements.

One of my colleague said that:

  Ideally, the code structure with promises shall look like this:

someFunction()
.then()
.then()
.then()
.catch();

Since, there are multiple if-else statements. We were trying to brainstorm if the above kind of chaining can be implemented or not.

Is there a better way to implement promises in this code?


texts: Avoiding the use of ordinal() in an already-deployed enum

texts:
While reviewing a PR, I found an enum being used like this:

class Entity {
    public enum STATUS { NEW, SENT, FAILED, OK }

    @Column(name = "STATUS") // a NUMBER(1) column in DB
    private int status; // + get/set
    //...
}

// Inside methods...
Entity e = new Entity();
e.setStatus(STATUS.SENT.ordinal());
EntityDAO.save(e);

Entity e = EntityDAO.findByStatus(STATUS.FAILED.ordinal());
logger.info("Found entity with status: " + STATUS.values()[e.getStatus()]);

Assume the necessary imports etc.

I find this use of ordinal() to be an antipattern, and consider that it should be avoided.
Instead, an inner field with the equivalent DB representation (e.g. NEW(1) or NEW("N")) should be used, in order to decouple the semantically meaningful representation of the enum value in the code (NEW) from the DB-optimized representation of such value when persisted (1 or 'N' or whatever).

Now, I don't have this POV for nothing: we've already had bugs stemming from altering the order of enum elements that were being used based on its ordinal() value (some times because of adding new values in between, some times because someone decided the values looked better in alphabetical order ¯\_(ツ)_/¯).

That's the case I made in the PR comments -- but in the end the PR got approved anyway, reasoning that my proposed correction would add too much clutter to the enum for little gain, and that we should all just be careful with enums.
And so the enum made its way to production.

Time has passed, and now I've got the chance to change that enum so its usage is not tied to the ordering of its elements.
However, since this has been in production for quite some time, I have to make it so the current DB values (0, 1, 2...) are kept and still interpreted correctly (as changing the DB values or column type would be too costly now).

This is the first version I came up with:

public enum STATUS {
    NEW (0),
    SENT (1),
    FAILED (2),
    OK (3),
    ;

    private final int val;

    STATUS (int val) { this.val = val; }

    public int val() { return val; }

    public static STATUS get(final int val) {
        switch (val) {
            case 0: return NEW;
            case 1: return SENT;
            case 2: return FAILED;
            case 3: return OK;
            default: throw new IllegalArgumentException();
        }
    }
}

I think this is as concise as it can get.
However, if a dev wanted to add a new enum value, they'd have to modify both the enum list and the switch inside the get(int) method. I find this to be inconvenient and, in a way, ammunition for my peers in favor of just using ordinal().
So I came up with this second version:

public static enum STATUS {
    NEW (0),
    SENT (1),
    FAILED (2),
    OK (3),
    ;

    private static final STATUS[] values;
    static { // like caching values() but sorted by dbValue
        STATUS[] st = values();
        values = new STATUS[st.length];
        for (STATUS s : st) {
            values[s.dbValue] = s;
        }
    }
    public static STATUS fromDB(final int dbValue) {
        return values[dbValue];
    }

    private final int dbValue;
    public int toDBValue() {
        return dbValue;
    }

    STATUS(int dbValue) {
        this.dbValue = dbValue;
    }
}

In this version, adding a new enum element is as simple as adding it to the list, just like a normal enum. And getting an element from its DB value is O(1) and rather efficient (compared to, say, using Streams to filter values() by dbValue every time). But maybe it is too complex for an enum? Also, this relies on DB values being consecutive numbers, as adding e.g. CANCELLED(99) would throw an AIOOB exception upon execution.

So my question is: how can I enhance this enum so adding elements to it is as simple as possible, getting elements by value is as efficient as possible, and it doesn't depend on ordinal()?


texts: C program to delete each character in s1 that matches any character in s2

texts:
Works fine. Not looking for any specific input.

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10000

void delete_str(char *s1, char *s2){
    for(int i = 0; *(s1+i) != '\0'; ++i){
        for(int j = 0; *(s2+j) != '\0'; ++j){
            if(*(s1+i) == *(s2+j)){
                for(int n = i; *(s1+n) != '\0'; ++n){
                    *(s1+n) = *(s1+n+1);
                }
                --i;
                break;
            }
        }
    }
}

int main(void){
    char s1[MAX_SIZE];
    char s2[MAX_SIZE];

    puts("Enter s1");
    if(fgets(s1, sizeof(s1), stdin) == NULL){
        puts("Error reading s1");
        exit(EXIT_FAILURE);
    }

    puts("Enter s2");
    if(fgets(s2, sizeof(s2), stdin) == NULL){
        puts("Error reading s2");
        exit(EXIT_FAILURE);
    }

    delete_str(s1, s2);

    printf("%s", s1);

    return 0;
}


texts:
An attempt to find Mersenne primes using the Lucas-Lehmer primality test:
n=int(input("Enter n to check if 2^n-1 is a prime:"))
a=4
for i in range(0,n-2):
    b=a**2
    a=b-2
    if i==n-3:
        c=(a)%((2**n) - 1)
        if c==0:
            print((2**n) - 1 ,"is a prime number")
            break
if c!=0:
    print((2**n) - 1 ,"is not a prime number")

Can you critique this code? It is apparent that it needs improvement as it doesnt work for n<=2 and computing power increases exponentially for increasing n.
I have been learning python for less than a year, I am only 15 and would love any feedback on this program.
Edit: The confusion with n-2 and n-3 is because we have to check if the (n-1)th term in the series is divisible by l = 2^n - 1 to establish that l is a Mersenne prime. But as you would have noticed the above written code considers the 0th term as 14 which is the 3rd term in the actual series. This means there is a gap of two terms between the actual series and the series procured by the program, therefore to actually study the (n-1)th term in the series , we have to consider the (n-3)th term here. Hence the mess that doesn't allow n to be <=2.
Please provide your opinion on this


texts: Collecting 3 years of data and building a string

texts:
I am collecting 3 years of data and building a string that will be used with an ASP Literal control. The method GetListOfMeetingBygroupId takes in a groupID and year and will return meeting for that group and year.

    MeetingService ms = new MeetingService();
    int groupId = 574;

    //Meeting

    int totalYearCount = 3;
    StringBuilder sbMeeting = new StringBuilder();
    DateTime aDate = DateTime.Now;
    for (int x = 1; x <= totalYearCount; x++)
    {

        var list = ms.GetListOfMeetingBygroupId(groupId, aDate.Year);

        sbMeeting.AppendFormat("
{0}
",aDate.ToString("yyyy"));

        foreach (var meeting in list)
        {
                sbMeeting.Append("
");

                DateTime meetingendDate = Convert.ToDateTime(meeting.MeetingDateList.Select(c => c.StartDate).Max());
                DateTime meetingstartDate = Convert.ToDateTime(meeting.MeetingDateList.Select(c => c.StartDate).Min());

                int totalMeetingPresentation = ms.GetListOfPresentationsBymeetingId(meeting.MeetingId).Count();

                sbMeeting.Append(meetingstartDate.ToString("dddd, MMMM dd  yyyy"));
                sbMeeting.Append("
");
                sbMeeting.Append(meeting.Type.Name);
                sbMeeting.Append("
");

                if (totalMeetingPresentation > 0)
                {
                    sbMeeting.AppendFormat("{1}", meeting.MeetingId, "Minutes and Presentations");
                }
                else
                {

                    var meetingMinFile = ms.GetMeetingFile(meeting.MeetingId);
                    sbMeeting.AppendFormat("{1}	", meetingMinFile.FileManagerId, "Minutes");

                }
                sbMeeting.Append("
");
                sbMeeting.Append("
");
                sbMeeting.Append("
");
       }
        aDate = aDate.AddYears(-1);
    }


texts:
The code reads all my routes and return to my AJAX request the names of the routes without duplicates and just those that have the "rt_" prefix.
class RouteController extends Controller {
    public function getRoutes()
    {

        //Get all the routes.
        $routes = Route::getRoutes();

        //Setting up the vars
        $array = [''];

        foreach ($routes as $route) {
            $condicional = substr($route->getName(), 0, 3);
            $found = FALSE;

           //Filtering the routes with rt_ prefix
            if ($condicional == 'rt_') {

                 //Filering duplicates
                foreach ($array as $item) {
                    if ($item == $route->getName()) {
                        $found = TRUE;

                    }

                }

                //Echo without duplicates
                if ($found == FALSE) {
                    $array[] = $route->getName();

                }
            }
        }

        return response()->json($array, 200);

    }

}


texts:
I have a lot of repeatable blocks of code and want to optimize/simplify them:

    function animationInit() {
    content = $('#content')
        .bind('show',function(event, f) {
            $(this).animate({right:0}, lag + 200, function() {
                if (f) f();
            });
        })
        .bind('hide',function(event, f) {
            $(this).animate({right:-700}, lag + 200, function() {
                if (f) f();
            });
        });

    hotelnav = $('#hotel')
        .bind('show',function(event, f) {
            hotelnav.removeClass('small');
            $(this).animate({left:0}, lag + 200, function() {
                if (f) f();
            });
        })
        .bind('hide',function(event, f) {
            $(this).animate({left:isGallery()?-300:-300}, lag + 200, function() {
                hotelnav.addClass(isGallery()?'small':'');
                if (f) f();
            });
        });

    bottompanel = $('#bottompanel')
        .bind('show',function(event, f) {
            $(this).animate({bottom:40}, lag + 200, function() {
                if (f) f();
            });
        })
        .bind('hide',function(event, f) {
            $(this).animate({bottom:-120}, lag + 200, function() {
                if (f) f();
            });
        });

    booknow = $('#booknow')
        .bind('show',function(event, f) {
            $(this).fadeIn(lag + 200, function() {
                if (f) f();
            });
        })
        .bind('hide',function(event, f) {
            $(this).fadeOut(lag + 200, function() {
                if (f) f();
            });
        });
};

How i can optimize repeatable parts of code with callbacks?
Im trying to create separate function like this:

function cb(callback) {
    if (callback) callback();
};

... but just have a lot of asynchronous callbacks...


texts: Project Euler 8 - Largest product in a series


texts:
I am attempting to make an eCommerce site from scratch. Right now I have the following code that gets all the items from a Firebase Firestore database and then adds HTML into an items div element based on the item's info.

var items = [];
var itemsDiv = document.getElementsByClassName("items")[0];

db.collection("items").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        var docData = doc.data();
        items.push(docData);
    });
    renderItems();
});

function renderItems() {
  console.log(items);
  items.forEach(function(item) {
    itemsDiv.innerHTML += `

      ${item.name}
      ${item.condition}
      ${item.price}

    `
  });
}

What can I do to make my code better?


texts: Create a list of random numbers with sum = n

texts:
I want to create a list of random integers in the range [0, 9], that sums up to 100 in Excel, using VBA. The list should be printed in a single column.

The routine I've written is as follows:

Sub RandomList()
    Dim arr(100) As Integer
    Dim i As Integer

    i = 0
    Do
        arr(i) = Int(10 * Rnd())
        i = i + 1
    Loop Until WorksheetFunction.Sum(arr) >= 100

    arr(i - 1) = 100 - WorksheetFunction.Sum(arr) + arr(i - 1)
    Range("A1").Resize(i, 1) = Application.Transpose(arr)

End Sub

This gives the correct result, but I'm sure there are ways to improve it:

Initializing the size to 100, seems odd. I want to use a dynamic sized array, but I can't get it to work. I've tried different approaches, but all result in a list containing only zeros (or an error).
I tried to sum all elements except the last one, but I didn't manage to make it work. Therefore I had to sum all elements, and subtract the last one. I can't believe that's optimal.
Should I delete the (100-i) last elements of the list somehow, before writing it to Excel? How and why?
Is the last line a good way of writing to Excel, or is there a better way?
I'm looking for a nice and clean way of doing this task, not necessarily the fastest way

I can do the same thing using Function RandomList() too, but as far as I can tell, that's used when I want to call the function from the worksheet.

PS! I'm not interested in some builtin function that can do the task directly, as I'm doing this to learn VBA, not to do that specific task.

This is inspired by this (bad) question on SO. There are other approaches there that can be used, but they are substantially different. I'm wondering if the way I'm doing this is a "good way" of doing it, or if it's filled with "Bad practice" code.