texts: Using 'each' to print chunks of an array

texts:
Working through Day 2 of Ruby in "7 Languages in 7 Weeks" - the answer to the second question seems acceptable, the first one feels quite wrong. Any suggestions?

Print the contents of an array of sixteen numbers, four numbers at a
time, using just each.

group = 0

(1..16).each do |x|
    print x
    group = group + 1
    if group % 4 == 0
        puts
        group = 0
    end
end

Now, do the same with each_slice in Enumerable (copied directly from http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_slice)

(1..16).each_slice(4) {|x| p x}


texts:
So I have a view model (asp.net mcv 3 app) that when instantiated with a particular parameter, populates it's properties via a couple of calls to a web service in it's constructor.

public class QuizPreviewViewModel
{
    private IQuizServiceWrapper _service;
    public string QuizName { get; set; }
    public List<QuizQuestion> QuizQuestions { get; set; }
    public List<AnswerChoice> AnswerChoices { get; set; }
    public int QuizId { get; set; }

    public QuizPreviewViewModel()
    {
    }

    public QuizPreviewViewModel(int quizId )
    {
        _service = new QuizServiceWrapper();
        var quiz = _service.GetQuizHeader(quizId);
        var questions = _service.GetQuizQuestionsByQuiz(quizId).OrderBy(x => x.Order).ToList();
        QuizId = quizId;
        QuizName = quiz.QuizName;
        QuizQuestions = questions;
    }
}

I know I could just as easily perform the population in the controller, or possibly extract the code to populate the properties into a separate method or helper class.

I have read in various books/articles that both view models and controllers should be kept as clean as possible.  So I'm wondering what you all think of populating the view model in it's constructor.  Is this a decent practice, or a horrible idea?  Where is the best place to populate the view model?


texts: PHP RESTful API for a student repository

texts:
All of the codes are based on the PSR-2 standard. Also Dependency-Injection and Repository patterns are followed. I would love to hear some advices or comments.

StudentRepository Class

namespace REST;

use Slim\PDO\Database;

interface IStudentRepository
{
    //Functions to be defined
    public function __construct();
    public function getStudentNames($request, $response, array $args);
    public function getAll($request, $response, array $args);
    public function addStudent($name, $id);
    public function updateName($id, $new_name);
}

class StudentRepository implements IStudentRepository
{
    //Queries and MYSQL connection
    protected $pdo;

public function __construct()
{
    //Database connection
    $dsn = 'mysql:host=localhost;dbname=College_DB;charset=utf8';
    $usr = 'root';
    $pwd = '';

    $this->pdo = new \Slim\PDO\Database($dsn, $usr, $pwd);
}

public function getStudentNames($request, $response, array $args)
{
    $array_val = array();
    $sql = 'SELECT name FROM Students';
    $cntrl=0;
    foreach ($this->pdo->query($sql) as $row) {
        $array_val[$cntrl]=$row["name"];
        $cntrl++;
    }
    $n_response = $response->withJson($array_val, 200);
    return $n_response;
}

public function getAll($request, $response, array $args)
{
    $array_val = array();
    $sql = 'SELECT * FROM Students';

    foreach ($this->pdo->query($sql) as $row) {
        $array_val[$row["id"]]=$row["name"];
    }

    $n_response = $response->withJson($array_val, 200);
    return $n_response;
}

public function addStudent($id, $name)
{

    $stmt = $this->pdo->prepare('INSERT into Students(id,name) values(:id,:namee)');
    $stmt->bindParam(":id", $id, \Slim\PDO\Database::PARAM_STR);
    $stmt->bindParam(":namee", $name, \Slim\PDO\Database::PARAM_STR);

    $stmt->execute();
}

public function updateName($id, $new_name)
{
    $stmt = $this->pdo->prepare('UPDATE Students set name=:namee where id=:id');
    $stmt->bindParam(":id", $id, \Slim\PDO\Database::PARAM_STR);
    $stmt->bindParam(":namee", $new_name, \Slim\PDO\Database::PARAM_STR);

    $stmt->execute();
}
}

StudentController Class

<?php

namespace REST;

class StudentController
{
    protected $Student_DB;

public function __construct(IStudentRepository $Student_DB)
{
    $this->Student_DB=$Student_DB;
}

public function getStudents($request, $response, array $args)
{
    return $this->Student_DB->getAll($request, $response, $args);
}

public function getStudentNames($request, $response, array $args)
{
    return $this->Student_DB->getStudentNames($request, $response, $args);
}

public function addStudent($request, $response, array $args)
{
    if (array_key_exists("id", $args) && array_key_exists("name", $args)) {
        $id = $args["id"];
        $name = $args["name"];
        if (!is_numeric($id) || !ctype_alpha($name)) {
            $n_response = $response->withStatus(400);
            return $n_response;
        }
    }
    $this->Student_DB->addStudent($id, $name);
    $n_response = $response->withStatus(200);
    return $n_response;
}
}

Edit : I have edited the code in order to return JSON data with spesific status codes.


texts:
I have decided to make a basic C++ implementation of the std::map class, and I was checking that it is fine, as I am not sure if the operator[] is done correctly: should I be using the has_key function? e.t.c

template < typename _Key, typename _Ty, typename _Cmp = std::less<_Key>, typename _Alloc = std::allocator< std::pair<const _Key, _Ty> > > class map
{
public:
    typedef map<_Key, _Ty, _Cmp, _Alloc> _Myt;
    typedef _Key key_type;
    typedef _Ty mapped_type;
    typedef _Cmp compare_type;
    typedef _Alloc allocator_type;
    typedef std::pair<const key_type, mapped_type> value_type;
    typedef value_type *pointer;
    typedef const value_type *const_pointer;
    typedef value_type *iterator;
    typedef const value_type *const_iterator;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;

    map()
        : size_(0), capacity_(20), data_(_Alloc().allocate(20))
    {
    }

    map(const _Myt &_Rhs)
        : size_(_Rhs.size_), capacity_(_Rhs.size_ + 20), data_(_Alloc().allocate(_Rhs.size_))
    {
        int count = 0;
        for (iterator i = &_Rhs.data_[0]; i != &_Rhs.data_[_Rhs.size_]; ++i, ++count)
        {
            _Alloc().construct(&data_[count], *i);
        }
    }

    ~map()
    {
        if (!empty())
        {
            for (iterator i = begin(); i != end(); ++i)
            {
                _Alloc().destroy(i);
            }
            _Alloc().deallocate(data_, capacity_);
        }
    }

    _Myt &insert(const value_type &_Value)
    {
        if (++size_ >= capacity_)
        {
            reserve(capacity_ * 2);
        }
        _Alloc().construct(&data_[size_ - 1], _Value);
        return *this;
    }

    bool has_key(const key_type &_Key)
    {
        for (iterator i = begin(); i != end(); ++i)
        {
            if (i->first == _Key)
            {
                return true;
            }
        }
        return false;
    }

    mapped_type &operator[](const key_type &_Key)
    {
        if (has_key(_Key))
        {
            for (iterator i = begin(); i != end(); ++i)
            {
                if (i->first == _Key)
                {
                    return i->second;
                }
            }
        }
        size_type op = size_;
        insert(value_type(_Key, mapped_type()));
        return data_[op].second;
    }

    _Myt &reserve(size_type _Capacity)
    {
        int count = 0;
        if (_Capacity < capacity_)
        {
            return *this;
        }
        pointer buf = _Alloc().allocate(_Capacity);
        for (iterator i = begin(); i != end(); ++i, ++count)
        {
            _Alloc().construct(&buf[count], *i);
        }
        std::swap(data_, buf);
        for (iterator i = &buf[0]; i != &buf[size_]; ++i)
        {
            _Alloc().destroy(i);
        }
        _Alloc().deallocate(buf, capacity_);
        capacity_ = _Capacity;
        return *this;
    }

    bool empty()
    {
        return size_ == 0;
    }

    iterator begin()
    {
        return &data_[0];
    }

    iterator end()
    {
        return &data_[size_];
    }
private:
    pointer data_;
    size_type size_, capacity_;
};


texts: UIButton subclass with animated 'shimmer' effect

texts:
In earlier versions of iOS the lock screen had a 'slide to unlock' element which I'm referencing as a 'shimmer' effect.

The effect I'm looking for is simpler:

Button starts with single color (e.g. blue)
a band of color (e.g. red) sweeps across the text label from left to right
Repeat

Here's an example of my ShimmerButton class in action, and the code itself:

class ShimmerButton: UIButton {

    private let wrapperLayer = CALayer()
    private let gradientLayer = CAGradientLayer()

    var gradientColors: [UIColor] = [] {
        didSet {
            gradientLayer.colors = gradientColors.map({ $0.cgColor })
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // only needs to be set once, but no harm (?) in setting multiple times
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
        wrapperLayer.addSublayer(gradientLayer)
        layer.insertSublayer(wrapperLayer, at: 0)
        wrapperLayer.mask = titleLabel?.layer

        // update sublayers based on new frame
        wrapperLayer.frame = frame
        gradientLayer.frame.size = CGSize(width: frame.width * 4, height: frame.height)

        // remove any existing animation, and re-create for new size
        let animationKeyPath = "position.x"

        gradientLayer.removeAnimation(forKey: animationKeyPath)

        let animation: CABasicAnimation = CABasicAnimation(keyPath: animationKeyPath)

        animation.fromValue = bounds.width - gradientLayer.bounds.width / 2
        animation.toValue = gradientLayer.bounds.width / 2
        animation.duration = 3

        animation.repeatCount = HUGE
        animation.fillMode = kCAFillModeForwards
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

        gradientLayer.add(animation, forKey: animationKeyPath)
    }
}

Example usage:

let shimmer = ShimmerButton(frame: .zero)
shimmer.backgroundColor = .white
shimmer.setTitle("Find new skills...", for: .normal)
shimmer.titleLabel?.font = UIFont.systemFont(ofSize: 24, weight: UIFontWeightHeavy)
shimmer.sizeToFit()
shimmer.gradientColors = [.blue, .blue, .red, .blue, .blue]

Some questions:

Code that only needs to be once off is happening in layoutSubviews so will be called multiple times. I did this so I didn't have to override init?(coder:) and init(frame:). Is this acceptable, or just lazy on my part?
I'm animating the position of a CAGradientLayer to get the visual effect, but found that I needed to use another layer as a wrapper otherwise the text itself would move. Am I overlooking a solution that involves fewer layers?


texts: Tidying and deduplicating files listed in a DataGridView

texts:
I have the following code that searches through folder directories in a DataGridView table, and puts all files of the wanted format into a list, it also gathers a list of their last modified date for later use in the application.

The code works, but it is sore on the eyes. I want to tidy up the following loops to improve efficiency - what I mean is that I have a For loop within a For loop that creates the list of filenames, then I have two separate Do Until loops that search through the list from start to finish to pick out file names that need adjustment.

I would be very interested to learn a better way of achieving the same result, as my knowledge of efficiency in coding is quite elementary. Basically, can this be done in one or two loops, as the idea of looping through the Lists twice seems inefficient?

Public Class
Private Sub btnDirectory_Click(sender As Object, e As EventArgs) Handles btnDirectory.Click

Dim FileNames As New List(Of String)
Dim FileDates As New List(Of Date)

Dim DocNo As String
Dim rowCheck As String
Dim ProjectNo As String = "1111"
Dim FileNameCheck As String
Dim str As String

Dim k As Integer = 0
Dim i As Integer
Dim j As Integer

'The first loop grabs all files of the wanted format from a datagridview table containing all directories to be checked

For Each rw In Background.Table1.Rows

    rowCheck = Background.Table1(0, k).Value
    If Not String.IsNullOrEmpty(rowCheck) Then

    For Each file As String In My.Computer.FileSystem.GetFiles(Background.Table1(0, k).Value)
        CorrectType = False
        FileNameCheck = IO.Path.GetFileNameWithoutExtension(file)
        If FileNameCheck.Contains(ProjectNo) AndAlso FileNameCheck.Contains("-") AndAlso Not String.IsNullOrEmpty(FileNameCheck) AndAlso FileNameCheck.Contains(" ") Then
            DocNo = FileNameCheck.Substring(0, FileNameCheck.IndexOf(" "))
            If FileNameCheck.Substring(0, FileNameCheck.IndexOf("-")) = ProjectNo AndAlso CountLetters(DocNo) = 3 Then
                FileNames.Add(FileNameCheck)
                FileDates.Add(IO.File.GetLastWriteTime(file))
            End If
        End If

    Next
    End If

    k += 1

Next

'The next loop tidies up the file formats that contain a "-00-" in their names

 j = FileNames.Count
 i = 0
 Do
     str = FileNames(i)
     If str.Contains("-00-") Then
         FileNames(i) = RemoveChar(str, "-00-") ' RemoveChar is a function that replaces "-00-" with a "-"
     End If
     i += 1
 Loop Until i = j

 i = 0
 j = FileNames.Count

 'Finally, this loop checks that no two files have the exact same name, and gets rid of one of them if that is the case

 Do

     Dim st1 As String = FileNames(j - 1)
     Dim st2 As String = FileNames(j - 2)

     If st1 = st2 Then
         FileNames.RemoveAt(j - 1)
         FileDates.RemoveAt(j - 1)
     End If
     j -=  1
 Loop Until j = 1

 End Sub

End Class


texts:
I am using a Bash script to execute a Python script multiple times. In order to speed up the execution, I would like to execute these (independent) processes in parallel. The code below does so:

#!/usr/bin/env bash

script="path_to_python_script"
N=16 # number of processors
mkdir -p data/

for i in `seq 1 1 100`; do
    for j in {1..100}; do
    ((q=q%N)); ((q++==0)) && wait

    if [ -e data/file_$i-$j.txt ]
    then
        echo "data/file_$i-$j.txt exists"
    else
        ($script -args_1 $i > data/file_$i-$j.txt ;
        $script -args_1 $i -args_2 value -args_3 value >> data/file_$i-$j.txt) &
        fi
    done
done

However, I am wondering if this code follow common best practices of parallelization of for loops in Bash? Are there ways to improve the efficiency of this code?


texts:
I want to make a map object that key is object.

But, JavaScript only allows string as a hash key. (at least before ECMAScript6 comes?)

So, I tried to write auxiliary functions to emulate, hash-ish (but actually linear search).
Are there any suggestions on improvement?

var tabInfo = {};
var tabInfoKey = 0;

function getTabInfoItem(tab) {
  console.log("getTabInfoItem", tab);
  for(var key in tabInfo) {
    if(tabInfo[key].tab === tab) {
      return tabInfo[key].info;
    }
  }
}

function setTabInfoItem(tab, info) {
  console.log("setTabInfoItem", tab, info);
  for(var key in tabInfo) {
    if(tabInfo[key].tab === tab) {
      tabInfo[key] = {
        tab: tab,
        info: info
      };
      return;
    }
  }
  tabInfoKey++;
  tabInfo[tabInfoKey] = {
    tab: tab,
    info: info
  };
}

function deleteTabInfoItem(tab) {
  console.log("deleteInfoItem", tab);
  for(var key in tabInfo) {
    if(tabInfo[key].tab === tab) {
      delete tabInfo[key];
      return;
    }
  }
}


texts: Linked List design and implementation - C++

texts:
Seeking recommendations on how to improve this code, LL always seem to be a struggle.

A basic linked list that does include next and previous pointers. I used a struct inside of a class, which I'm not sure if that's frowned upon. The program includes 5 basic member functions, one to add to the head of the list, one to add to the tail of the list, one to delete the head, one to delete any index, one that checks the list for duplicate data (based on the data variable in the struct),  and a print. Everything works as it should, but I'm just not sure if I was efficient, in fact I'm pretty sure I wasn't. Sorry If im forgetting something, but I'm new here!

1.

class list
{
private:
    struct node
    {
        int data;
        node* next;
        node* prev;
    };

    typedef node* nodePtr;

    nodePtr head;
    nodePtr temp;
    nodePtr prev;

public:
    list();
    void add_to_head(int);
    void add_to_tail(int);
    void delete_index(int);
    void check_duplicates(int);
    void print();
};

2.

#include <iostream>
using std:: cout;
using std:: endl;

list::list(void)
{
    head = NULL;
    temp = NULL;
    prev = NULL;
}

void list:: add_to_head(int num)
{
    nodePtr n = new node;

    n->data = num;

    if(head == NULL)
    {
        n->prev = NULL;
        n->next = NULL;
        head = n;

    }
    else
    {
        n->next = head;
        n->prev = NULL;
        head = n;
    }

    return;
}

void list::add_to_tail(int num)
{
    nodePtr n = new node;

    n->data = num;

    if(head == NULL)
    {
        n->prev = NULL;
        n->next = NULL;
        head = n;
    }
    else
    {
        temp = head;

        while(temp->next != NULL)
        {
            temp = temp->next;
        }

        temp->next = n;
        n->prev = temp;
        n->next = NULL;
    }

    return;
}

void list::delete_index(int index)
{
    if(index == 0)
    {
        temp = head->next;
        temp ->prev = NULL;

        prev = head;
        delete prev;

        head = temp;
    }
    else
    {
        nodePtr del = new node;

        int count =0;
        temp = head;

        while(count != index)
        {
            prev = temp;
            temp = temp->next;
            count++;
        }

        del = temp;

        if(temp->next == NULL)
        {
            prev->next = NULL;
        }
        else
        {
            prev->next = temp->next;
            temp = temp->next;
            temp->prev = prev;
        }

        delete del;
    }

    return;
}

void list::check_duplicates(int num)
{
    int count = -1;

    temp = head;

    while(temp != NULL)
    {
        if(temp->data == num)
        {
            count++;
        }

        temp = temp->next;
    }

    if(count > 0)
    {
        cout<<endl<<endl<<"The number "<<num<<" was found "<<count + 1<<" times."<<endl;
    }

    else if(count == -1)
    {
        if(head == NULL)
        {
            cout<<"The list is empty."<<endl;
        }
        else
        {
            cout<<"The number was not found within the list."<<endl;
        }
    }

    return;
}

void list::print()
{
    temp = head;

    cout<<endl<<"The list:"<<endl;

    while(temp != NULL)
    {
        cout<<temp->data<<" ";
        temp = temp->next;
    }

    return;
}


texts:
I've gone back and forth a few times recently on my Perl coding style when it comes to module subroutines. If you have an object and you want to call the method bar with no arguments, then you can either do $foo->bar() or $foo->bar. At one point I started favoring the latter because I felt it cleaned up the code and made it more readable. However, sometimes I question whether it would be better to be fully explicit, especially considering the possibility that someone else will have to look at my code later — someone who almost certainly will not be an expert Perl programmer.

For example, consider this block of code. For the method calls that require arguments (get_tag_values and has_tag), there is no question about the parentheses. But what about next_feature and primary_tag? Is the readability I gain from dropping the parens worth losing the explicit syntax? Is one better than the other for long term maintainability? Or is this simply a subjective judgment call?

while( my $feature = $gff3->next_feature )
{
  if($type eq "cds")
  {
    if( $feature->primary_tag eq "mRNA" )
    {
      my($gene_id) = $feature->get_tag_values("Parent");
      my($mRNA_id) = $feature->get_tag_values("ID");
      next unless( $list eq '' or $genes_to_extract->{$gene_id} );
      $subseq_locations->{ $feature->seq_id }->{ $mRNA_id } = Bio::Location::Split->new();
    }
    elsif( $feature->primary_tag eq "CDS" )
    {
      my($mRNA_id) = $feature->get_tag_values("Parent");
      if( $subseq_locations->{ $feature->seq_id }->{ $mRNA_id } )
      {
        $subseq_locations->{ $feature->seq_id }->{ $mRNA_id }->add_sub_Location( $feature->location );
      }
    }
  }
  else
  {
    if( $feature->primary_tag eq $type )
    {
      my $feat_id;
      if( $list ne '')
      {
        ($feat_id) = $feature->get_tag_values("ID") if($feature->has_tag("ID"));
        next unless( $feature->has_tag("ID") and $genes_to_extract->{$feat_id} );
      }
      $subseq_locations->{ $feature->seq_id }->{ $feat_id } = Bio::Location::Split->new();
      $subseq_locations->{ $feature->seq_id }->{ $feat_id }->add_sub_Location( $feature->location );
    }
  }
}


texts: Meta functions for sequences of exponents of 2

texts:
I have implemented some meta functions to create sequence for exponents of 2. I would love to know if there is any way to make the code more optimized.
Note: int main() should not be modified. From the requirements of my school:

This program must implement three definitions: sequence<Ts...>, print() and printing_type().

Hence, the name of functions should not be modified.
#include<iostream>

template<size_t... Ts>
struct int_seq{};

template<size_t TCount, size_t...Ts>
struct sequence
{
    using type = typename sequence<TCount - 1,  1, (2 * Ts)...>::type;
};

template<size_t...Ts>
struct sequence<0, Ts...>
{
    using type = int_seq<Ts...>;
};

template<size_t TCount>
using create_int_seq  = typename sequence<TCount + 1>::type;

template <typename T>
void print(T val)
{
    std::cout << val << " ";
}

template <typename T, typename... Ts>
void print(T val, Ts... t)
{
    std::cout << val << " ";
    print(t...);
}

template <
    template <size_t...> class T,
    size_t... S
>
void printing_type(T<S...>)
{
    print(S...);
}

int main()
{
    constexpr size_t N = 63;
    create_int_seq<N> dum{};
    printing_type(dum);
}


texts: Incrementing and decrementing 3 seperate input values by 1 using Javascript

texts:
I have written the following Javascript code which increments and decrements 3 separate inputs by 1:

//INCREMENTS/DECREMENTS BEDROOMS BY 1

function plusOneBedrooms() {
    var addRoom = document.getElementById('rooms_amount_bedroom');
    value = parseInt(addRoom.getAttribute('value'), 10) + 1;
    addRoom.setAttribute('value', value);
    addRoom.innerHTML = value;

}

function minusOneBedrooms() {
    var subtractRoom = document.getElementById('rooms_amount_bedroom');
    value = parseInt(subtractRoom.getAttribute('value'), 10) - 1;
    subtractRoom.setAttribute('value', value);
    subtractRoom.innerHTML = value;

}

//INCREMENTS/DECREMENTS BATHROOMS BY 1
function plusOneBathrooms() {
    var addRoom = document.getElementById('rooms_amount_bathrooms');
    value = parseInt(addRoom.getAttribute('value'), 10) + 1;
    addRoom.setAttribute('value', value);
    addRoom.innerHTML = value;

}

function minusOneBathrooms() {
    var subtractRoom = document.getElementById('rooms_amount_bathrooms');
    value = parseInt(subtractRoom.getAttribute('value'), 10) - 1;
    subtractRoom.setAttribute('value', value);
    subtractRoom.innerHTML = value;

}
//INCREMENTS/DECREMENTS KITCHENS BY 1
function plusOneKitchens() {
    var addRoom = document.getElementById('rooms_amount_kitchens');
    value = parseInt(addRoom.getAttribute('value'), 10) + 1;
    addRoom.setAttribute('value', value);
    addRoom.innerHTML = value;

}

function minusOneKitchens() {
    var subtractRoom = document.getElementById('rooms_amount_kitchens');
    value = parseInt(subtractRoom.getAttribute('value'), 10) - 1;
    subtractRoom.setAttribute('value', value);
    subtractRoom.innerHTML = value;

}

        Bedrooms

            <input type="number" class="room_count" id="rooms_amount_bedroom" autocomplete="off" value="0">

        Bathrooms

            <input type="number" class="room_count" id="rooms_amount_bathrooms" autocomplete="off" value="0">

        Kitchens

            <input type="number" class="room_count" id="rooms_amount_kitchens" autocomplete="off" value="0">

I would like to be able to have the same functionality but feel I could have probably done this in a simpler way. I'm new to Javascript/JQuery so any suggestions will be appreciated. Thanks!


texts:
I'm using some simple files for caching and some basic user data. I was first just using file_put_contens and file_get_contents, but realized this could quickly go wrong when traffic starts increasing.

I've been trying to figure out how to do it properly with flock, correct file modes, etc, and come up with the following functions. Have I understood things correctly? Will this be safe in most normal use-cases, with small to medium web site usage?

class File
{

    public static function read($path, $default = NULL)
    {
        $fp = @fopen($path, 'r');
        if( ! $fp)
            return $default;

        flock($fp, LOCK_SH);
        $data = fread($fp, filesize($path));
        flock($fp, LOCK_UN);
        fclose($fp);

        return $data;
    }

    public static function write($path, $data)
    {
        self::check(dirname($path));

        $fp = fopen($path, 'c');
        flock($fp, LOCK_EX);
        ftruncate($fp, 0);
        fwrite($fp, $data);
        fflush($fp);
        flock($fp, LOCK_UN);
        fclose($fp);

        return $data;
    }

    public static function check($dir)
    {
        if( ! is_dir($dir))
        {
            // https://en.wikipedia.org/wiki/Chmod#System_call
            @mkdir($dir, 06750, true);
            @chmod($dir, 06750);
        }
        return $dir;
    }
}

Some particular things:

Should using LOCK_SH in read allow for multiple simultaneous reads?
(which will be the bulk of what's happening since writes will happen quite seldom)
Will using LOCK_EX in write make sure nobody else is reading or writing while the file is changed?
Will using the directory permission mask 06750 makes sure that

any files created in that directory will get the same permissions as the directory, and
the directory/file will only be writable by the web server user and readable by its group?


texts:
This is my take on an image → greyscale converter.

#greyscale.py -- Converts an image file to greyscale

from tkinter.filedialog import askopenfilename, asksaveasfilename
from graphics import *

def displayimage(imagefile):
    #Open image to get width and height
    image2convert = Image(Point(0, 0), imagefile)
    imgwidth = image2convert.getWidth()
    imgheight = image2convert.getHeight()

    #Set window size to image size and draw image to window
    win = GraphWin("Greyscale Converter", imgwidth, imgheight)
    image2convert.move(imgwidth/2, imgheight/2)
    image2convert.draw(win)

    return image2convert, win

def convert(image2convert, win):
    width = image2convert.getWidth()
    height = image2convert.getHeight()

    #For each row of pixels
    for pixelx in range(width):
        #For each column of pixels
        for pixely in range(height):
            print("Converted pixel: x:{0} y: {1}".format(pixelx, pixely))
            #Get Pixel Colour, calculate greyscale, set Pixel to calculated colour
            r, g, b = image2convert.getPixel(pixelx, pixely)
            brightness = int(round(0.299 * r + 0.587 * g + 0.114 * b))
            image2convert.setPixel(pixelx, pixely, color_rgb(brightness, brightness, brightness))
        #See progress for each row
        win.update()
    return image2convert

def main():
    imagefile = askopenfilename(filetypes=[("GIF-Image", ".gif"), ("PPM-Image", ".ppm")])

    image2convert, win = displayimage(imagefile)

    #convert after click
    win.getMouse()
    image2convert = convert(image2convert, win)

    #save new image
    outFile = asksaveasfilename(filetypes=[("GIF-Image", ".gif"), ("PPM-Image", ".ppm")])
    newImg = image2convert.save(outFile)

    #close file and window after click
    win.getMouse()
    image2convert.close()
    win.close()

main()

Opinions/Suggestions/Ideas? It is pretty slow, but I don't think that this approach can be much faster.


texts: SSE instruction to check if byte array is zeroes C#

texts:
My fundamental problem is how to check whether byte[] is full of zeroes. I posted a range of implementations (with timings) and one clearly beats others. In fact, it is so fast that I am having trouble believing it even works. I suggest taking a look at SO question page first. This is the winner code:

static unsafe bool IsAllZeros(byte[] data)
{
    fixed (byte* bytes = data) {
        int len = data.Length;
        int rem = len % (16*16);
        Vector16b* b = (Vector16b*)bytes;
        Vector16b* e = b + (len - rem) / (16*16);
        Vector16b zero = Vector16b.Zero;

        while (b+15 < e) {
            if (*(b)+*(b+1)+*(b+2)+*(b+3)+*(b+4)+*(b+5)+*(b+6)+*(b+7)+*(b+8)+
                *(b+9)+*(b+10)+*(b+11)+*(b+12)+*(b+13)+*(b+14)+*(b+15) != zero)
                return false;
            b += 16;
        }

        for (int i = 0; i < rem; i++)
            if (data [len - 1 - i] != 0)
                return false;

        return true;
    }
}

Project references Mono.Simd assembly. I checked the code for following issues so far:

Pointer arithmetic. Adding 1 to pointer moves it 16 bytes ahead. However loop is unrolled 16 times so iteration processes 256 bytes at a time.
Array length is in bytes while b e are in 16 byte vectors.
Loop condition checks if last element b+15 is within the array. End pointer e points to just outside of array.
Loop processes 16 vectors so it moves pointer by 16 elements.
Tail is processed for up to 15 vectors, each 16 bytes, one byte at a time.

Is this code correct?


texts: Conditional AND statement- which is more readable?

texts:
Does this function

automationStatusIsSuccessful = (data) ->
    data.Automation.Status isnt "FAILED" and data.Automation.Status isnt "COMPLETEDWITHERROR"`

make the conditional statement more readable or less readable?

With:

  automationStatusIsSuccessful = (data) ->
    data.Automation.Status isnt "FAILED" and data.Automation.Status isnt "COMPLETEDWITHERROR"

  checkIteration = (data) ->
    if iteration < Configuration.CHECK_ITERATIONS and automationStatusIsSuccessful(data)

Without:

checkIteration = (data) ->
  if iteration < Configuration.CHECK_ITERATIONS and data.Automation.Status isnt "FAILED" \
  and data.Automation.Status isnt "COMPLETEDWITHERROR"


texts: PowerShell - Find Least Common Multiple of a series of numbers

texts:
I am a Windows power user, a system tweaker, my idol is Leanardo da Vinci, and now I want to be a hacker.
I am extremely new to programming, but I really am a fast learner if I am interested in the subject, now I use PowerShell to hone my programming skills, I have only started learning PowerShell less than a month ago, and here is a script I have written without help dozen days ago to find lcm to test my skill.
This function accepts a string of numbers seperated by comma ",", finds the lcm of the series of numbers and returns it, I have confirmed it is working on PowerShell 7.1 x64 on Windows 10, I want to know if it can be shortened and still maintain human readability and clarity, without changing its logic, feel free to answer if you can help me improve it.
The Script:
Function Find-LCM {
PARAM (
[Parameter(ValueFromPipeline=$true)]
[System.String]$String,
[System.Double]$Number
)
$array=@()
[System.Double]$product=1
$Numbers = $String.Split(",")
foreach ($Number in $Numbers) {
    $sqrt=[math]::sqrt($number)
    $Factor=2
    $count=0
    while ( ($Number % $Factor) -eq 0) {
        $count+=1
        $Number=$Number/$Factor
        if (($array | Where-Object {$_ -eq $Factor}).count -lt $count) {
            $array+=$Factor
        }
    }
    $count=0
    $Factor=3
    while ($Factor -le $sqrt) {
        while ( ($Number % $Factor) -eq 0) {
            $count+=1
            $Number=$Number/$Factor
            if (($array | Where-Object {$_ -eq $Factor}).count -lt $count) {
                $array+=$Factor
                }
            }
        $Factor+=2
        $count=0
    }
    if ($array -notcontains $Number) {
        $array+=$Number
    }
}
foreach($arra in $array) {$product = $product * $arra}
$product
}

Edit: deleted $maxfactor=[math]::sqrt($number) line and revised prime factorization loop condition to while ($factor -le $number), I did so because when using square root as max factor to factorise 1920 it outputed 15 as a prime factor which is wrong, now it's fixed.
ReEdit: reimplemented square root as prime factorise while loop condition


texts:
Here is my solution to the following Daily Coding Problem challenge

  Given a string, find the palindrome that can be made by inserting the
  fewest number of characters as possible anywhere in the word. If there
  is more than one palindrome of minimum length that can be made, return
  the lexicographically earliest one (the first one alphabetically).

Example

Input: race

Output: ecarace

I used a PEP8 checker for this code and the only issue I couldn't fix was the "UPPER_CASE" naming style as I don't understand what I am supposed to do to fix this

import itertools

def find_palindrome(word, new_strings) -> str:
    """Find the first palindromic word of a given string by adding new letters"""
    for add_string in new_strings:
        for index in range(len(word)):
            new_word = word[:index] + "".join(add_string) + word[index:]
            if new_word == new_word[::-1]:
                return new_word

if __name__ == "__main__":
    word = "r"
    if word != word[::-1]:
        new_strings = sorted(list(itertools.chain.from_iterable(itertools.permutations(word, n)
                                                            for n in range(len(word)+1))))
        print(find_palindrome(word, new_strings))
    else:
        print(word)

EDIT
I noticed the find_palindrome function didn't return the first alphabetic palindrome so here is an update for this function

def find_palindrome(word, new_strings) -> str:
    """Find the first palindromic word of a given string by adding new letters"""
    add_string_length = 0
    list_new_words = []
    for add_string in new_strings:
        if len(add_string) > add_string_length and list_new_words:
            return (sorted(list_new_words)[0])
        add_string_length = len(add_string)
        for index in range(len(word)+1):
            new_word = word[:index] + "".join(add_string) + word[index:]
            if new_word == new_word[::-1]:
                list_new_words.append(new_word)

EDIT 2:
It turns out I had updated the main function too, so here is the update for that:

if __name__ == "__main__":
    word = "race"
    if word != word[::-1]:
        new_strings = sorted(list(itertools.chain.from_iterable(itertools.permutations(word, n)
                                                            for n in range(len(word)+1))),key=len)

        print(find_palindrome(word, new_strings))
    else:
        print(word)


texts:
I have a project from my college. I'm making a site which will display different quotations each time the page is loaded. I use the following code:

$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xlsx_db", $con);

$result = mysql_query("SELECT * FROM sheet1 ORDER BY RAND() LIMIT 1");

if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}

$row = mysql_fetch_array($result);
echo "Quote: ";
echo $row['quote']."
";
echo $row['by']."
";
?>

All works fine. But my teacher told me to make the text link-able. So that if anyone copy that link of the quote, that case, he can pest the code on the browser and can see that quote again.

Could anyone please help me with this task? Any kind of help is really appreciated.


texts: How can I improve my A* algorithm in Python?

texts:
I'm trying to implement my own A* pathfinder, but the voices in my head scream of better ways to do this.  Probably because I'm exceeding Python's default maximum recursion depth of 1000.

class PathFinder():

    ## grid is a list of 8 sub-lists, each containing 8 nodes.
    ## start and goal are tuples representing the grid indexes of my start and goal.

    def __init__(self, start, goal, grid):
        ## I don't do anything with these yet,
        ## just thought they would be good to have.
        self.goal = goal
        self.start = start
        self.grid = grid

    def find_path(self, start, goal, path=[]):

        ## My seemingly hackish method of looping through
        ## the 8 cells surrounding the one I'm on.
        for row in (-1,0,1):
            for col in (-1,0,1):
                if row == 0 and col == 0:
                    continue
                cell = [start[0]+row,start[1]+col]

                ## Catching the inevitable exception when I try to examine
                ## the surroundings of cells that are already on the edge.
                try:
                   ## Skip if the cell is blocked ("X").
                    if self.grid[cell[0]][cell[1]] == "X":
                        continue
                except IndexError:
                    continue

                path.append(cell)
                if cell == goal:
                    return path
                self.find_path(cell, goal, path)

def main():
    import Gridder2
    grid = Gridder2.board()
    start = (0,0)
    goal = (0,3)
    pt = PathFinder(start, goal, grid)
    print(pt.find_path(start, goal))

    return 0

if __name__ == '__main__':
    main()

My find_path function particularly seems like it needs work.  Seems like I should be able to calculate a path through an 8x8 grid with a recursion depth of less than 1000.

How can I improve this?


texts: Multi or n-armed bandit reinforcement learning in R

texts:
I am learning about reinforcement learning and came across the first and simplest form of reinforcement learning system called multi-armed reinforcement learning (also called as n-armed bandit). I have read Sutton's book and an outlace.com tutorial regarding this learning. Outlace.com has written a nice Python implementation of this learning which I rewrote as an R program.

#multi/n-armed bandit algorithm with greedy search
#original code http://outlace.com/Reinforcement-Learning-Part-1/

iter=500
n=10
arms=runif(n)
eps=0.1
av=rep.int(1,n)
counts=rep.int(0,n)

#reward function
reward<-function(prob){
  reward=0
  for (i in 1:100){
    if(runif(1)<prob){
      reward=reward+1
    }
    return(reward)
  }
}

bestArm<-function(a){
  return(max(a))
}

runMean=NULL
for (i in 1:iter){
  if(runif(1) > eps){
    # exploitation!(use best arm)
    choice=bestArm(av)
    counts[choice]=counts[choice]+1
    k = counts[choice]
    #reward for n arms
    rwd =  reward(arms[choice])
    old_avg = av[choice]
    new_avg = old_avg + (1/k)*(rwd - old_avg) #update running avg
    av[choice] = new_avg

  }else{
    # exploration!(test all arm)
    # choose a random lever 10% of the time.

    #randomly chose an arm
    choice=sample(arms,1)
    counts[choice]=counts[choice]+1
    old_avg = av[choice]
    new_avg = old_avg + (1/k)*(rwd - old_avg) #update running avg
    av[choice] = new_avg
  }
  runMean[i]=mean(av)
}
plot(runMean)

I don't know whether the output is correct because I don't understand some parts of the code and just copy pasted it.

Python

choice = bestArm(av)
counts[choice] += 1
k = counts[choice]
rwd =  reward(arms[choice])
old_avg = av[choice]
new_avg = old_avg + (1/k)*(rwd - old_avg) #update running avg
av[choice] = new_avg

R

choice=bestArm(av)
counts[choice]=counts[choice]+1
k = counts[choice]
#reward for n arms
rwd =  reward(arms[choice])
old_avg = av[choice]
new_avg = old_avg + (1/k)*(rwd - old_avg) #update running avg
av[choice] = new_avg

It runs and doesn't show any errors even after using most of the original Python code.


texts: Replacing strings to have a single blank

texts:
In Kernighan and Ritchie (the C programming language):

  Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

I wrote the following code.  Do you have advice to improve it?

#include <stdio.h>

/* copy input to output, replacing each
string of one or more blanks by a single blank */

main(){

    int c;
    double nc;
    char otherBlank;

    otherBlank = 'f';

    while ((c = getchar()) != EOF){
        if (otherBlank == 't' && c != ' '){
            /* read a non blank and had a blank before */
            putchar(' ');
            putchar(c);
            otherBlank = 'f';
        }

        else if (c == ' ')
            /* read a blank */
            otherBlank = 't';

        else
            /* read a non blank and had no blank before */
            putchar(c);

    }

}


texts:
I don't want to serialize everything. I created a custom attribute DoNotSerializeAttribute. If some property in info contain that attribute then ignore it and do not serialize it.

Is my code bug-free? Maybe I can improve it or I miss something?

class Program
{
    static void Main(string[] args)
    {
        var s = Serialize(new BackgroundJobInfo {Text = "toto", BackgroundJob = new BackgroundJob { Password = "pass"}});
        var myJob = Deserialize(s);
    }

    public static string Serialize(BackgroundJobInfo info)
    {
        using (var stringWriter = new StringWriter(CultureInfo.InvariantCulture))
        {
            var writer = XmlWriter.Create(stringWriter);
            var dataContractSerializer = new DataContractSerializer(typeof(BackgroundJobInfo),
                                                                    null,
                                                                    int.MaxValue,
                                                                    true,
                                                                    true,
                                                                    new MySurrogate());
            dataContractSerializer.WriteObject(writer, info);
            writer.Flush();

            return stringWriter.ToString();
        }
    }

    public static BackgroundJobInfo Deserialize(string info)
    {
        using (var stringReader = new StringReader(info))
        {
            try
            {
                var xmlReader = XmlReader.Create(stringReader);
                var dataContractSerializer = new DataContractSerializer(typeof(BackgroundJobInfo));
                return (BackgroundJobInfo) dataContractSerializer.ReadObject(xmlReader);
            }
            catch (Exception e)
            {
                // hopefully, will never happen
                return null;
            }
        }
    }
}

internal class MySurrogate : IDataContractSurrogate
{
    public Type GetDataContractType(Type type)
    {
        return typeof (BackgroundJobInfo);
    }

    public object GetObjectToSerialize(object obj, Type targetType)
    {
        var maskedProperties = obj.GetType().GetProperties();
        var b = maskedProperties.Where(m => m.GetCustomAttributes(typeof(DataMemberAttribute), true).Any() &&
                                            m.GetCustomAttributes(typeof(DoNotSerializeAttribute), true).Any());
        foreach (var member in b)
        {
            member.SetValue(obj, null, null);
        }
        return obj;
    }

internal class DoNotSerializeAttribute : Attribute
{
}

[KnownType(typeof(BackgroundJob))]
[DataContract]
public class BackgroundJobInfo
{
    [DataMember(Name = "text")]
    public string Text { get; set; }

    [DataMember(Name = "backgroundJob")]
    public BackgroundJob BackgroundJob { get; set; }
}

[DataContract]
public class BackgroundJob
{
    [DataMember(Name = "password")]
    [DoNotSerializeAttribute]
    public string Password { get; set; }
}


texts:
I was surprised that I didn't find this approach to logging anywhere while reading up on the subject. So, naturally, I think I may be doing something wrong. I set up some simple tests, and this seems to work:

First, the source: log.py

import datetime
import logging
import os

import config

#this is very straightforward, nothing special here.
log = config.Parser('log')

def setup(stream_level=logging.INFO):
    """shared log named {log.name + log.format}.log
    call this logging setup method once, in the main function
    always refer to the config file when referring to the logger

    in modules other than the main file, call a reference to the
    already created logger in memory via log.hook(module_name)
    as long as this setup() was ran in the main method, the logfile
    should already exist in the proper place, with streams created
    for use, according to the config file entry for 'log'.

    `stream_level` indicates what level of
    detail should be printed to the terminal
    """

    log.level = log.level.upper()

    logger = logging.getLogger(log.name)
    logger.setLevel(log.level)

    formatter = logging.Formatter(log.format)
    formatter.datefmt = log.datefmt

    pretty_date = datetime.date.strftime(datetime.datetime.now(), log.datefmt)
    date_ext = filter(lambda x: x.isdigit(), pretty_date)

    #terminal logging
    if stream_level:
        ch = logging.StreamHandler()
        ch.setLevel(stream_level)
        ch.setFormatter(formatter)

    #file logging
    logname = ''.join([log.name, date_ext, '.log'])
    fh = logging.FileHandler(os.path.join(log.dir, logname))
    fh.setLevel(log.level)
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    if stream_level:
        logger.addHandler(ch)

    return logger

def hook(module_name):
    """pass in the special method __name__ for best results
    don't call this until you've setup() the logger in your main function
    """
    return logging.getLogger('.'.join([log.name, module_name]))

And the main.py

import util
import log

logger = log.setup()

logger.info('starting now')

util.p()

logger.critical('quitting!')

util.py

import log

def p():
    logger = log.hook(__name__)
    for x in range(10):
        logger.warn('.')


texts:
I am creating a HTML game where you fight monsters and stuff and this is part of the game loop for dealing damage:

var hp = 1000000000;
var speed = 10;
var power = 5;

var lastCalledTime;
var fps;

var GameLoop = function() {
    if(!lastCalledTime) {
           lastCalledTime = new Date().getTime();
           fps = 0;
           return;
    }
    delta = (new Date().getTime() - lastCalledTime)/1000;
    lastCalledTime = new Date().getTime();
    fps = 1/delta;

    hp = hp - (5 * speed * 0.1) / fps;
};

var animFrame = window.requestAnimationFrame ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame    ||
                window.oRequestAnimationFrame      ||
                window.msRequestAnimationFrame     ||
                null ;

if ( animFrame !== null ) {
    var recursiveAnim = function() {
        GameLoop();
        animFrame( recursiveAnim );
    };
    animFrame( recursiveAnim );
} else {
    setInterval( GameLoop, 33.33 );
}

http://jsfiddle.net/u0k7tbv4/2/

Power is how much you deal with each attack and each level of speed gives 0.1 attack / second. With 5 Power and 10 Speed it should deal 5 damage every second and that seems to be the case in the fiddle.

But I'm not sure, I only used requestAnimationFrame because I heard setInterval is unstable and so it would be nice if someone could validate the code.


texts: Algorithm for auto tiling of tiles in a 2D tile map

texts:
Introduction
I have implemented an algorithm that applies auto tiling to a 2D tile map for a game, selecting the correct tiles according to their neighborhood. Given a string representation in a classic roguelike form such as this

the algorithm yields a generated map with properly connected tiles as follows

Algorithm
The general idea of the algorithm is to create a distinct bitmask that indicates in which directions neighbors of the same kind are already available.

In the sample image a tile in the center has a value based on its adjacent tiles (and corners under a particular conditition described later). Since the adjacent tiles at N, NE and E are of the same kind the tile has a total value of 2 + 4 + 16.
Corners only contribute to the value of a tile if their cardinal neighbors connecting the corners to the center are of the same kind as well. Therefore the SE and SW tiles would not be considered for calculation of the tile value no matter their kind unlike the NE tile.
The mapping of adjacencies to tiles is visualized in my use case as follows:

Implementation
Using this algorithm one has 48 different configurations and mappings of tile value to actual tile/sprite from the tileset. I have cleaned some parts of my code and would like to receive further input what may be improved. The core problem was to compute the atlas index to deduce the coordinates in the atlas via the std::unordered_map.
All unrelated data and methods have been removed from the code for review purposes:
class TileMap : public sf::Drawable, public sf::Transformable {
public:
  auto loadFromString(const std::string &String, const sf::Vector2<uint16> Size)
      -> bool {
    Data = String;
    Width = Size.x;
    Height = Size.y;

    // ... snip ...

    for (auto Column = 0; Column < Width; ++Column) {
      for (auto Row = 0; Row < Height; ++Row) {
        auto Tile = Data[Column + Row * Width];

        // ... snip ...

        auto Index = atlasIndexAt(Column, Row, Tile);
        auto AtlasPosition = Atlas[Index];

        // ... snip ...
      }
    }

    return true;
  }

private:
  auto atlasIndexAt(const uint16 Column, const uint16 Row, const char Tile)
      -> uint8 {
    auto T = tileValueAt(Column, Row - 1, Tile);
    auto L = tileValueAt(Column - 1, Row, Tile);
    auto R = tileValueAt(Column + 1, Row, Tile);
    auto B = tileValueAt(Column, Row + 1, Tile);
    // Corners are only relevant if both cardinals connecting the corner to the
    // center tile have positive value.
    auto TL = (T == 0 || L == 0) ? 0 : tileValueAt(Column - 1, Row - 1, Tile);
    auto TR = (T == 0 || R == 0) ? 0 : tileValueAt(Column + 1, Row - 1, Tile);
    auto BL = (B == 0 || L == 0) ? 0 : tileValueAt(Column - 1, Row + 1, Tile);
    auto BR = (B == 0 || R == 0) ? 0 : tileValueAt(Column + 1, Row + 1, Tile);
    return TL * 1 + T * 2 + TR * 4 + L * 8 + R * 16 + BL * 32 + B * 64 +
           BR * 128;
  }

  auto tileValueAt(const uint16 Column, const uint16 Row, const char Tile)
      -> uint8 {
    if (Column >= Width || Row >= Height ||
        Column == std::numeric_limits<uint16>::max() ||
        Row == std::numeric_limits<uint16>::max()) {
      return 1;
    }
    return Data[Column + Row * Width] == Tile ? 1 : 0;
  }

  // ... snip ...

  uint16 Width;
  uint16 Height;
  std::string Data;
  std::unordered_map<uint8, sf::Vector2<uint8>> Atlas{
      {208, sf::Vector2<uint8>(0, 0)},
      {248, sf::Vector2<uint8>(1, 0)},
      {104, sf::Vector2<uint8>(2, 0)},
      // ... snip ...
  };
};


texts: Null object design pattern in a linked list

texts:
I'm trying to create a doubly linked list using the null object design pattern. I've implemented four classes: a node abstract class, nullnode and datanode classes for the null node object and the linkedlist class, for the linked list implementation. I'm not sure if I've done this correctly.

Can anyone tell me if I am correctly using the null object design pattern and if not, how I can fix it?

/* Node abstract class */
class node{
public:

node();

    node(int el) { element = el; }

    /* Return pointer to next node */
    node* getNext() { return next; }

    /* Set pointer to next node */
    void setNext(node* n) { next = n; }

    /* Return pointer to prev node */
    node* getPrev(){ return prev; }

    /* Set pointer to prev node */
    void setPrev(node* n) { prev = n; }

    /* Return element stored in node */
    int getElement() { return element; }

    /* Set element stored in node */
    void setElement(int e) { element = e; }

    node* self();

private:
    // pointer to next node
    node* next;

    // pointer to prev node
    node* prev;

    // element stored in node
    int element;
};

/* Null node class */
class NullNode : public node{
public:

    /* Return pointer to next node */
    node* getNext() { return NULL; }

    /* Set pointer to next node */
    void setNext(node* n){ /* Do Nothing */ }

    /* Return pointer to prev node */
    node* getPrev() { return NULL; }

    /* Set pointer to prev node */
    void setPrev(node* n){ /* Do Nothing */ }

    /* Return element stored in node */
    int getElement() { return -1; }

    /* Set element stored in node */
    void setElement(int e){ /* Do Nothing */ }

    node* self(){ return NULL; }

};

/* datanode class */
class dataNode : public node{

public:

    dataNode(int ele) { node::node(); }

    // Return pointer to next node
    node* getNext() { return node::getNext(); }

    // Set pointer to next node
    void setNext(node* n){ node::setNext(n); }

    // Return pointer to prev node
    node* getPrev() { return node::getPrev(); }

    // Set pointer to prev node
    void setPrev(node* n){ node::setPrev(n); }

    // Return element stored in node
    int getElement() { return node::getElement(); }

    // Set element stored in node
    void setElement(int e){ node::setElement(e); }

    node* self(){ return this; }

};

/* linked list class */
class linkedlist{
public:

    linkedlist(){
        container.setNext(&container);
        container.setPrev(&container);
    }

    ~linkedlist();

    // Insert an element at the beginning of the list
    dataNode* insertHead(int element);

    // Return pointer to first node in list
    dataNode* getHead() { return (container.getNext())->self(); }

    // Return pointer to last node in list
    dataNode* getTail() { return (container.getPrev())->self(); }

    void insertBefore(dataNode* n, int e);

    void insertAfter(dataNode* n, int e);

// Remove specified node
void remove(dataNode* n);

private:
    // Pointer to first node in list
    NullNode container;
};


texts: Find how much reputation a user had on a given date

texts:
I saw this question on MSE and went ahead and wrote a solution to it:
https://meta.stackexchange.com/questions/313561/determining-users-reputation-as-of-particular-date

This calculates the reputation a user should have had at a certain date. I attempt to factor in everything that SEDE allows me to see. So -1 events from downvoting posts and serial voting reversal as well as the documentation reputation aren't factored in.

I'm curious about what could be improved here

SELECT
-- Total Reputation
(
SUM(CASE WHEN r2d.ReputationFromVotes + r2d.ReputationFromSuggestedEdits > 200 THEN 200 ELSE r2d.ReputationFromVotes + r2d.ReputationFromSuggestedEdits END)
+ SUM(r2d.ReputationFromBounties)
+ COALESCE((SELECT SUM(v4.BountyAmount * -1) FROM Votes AS v4 WHERE v4.VoteTypeId = 8 AND v4.UserId = ##UserId## AND v4.CreationDate < ##UntilDate:string## ),0)
+ COALESCE((SELECT COUNT(*) * 2 FROM Posts AS p3 WHERE p3.OwnerUserId = ##UserId## AND p3.AcceptedAnswerId IS NOT NULL),0)
+ SUM(r2d.ReputationFromAccepts)
) AS TotalReputation,
-- Rep Capped Activities with the Cap Factored in
SUM(
CASE
WHEN r2d.ReputationFromVotes + r2d.ReputationFromSuggestedEdits > 200 THEN 200
ELSE r2d.ReputationFromVotes + r2d.ReputationFromSuggestedEdits
END) AS ReputationFromRepCap,
-- Total Bounties recieved
SUM(r2d.ReputationFromBounties) AS ReputationFromBounties,
-- Total Bounties given
COALESCE((SELECT SUM(v4.BountyAmount * -1) FROM Votes AS v4 WHERE v4.VoteTypeId = 8 AND v4.UserId = ##UserId## AND v4.CreationDate < ##UntilDate:string## ),0) AS ReputationGivenAsBounties,
-- Total Reputation from Accepting Answers
COALESCE((SELECT COUNT(*) * 2 FROM Posts AS p3 WHERE p3.OwnerUserId = ##UserId## AND p3.AcceptedAnswerId IS NOT NULL),0) AS ReputationFromAcceptingAnswers,
-- Total Reputation from Accepted Answers
SUM(r2d.ReputationFromAccepts) AS ReputationFromAcceptedAnswers

FROM

(

SELECT
v.CreationDate AS VoteDate,

-- Total Reputation from Post Upvotes
-- PostTypeId 1 = Question, 2 = Answer
-- VoteTypeId 2 = Upvote, 3 = Downvote
-- CommunityOwnedDate is when a post was made CW.
-- Votes before that count, after not.
-- Vote Date is truncated to full days only so grouping works
SUM((CASE
  WHEN (p.PostTypeId = 1 AND v.VoteTypeId = 2 AND (p.CommunityOwnedDate > v.CreationDate OR p.CommunityOwnedDate IS NULL)) THEN 5
  WHEN (p.PostTypeId = 2 AND v.VoteTypeId = 2 AND (p.CommunityOwnedDate > v.CreationDate OR p.CommunityOwnedDate IS NULL)) THEN 10
  WHEN (v.VoteTypeId = 3 AND (p.CommunityOwnedDate > v.CreationDate OR p.CommunityOwnedDate IS NULL)) THEN -2
  ELSE 0
END)) AS ReputationFromVotes,

-- Total Reputation from Answer Bounties
-- VoteTypeId 9 = Bounty Close (Bounty Awarded)
-- BountyAmount = Amount of Reputation awarded
SUM(CASE
  WHEN v.VoteTypeId = 9 THEN v.BountyAmount
  ELSE 0
END) AS ReputationFromBounties,

-- Total Reputation from Answer Accepts
-- VoteTypeId 1 = AcceptedByOriginator (Answer Accepted)
SUM(CASE
  WHEN (v.VoteTypeId = 1 AND (p.CommunityOwnedDate > v.CreationDate OR p.CommunityOwnedDate IS NULL)) THEN 15
  ELSE 0
END) AS ReputationFromAccepts,

-- Total Reputation from Suggested Edits
-- if ApprovalDate isn't NULL and RejectionDate is NULL it's been approved and not overriden
-- Group by the same Date as Votes for Rep-Cap evaluation (They count towards it)
COALESCE((SELECT
SUM(CASE WHEN (se.ApprovalDate IS NOT NULL AND se.RejectionDate IS NULL) THEN 2 ELSE 0 END)
FROM SuggestedEdits AS se
WHERE se.OwnerUserId = ##UserId##
AND YEAR(v.CreationDate) = YEAR(se.ApprovalDate)
AND MONTH(v.CreationDate) = MONTH(se.ApprovalDate)
AND DAY(v.CreationDate) = DAY(se.ApprovalDate) ),0) AS ReputationFromSuggestedEdits

FROM Posts AS p
INNER JOIN Votes AS v ON v.PostId = p.Id

WHERE p.OwnerUserId =  ##UserId:int##
AND v.CreationDate <= ##UntilDate:string##

GROUP BY v.CreationDate

) as r2d


texts:
I've been learning more about PHP Objects and Classes, and my immediate reaction was to create a Database Object for handling the MySQLi Connection, Statements and Results.  Its not meant to be an ultimate do-all object, but help with WET code.  Obviously this has been done before... at least a hundred times.

There's no question lingering on whether I should be doing this, my question is more along the lines of am I doing this right?.

Basically I don't want to write out 10+ lines of code each time I make an SQL statement, let alone deal with the other functions that take place.  So I made an object that can do the SQL connection, statement, and get results.  The goal was to make the interaction as simple as possible and I like to think I achieved that.  Thoughts?

Usage:

Create the Object

$db = new Sqli();

Execute a Statement

$db->statement($sql, $param)

$db->statement("SELECT column_name FROM table WHERE = ?", "bind_me")

$db->statement("INSERT INTO table (col1, col2, col3) VALUES (?, ?, ?)", [$foo, $bar, $baz]);

Print Results

print_r($db->result());

JSON Result

print json_encode($db->result());

PHP Code:

class Sqli
{
    const DBHOST = "localhost";
    const DBUSER = "";
    const DBPASS = "";
    const DBNAME = "";

    protected $conn;
    protected $stmt;

    function __construct()
    {
        $this->setConnection();
    }

    private function setConnection()
    {
        mysqli_report(MYSQLI_REPORT_STRICT|MYSQLI_REPORT_ERROR);
        try
        {
            $conn = new mysqli(
                self::DBHOST,
                self::DBUSER,
                self::DBPASS,
                self::DBNAME
            );
        }
        catch(MySQLi_sql_exception $e)
        {
            throw new \MySQLi_sql_exception(
                $e->getMessage(),
                $e->getCode()
            );
        }
        $this->conn = $conn;
    }

    public function statement($sql, $param)
    {
        $stmt   = $this->conn->prepare($sql);

        if($param !== FALSE)
        {

            if(!is_array($param))
            {
                $param = [$param];
            }

            $types = str_repeat("s", count($param));

            $stmt->bind_param($types, ...$param);
        }

        $stmt->execute();

        $stmt->store_result();

        $this->stmt = $stmt;
    }

    public function result()
    {
        $stmt = $this->stmt;

        $meta = $stmt->result_metadata();

        while($field = $meta->fetch_field())
        {
            $param[] = &$row[$field->name];
        }

        call_user_func_array([$stmt, "bind_result"], $param);

        while($stmt->fetch())
        {

            foreach($row as $key => $val)
            {
                $r[$key] = filter_var($val, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW|FILTER_FLAG_ENCODE_AMP);
            }
            $result[] = $r;
        }

        return $result;
    }
}


texts: Better way to do multiple try/except in Python

texts:
I have this code:

    lengths = []
    lengths.append(len(self.download_links))
    lengths.append(len(self.case_names))
    lengths.append(len(self.case_dates))
    lengths.append(len(self.docket_numbers))
    lengths.append(len(self.neutral_citations))
    lengths.append(len(self.precedential_statuses))

Unfortunately, any of those object properties can be None, so I need to check each with either an if not None block or a try/except block. Checking each individually will blow up the size and conciseness of the code.

I assume there must be a better way for this kind of pattern, right?


texts:
I am trying to implement a program which can convert number into words. My code can convert numbers between 0 - 999.  It uses recursive function calls and simple arithmetic operations. Can you please review it and give me your feedback?

I used three different vectors to store words such as "Six" and "Eleven" and then access there indexes according to your input.

numberToWord.h

#ifndef numberToWord_H
#define numberToWord_H

#include <vector>
#include <string>

class numbertoword
{
public:
    numbertoword();
    ~numbertoword(){};

public:
    std::vector<std::string> one2nine;
    std::vector<std::string> elevent2ninteen;
    std::vector<std::string> twoDigit;
    std::vector<std::string> threeDigit;

public:
    void initialize();
    void convert(int number);
    int countNumber(int number);
    void calculate(int number, int count);
    void display(int digit);

private:
    int xN, yN;
    int originalNumber;

};

#endif

Source.cpp

#include <iostream>
#include "numberToWord.h"

numbertoword::numbertoword() : xN(0), yN(0), originalNumber(0)
{
}

void numbertoword::initialize()
{
    //one to nine
    one2nine.push_back("Zero");
    one2nine.push_back("One");
    one2nine.push_back("Two");
    one2nine.push_back("Three");
    one2nine.push_back("Four");
    one2nine.push_back("Five");
    one2nine.push_back("Six");
    one2nine.push_back("Seven");
    one2nine.push_back("Eight");
    one2nine.push_back("Nine");

    //eleven to ninteen
    elevent2ninteen.push_back("Eleven");
    elevent2ninteen.push_back("Twelve");
    elevent2ninteen.push_back("Thirteen");
    elevent2ninteen.push_back("Fourteen");
    elevent2ninteen.push_back("Fifteen");
    elevent2ninteen.push_back("Sixteen");
    elevent2ninteen.push_back("Seventeen");
    elevent2ninteen.push_back("Eighteen");
    elevent2ninteen.push_back("Nineteen");

    //TwoDigit
    twoDigit.push_back("Ten");
    twoDigit.push_back("Twenty");
    twoDigit.push_back("Thirty");
    twoDigit.push_back("Forty");
    twoDigit.push_back("Fifty");
    twoDigit.push_back("Sixty");
    twoDigit.push_back("Seventy");
    twoDigit.push_back("Eighty");
    twoDigit.push_back("Ninety");

    //threeDigit
    threeDigit.push_back("Hundred");
}

void numbertoword::display(int digit)
{
    if( originalNumber < 10)
    {
        std::cout<< one2nine[digit]<<" ";
    }
    else if( originalNumber < 20)
    {
        std::cout<< elevent2ninteen[digit - 1]<<" ";
    }
    else if( originalNumber < 100)
    {
        std::cout<< twoDigit[digit - 1]<<" ";
    }
    else if( originalNumber < 1000)
    {
        std::cout<<one2nine[digit]<<" "<<threeDigit[0]<<" ";
    }
}

void numbertoword::calculate(int number, int count)
{
    if( number < 10)
    {
        display(number); return;
    }

    xN = number / count;
    yN = number - (xN * count);

    if( number < 20 && number != 10)
    {
        display (yN ); return;
    }
    else if(number < 100 && yN == 0)
    {
        display( xN ); return;
    }
    else if(number < 100 )
    {
        display( xN );
    }
    else if(number < 1000 && yN == 0)
    {
        display(xN);
        return;
    }
    else if(number < 1000 )
    {
        display(xN);
    }
    originalNumber = yN;
    count = countNumber(originalNumber);
    calculate(yN, count);

}

int numbertoword::countNumber(int number)
{
    int c = 1;
    while( number > 9)
    {
        number = number / 10;
        c *= 10;
    }

    return c;
}

void numbertoword::convert(int number)
{
    initialize();

    originalNumber = number;

    int c = countNumber(number);
    calculate(number, c);

}

int main()
{
    numbertoword n2w;
    n2w.convert(999);

    std::cin.get();
    return 0;
}


texts: Exception handling with expression lambda in Presenter class

texts:
Following is a code snippet from MVP Win Forms application.

My DAL doesn't handle exceptions and it will be propagated up to the calling method in the presenter classes where the exception will be handled.

I'm using a single handler called ExecutAction(Action action) so I'm catching exceptions in one place rather than repeating it in every method.

At the moment, I'm not logging errors just alert the user for an action, trying to keep the system alive.

When showing messages to users, Presenters will use static class MessagingService's ShowErrorMessage(). So that I can customize all massage boxes in one place.

    class BankAccountPresenter : BasePresenter
    {
        IBankAccount _Model;
        IBankAccountView _View;
        IDataService _DataService;

        public BankAccountPresenter(IBankAccount model, IBankAccountView view, IDataService dataService)
        {
            _DataService= dataService;
            _Model = model;
            _View = view;

            this.SetViewPropertiesFromModel(_Model, _View);

            this.WireUpViewEvents();
        }

        private void WireUpViewEvents()
        {
            this._view.Search += new EventHandler(_view_Search);
        }

        private void _view_Search(object sender, EventArgs e)
        {
            this.Search();
        }

        private void Search()
        {
            ExecutAction(() =>
            {
                var info = _DataService.GetByACNo(_model.AccountNumber);

                if (info != null)
                {
                    _Model = info ;
                    this.SetViewPropertiesFromModel(_Model, _View);
                }
                else
                {
                    MessageBox.Show ("Bank account not found");
                }
            });
        }

        private void ExecutAction(Action action)
        {
            try
            {
                action();
            }

            catch (NullReferenceException e) { MessagingService.ShowErrorMessage(e.Message); }
            catch (System.Data.SqlTypes.SqlTypeException e) { MessagingService.ShowErrorMessage(e.Message); }
            catch (System.Data.SqlClient.SqlException e) { MessagingService.ShowErrorMessage(e.Message); }
        }
    }

Could you please review the above code and let me know whether this approach is good?

Also could you show me a better way to handle showing user messages than using a static?

Does use of lambda statements in every method (ExecutAction(() =>) degrade code readability? or is it a good practice keep things in one place in this way?


texts: OpenCV calculate center of mass for a single contour

texts:
I was recently going through some OpenCV code that finds the center of mass in a contour and realized there is potential room for optimisation.

What I noticed looking back through my code is when I calculate the mass I'm using contours.size() which makes me believe that I'm calculating the moments and center of mass for all of my contours.

In my cases this is not needed as I have a function that returns the largest contour that I have found getMaxAreaContourId(contours, imageSize); which returns an int that I can use like contours[largestContour] and largestContour would be set from the result of getMaxAreaContourId

So if I'm not mistaken would I be able to just find the moment and mass from a single contour and completely remove two for loops?

Because Ultimately I end up doing this:

int CenterOfContourX = mc[largestContour].x;
 int CenterOfContourY = mc[largestContour].y;

Really the end goal is to end up with two integers that represent the center of mass of my contour.

Code to optimise:

// Get the moments
mu.reserve(contours.size());
for( int i = 0; i < contours.size(); i++ )
{ mu[i] = moments( contours[i], false ); }

// Get the mass centers:
std::vector<cv::Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }


texts:
I've written a small C function to handle the builtin commands of a custom shell that I'm writing in C. Is it better to use a switch instead?

int handleBuiltinCommands(char *input, int ret) {
    int built_in_command = 0;
    if (strcmp(input, "exit") == 0) {
        free(input);
        exit(0);
    }
    if (StartsWith(input, "cd")) {
        built_in_command = 1;
        runcd(input);
    }
    if (StartsWith(input, "checkEnv")) {
        built_in_command = 1;
        checkEnv(ret);
    }
    return built_in_command;
}

I compile it with gcc -pedantic -Wall -ansi -O3

(Background: Tokenizing a shell command)


texts: Method to return statistics from a collection with O(1) time and space

texts:
I have a DelayQueue, and the goal is to collect statistical information from the collection in O(1) time and space from getStatistics(). The stream for loop does not provide it. However I thought of keeping statistics updated on add of a transaction. But this will not guarantee that at the time when the getStatistics() called the queue will contain only unexpired item, and therefore I would need to iterate anyway. Or maybe the whole architecture here is not correct. I had also other thoughts, like having background task, with waiting time of the difference of the oldest transaction to drain the queue, and running it when that time expires, and update that watch to run it again when the other oldest transaction is approaching in time.

public class TransactionManager {

    private DelayQueue<Transaction> transactions;

    public TransactionManager() {
        transactions = new DelayQueue<>();
    }

    /**
     * Create a transaction. If the json string is not valid, return {@link HttpStatus} UNPROCESSABLE_ENTITY
     * If a transaction was created more than 60 seconds ago, return {@link HttpStatus} NO_CONTENT
     * Otherwise add this transaction to the queue
     *
     * @param json {@link String} json object containing amount (type of {@link Double}),
     *             and timestamp (type of {@link Long})
     */
    public Object createTransaction(String json) {
        JSONObject jsonObject = null;
        try {
            jsonObject = JsonValidator.validateTransactionJson(json);
        } catch (Exception ex) {
            return new ResponseEntity(HttpStatus.UNPROCESSABLE_ENTITY);
        }
        long delay = System.currentTimeMillis() - ((Long) jsonObject.get(TIMESTAMP));
        if (delay > ONEMINUTE) {
            return new ResponseEntity(HttpStatus.NO_CONTENT);
        }
        transactions.add(new Transaction((Double) jsonObject.get(AMOUNT), (Long) jsonObject.get(TIMESTAMP)));
        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * Return statistics of transaction for the last 60 seconds.
     *
     * @return {@link String} in a JSON format
     */
    public String getStatistics() {
        //drain to a list
        List<Transaction> tempForCleaning = new ArrayList<>();
        transactions.drainTo(tempForCleaning);
        //clear it
        tempForCleaning.clear();

        Statistic statistics = new Statistic();
        transactions.forEach(transaction -> {
            statistics.setCount(statistics.getCount() + 1);
            statistics.setSum(statistics.getSum() + transaction.getAmount());
            statistics.setMax(statistics.getMax() > transaction.getAmount() ? statistics.getMax() : transaction.getAmount());
            statistics.setMin(statistics.getMin() < transaction.getAmount() ? statistics.getMin() : transaction.getAmount());
        });
        if (statistics.getCount() > 0) {
            statistics.setAvg(statistics.getSum() / statistics.getCount());
        }
        return statistics.toJSON();
    }
}

Update:

Statistic.class with getters and setters.

public class Statistic {
private double sum = 0.0;
private double avg = 0.0;
private double max = 0.0;
private double min = 0.0;
private int count = 0;}

Just in case transaction as well:

public class Transaction implements Delayed {
    private final Double amount;
    private final Long timestamp;   //timestamp of a time when the item was created and send here

    public Transaction(double amount, long timestamp) {
        this.amount = amount;
        this.timestamp = timestamp;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(ONEMINUTE - (System.currentTimeMillis() - timestamp), MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed delayed) {
        return delayed == this ?
                0 :
                Long.compare(getDelay(MILLISECONDS), delayed.getDelay(MILLISECONDS));
    }

    public double getAmount() {
        return amount;
    }
}


texts: Save to a MySQL database a temporary row with all information about a receipt

texts:
The Code
The Save Function:

public void SaveProducts()
{
    TempSave _Save = new TempSave();
    _Save.Localization = _LocationLabel.Text + "," + _LocNumbLab.Text;
    string items = "";
    for (int i = 0; i < _ProductsGrid.Rows.Count; i++)
    {
        items += _ProductsGrid.Rows[i].Cells[1].Value.ToString();
        items += ",";
    }
    string Qnt = "";
    for (int i = 0; i < _ProductsGrid.Rows.Count; i++)
    {
        Qnt += _ProductsGrid.Rows[i].Cells[0].Value.ToString();
        Qnt += ",";
    }
    try
    {
        items = items.Remove(items.Length - 1, 1);
        Qnt = Qnt.Remove(Qnt.Length - 1, 1);
    }
    catch{}
    _Save.Items = items;
    _Save.Quantity = Qnt;

    IEnumerable<TempSave> _CheackTem;

    string Cheak_TempSave = "SELECT * FROM TempSave WHERE Localization='" + _Save.Localization + "'";

    using (MySqlConnection Con = new MySqlConnection("server=localhost; database=wintestbeta;user=root; password=;"))
    {
        Con.Open();
        _CheackTem = Con.Query<TempSave>(Cheak_TempSave);
        Con.Close();
    }

    if (_CheackTem.Count() == 0)
    {
        string _TempSave = "INSERT INTO TempSave (Localization,items,Quantity) VALUES('" + _Save.Localization + "','" + _Save.Items + "','" + _Save.Quantity + "')";

        using (MySqlConnection Con = new MySqlConnection("server=localhost; database=wintestbeta;user=root; password=;"))
        {
            Con.Open();
            Con.Query(_TempSave);
            Con.Close();
        }
    }
    else
    {
        string _TempDelete = "DELETE FROM TempSave WHERE Localization='" + _Save.Localization + "'";

        using (MySqlConnection Con = new MySqlConnection("server=localhost; database=wintestbeta;user=root; password=;"))
        {
            Con.Open();
            Con.Query(_TempDelete);
            Con.Close();
        }
        string _TempSave = "INSERT INTO TempSave (Localization,items,Quantity) VALUES('" + _Save.Localization + "','" + _Save.Items + "','" + _Save.Quantity+ "')";

        using (MySqlConnection Con = new MySqlConnection("server=localhost; database=wintestbeta;user=root; password=;"))
        {
            Con.Open();
            Con.Query(_TempSave);
            Con.Close();
        }

    }
}

The TempSave class

public class TempSave
{
    public int id { get; set; }
    public string Localization { get; set; }
    public string Items { get; set; }
    public string Quantity { get; set; }
}

I don't use the int id but I left it there because I can became necessary in the future

How It Works
What the code does is gather 3 information's from a grid

Get the location (this is from a label)
Get all items from a grid that have been selected and put it into a string array
Get the quantity of all items from a grid and put it into a string array

The grid looks like this

+---------------------+
|Qnt|Description|Value|
+---------------------+

Then for each string in the items string array it will join all string together with a "," between them.

Then it does the same to the quantity string array

After that it checks if in the MySQL table already contains any row in the same location

If it doesn't it will insert the row,
if it does it will delete and insert the row.

This function is activated every time a new item is add to the grid no matter if it exists or not, if it exists it will just change the quantity.

I want to know if there is anyway I can make this function faster because it is taking to much time, about 2 seconds.


texts:
This generates a square matrix with spiral inward increasing values. How can I reduce this code?

Input Number = 3

Output

1 2 3

8 9 4

7 6 5

import math
row=int(input("Input nomber := "))
lis=[[0 for i in range(0,row)]for j in range(0,row)]
y=row
a=1
c=0
z=0
x=1
k=1
f=row/2
f=math.ceil(f)
for b in range(0,f):
    if b==k:
        row=row-1
        x=x+1
        z=z+1
        k=k+1
    for c in range(z,row):
        lis[b][c]=a
        a=a+1
    for d in range(x,row):
        lis[d][row-1]=a
        a=a+1
    for e in range(row-1,z,-1):
        lis[row-1][e-1]=a
        a=a+1
    for f in range(row-2,z,-1):
        lis[f][z]=a
        a=a+1
for i in range(0,y):
    print()
    for j in range(0,y):
        print(lis[i][j],end="\t")


texts:
I have the following requirement for valid usernames:

Only alphanumeric characters and -
Must not start with a -

I wrote this regex (on Rubular):

/^[^a-zA-Z0-9]|[^a-zA-Z0-9-]+/

Is there a better to test this requirement other than to iterate through all the possible scenarios? I'm doing something like this.

  # There much more, but for brevity's sake I'm only including a few
  illegal_chars = [ "~", "!", "@", "#", "$"]

  illegal_chars.each do |char|
    test "username does not accept #{char}" do
      user = users(:homer)
      user.username = "name#{char}"
      refute user.valid?, "Username should not be valid"
    end
  end

I'll repeat for cases where #{char} is at the beginning and end of the word.

Am I testing too much? Is there a better way? Running 70 or 80 tests for something like this seems excessive.
As an aside, can my regex be expressed better?


texts:
I am working on bettering my C# skills, and recently wrote this program to solve a projecteuler.net problem:

  A palindromic number reads the same both ways. The largest palindrome
  made from the product of two 2-digit numbers is 9009 = 91 * 99. Find
  the largest palindrome made from the product of two 3-digit numbers.

The code works and produced the correct answer, but I'm looking to avoid bad code and use best practices. Any critique of changes to make this more efficient would be appreciated! (Also, if there are any WTF's in there, please point them out!)

using System;
using System.Collections.Generic;
using System.Text;

namespace NumericPalindrome {
    class Program
    {
        static void Main(string[] args)
        {
            long result = 0;

            for (int i = 100; i < 1000; i++)
            {
                for (int k = 100; k < 1000; k++)
                {
                    if (IsPalindrome(i * k))
                        if ((i * k) > result)
                            result = i * k;
                }
            }

            Console.WriteLine(result);
        }

        static bool IsPalindrome(long testNumber)
        {
            List<int> list = new List<int>();

            //Break testNumber into an integer list of its digits
            while (testNumber >= 1)
            {
                list.Add((int)(testNumber % 10));
                testNumber /= 10;
            }

            List<int> reverseList = new List<int>(list);
            reverseList.Reverse();

            bool palindrome = true;

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i] != reverseList[i])
                    palindrome = false;
            }

            return palindrome;
        }
    }
}


texts:
I'm learning DB design.  How would you change the following schema which tries to replicate Stack Overflow's functionality:

create_table "questions", :force => true do |t|
    t.text      "question",         :null => false
    t.text      "description",  :null => false
    t.integer       "up_votes",         :null => false, :default => 0
    t.integer       "down_votes",       :null => false, :default => 0
  t.timestamps
end

create_table "answers", :force => true do |t|
    t.integer       "question_id",  :null => false
    t.text      "answer",               :null => false
    t.integer       "up_votes",         :null => false, :default => 0
    t.integer       "down_votes",       :null => false, :default => 0
  t.timestamps
end

create_table "question_comments", :force => true do |t|
    t.integer   "question_id",  :null => false
    t.text      "comment",          :null => false
  t.timestamps
end

create_table "answer_comments", :force => true do |t|
    t.integer   "answer_id",    :null => false
    t.text      "comment",      :null => false
  t.timestamps
end

create_table "tags", :force => true do |t|
    t.string        "tag",  :null => false, :limit => 100
  t.timestamps
end
add_index "tags", ["tag"], :name => "tag_UNIQUE", :unique => true

create_table "question_tags", :force => true do |t|
  t.integer     "question_id",  :null => false
  t.integer     "tag_id",               :null => false
  t.timestamps
end

create_table "users", :force => true do |t|
    t.string        "first_name",   :limit => 45,       :null => false
    t.string        "last_name",    :limit => 45,       :null => false
    t.string        "email",            :limit => 100,  :null => false
    t.string        "password",                                     :null => false
    t.string        "salt",                                             :null => false
  t.timestamps
end

create_table "user_votes", :force => true do |t|
    t.integer       "user_id",  :null => false
    t.integer       "question_id"
    t.integer       "answer_id"
    t.boolean       "is_positive_vote"
    t.timestamps
end

create_table "user_favorites", :force => true do |t|
    t.integer       "user_id",  :null => false
    t.integer       "question_id"
    t.integer       "answer_id"
    t.timestamps
end

create_table "question_flags", :force => true do |t|
    t.integer       "user_id",  :null => false
    t.integer       "question_id"
    t.timestamps
end

create_table "answer_flags", :force => true do |t|
    t.integer       "user_id",  :null => false
    t.integer       "question_id"
    t.timestamps
end

create_table "related_questions", :force => true do |t|
    t.integer       "question_id",                  :null => false
    t.integer       "related_question_id",  :null => false
    t.timestamps
end


texts:
I created a function to read lines from an file into chunks.
My hidden agenda in creation this script was in python the yield function in interaction with chunks.
The script works fine, but now i want to know if anyone has improvements?

#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;

sub read_in_chunks {
    my $args = shift;
    my $self = {
        fd => $args->{fd} || undef,
        chunk_size => $args->{chunk_size} || 10,
        chunks => [],
    };
    my $fh = $self->{fd};
    return unless defined(my $line=<$fh>);
    while(<$fh>){
        chomp($_);
        # maybe the following line could be written nicer :)
        ($self->{chunk_size} == 0) ? return $self->{chunks} : (push @{$self->{chunks}}, $_);
        $self->{chunk_size}--;
    }
    return $self->{chunks};
}

open my $fh, 'dump.txt' or die $!;

my $opts = {
    fd => $fh,
    chunk_size => 4
};

while(my $chunk = read_in_chunks($opts)) {
    print Dumper($chunk);
    # process data
}

close $fh;


texts:
I am practising my coding skills on interviewbit. I got one question about preorder (for a tree). This is what I did first:

public class Solution {
   private ArrayList<Integer> result = new ArrayList<Integer>();
   public ArrayList<Integer> preorderTraversal(TreeNode a) {
       if(a == null){
          return result;
       }
       result.add(a.val);
       preorderTraversal(a.left);
       preorderTraversal(a.right);
       return result;
    }
}

Then I googled solutions for the same problem and this is what I found.

public class PreOrder{
    public ArrayList<Integer> preorderTraversal(TreeNode a) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        if(a == null)
            return result;
        stack.push(a);
        while(!stack.isEmpty()){
            TreeNode popped = stack.pop();
            result.add(popped.val);
            if(popped.right != null)
                stack.push(popped.right);
            if(popped.left != null)
                stack.push(popped.left);
        }
        return result;
    }
}

I understood the second method too. What am I asking is the other method better than mine? If yes then how?

NOTE: I am not allowed to change function arguments and return types.


texts:
I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!
Problem

Given a 2d grid map of '1's (land) and '0's (water), count the number
of islands. An island is surrounded by water and is formed by
connecting adjacent lands horizontally or vertically. You may assume
all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000

Output: 1

Example 2:
Input:
11000
11000
00100
00011

Output: 3

Code
#include <vector>

class Solution {
public:
    std::size_t numIslands(std::vector<std::vector<char>>& grid) {
        std::size_t row_length = grid.size();

        if (!row_length) {
            return 0;
        }

        std::size_t col_length = grid[0].size();
        std::size_t islands = 0;

        // Runs depth first search for every cell
        for (std::size_t row = 0; row < row_length; row++) {
            for (std::size_t col = 0; col < col_length; col++) {
                if (grid[row][col] == '1') {
                    islands++;
                    depth_first_search(grid, row, col, row_length, col_length);
                }
            }
        }

        return islands;
    }

private:
    void depth_first_search(std::vector<std::vector<char>>& grid, const std::size_t row, const std::size_t col, const std::size_t row_length, const std::size_t col_length) {
        // Checks for grid boundaries and '0' cells
        if (row < 0 || row >= row_length || col < 0 || col >= col_length || grid[row][col] == '0') {
            return;
        }

        grid[row][col] = '0';
        // Recurse in 4 directions of grid
        depth_first_search(grid, row + 1, col, row_length, col_length);
        depth_first_search(grid, row - 1, col, row_length, col_length);
        depth_first_search(grid, row, col + 1, row_length, col_length);
        depth_first_search(grid, row, col - 1, row_length, col_length);
    }
};

LeetCode's Solution (Not for review)
class Solution {
private:
  void dfs(vector<vector<char>>& grid, int r, int c) {
    int nr = grid.size();
    int nc = grid[0].size();

    grid[r][c] = '0';
    if (r - 1 >= 0 && grid[r-1][c] == '1') dfs(grid, r - 1, c);
    if (r + 1 < nr && grid[r+1][c] == '1') dfs(grid, r + 1, c);
    if (c - 1 >= 0 && grid[r][c-1] == '1') dfs(grid, r, c - 1);
    if (c + 1 < nc && grid[r][c+1] == '1') dfs(grid, r, c + 1);
  }

public:
  int numIslands(vector<vector<char>>& grid) {
    int nr = grid.size();
    if (!nr) return 0;
    int nc = grid[0].size();

    int num_islands = 0;
    for (int r = 0; r < nr; ++r) {
      for (int c = 0; c < nc; ++c) {
        if (grid[r][c] == '1') {
          ++num_islands;
          dfs(grid, r, c);
        }
      }
    }

    return num_islands;
  }
};

Reference
On LeetCode, there is a class usually named Solution with one or more public functions which we are not allowed to rename.

Problem

Discuss


texts: Finding all the subsets in an array of integers that sum to a given target

texts:
Problem Statement:

  Given an Array if ints, Find out all the subsets in the Array that
  sum to a given target value.

  Example:

  If the input array is:

  {1, 3, 2, 5, 4, 9} with target as 9

  The resulting subsets are:

135
324
9
54

Below is my implementation in Java. Please free to review in terms of time, space complexity, style etc and a more efficient solution is welcome.

 import java.util.HashSet;

 /**
  * Created by anirudh on 12/5/15.
 */
 public class FindSubsetsThatSumToATarget {

    /**
     * The collection for storing the unique sets that sum to a target.
     */
    public static HashSet<String> allSubsets = new HashSet<>();

    /**
     * The method for finding the subsets that sum to a target.
     *
     * @param input  The input array to be processed for subset with particular sum
     * @param target The target sum we are looking for
     * @param ramp   The Temporary String to be beefed up during recursive iterations(By default value an empty String)
     * @param index  The index used to traverse the array during recursive calls
     */
    private void FindTargetSumSubsets(int[] input, int target, String ramp, int index) {

        if(index > (input.length - 1)) {
            if(getSum(ramp) == target) {
                allSubsets.add(ramp);
            }
            return;
        }

        //First recursive call going ahead selecting the int at the currenct index value
        FindTargetSumSubsets(input, target, ramp + input[index], index + 1);
        //Second recursive call going ahead WITHOUT selecting the int at the currenct index value
        FindTargetSumSubsets(input, target, ramp, index + 1);
    }

    /**
     * A helper Method for calculating the sum from a string of integers
     *
     * @param intString the string subset
     * @return the sum of the string subset
     */
    private static int getSum(String intString) {
        int sum = 0;
        for (int i = 0; i < intString.length(); i++) {
            sum += Integer.parseInt(intString.substring(i, i + 1));
        }
        return sum;
    }

    /**
     * Cracking it up here : )
     *
     * @param args command line arguments.
     */
    public static void main(String[] args) {
        int [] n =  {1, 3, 2, 5, 4, 9};
        new FindSubsetsThatSumToATarget().FindTargetSumSubsets(n, 9, "", 0);
        for (String str: allSubsets) {
            System.out.println(str);
        }
    }
}

I have some across a problem with the above implementation that in case of repeated values in the input array I am getting duplicate permutes of sets that sum to a given target.

E.g.: In input is:

int [] n =  {2, 3, 2};

The resulting sets generated are:

32
23

Which in the given context are actually the same.


texts: Tabulate k = 2^n minimizing multiplication

texts:
Given the following problem:

;3.3 Tabulate the function k = 2^n for n = 1..50.
;Do this for the fewest possible multiplications.[3]

I wrote this answer:

(defun k (n) (ash 2 (1- n)))

(loop for n from 1 to 50 do
      (format t "k(~a) = ~a ~%" n (k n)))

What do you think?


texts: Script for dynamically-loading data onto a restaurant menu for printing

texts:
I have a script which dynamically loads data onto a restaurant menu for printing.  Could the following code could be shortened at all?

    <script>
                $(document).ready(function(){
                $('#prestarters').load('prestarters.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                $('#starters').load('starters.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });

                        $('#mains').load('mains.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }
            });

                        $('#sides').load('sides.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }
            });
                $('#dessert').load('dessert.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#dessertwines').load('dessertwines.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#afterdinnerdrinks').load('afterdinnerdrinks.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#whiskeys').load('whiskeys.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#hotdrinks').load('hotdrinks.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#ports').load('ports.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#cognacs').load('cognacs.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#liqueurs').load('liqueurs.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
    });
    </script>

Also, is there a way to alert the user once all data has been loaded? I currently have a message which tells the user to wait 5 - 10 seconds before printing...


texts:
Can this if-else statement be simplified and/or cleaned up?

var path = require('path')
var express = require('express')
var app = express()
app.get('/*', function (req, res) {
  var page;
  if (req.params[0] === '') {
    // if requesting root dir, add `index.html`
    page = path.parse(path.join(__dirname, 'index.html'))
  } else {
    // otherwise add requested path
    page = path.parse(path.join(__dirname, req.params[0]))
    if (page.ext === '') {
      // if requested page has no extension, change page, adding `index.html`
      page = path.parse(path.join(__dirname, req.params[0], 'index.html'))
    }
  }
  if (page.ext === '.html') {
    /*... do html stuff ...*/
  }
  else if (page.ext === '.css') {
    /*... do css stuff ...*/
  }
  /*...*/
})

It works correctly but I feel it’s "bad coding". There are nested if statements and I’m repeating a lot of code. Also, below the first condition, there are other conditions testing the type of page (HTML, CSS, etc.) Since in the page.ext==='' condition, the value of page may change, it's not a mutually exclusive case of the other conditions.

It’s weird and feels wrong, but I can’t quite explain why.

I tried using the ternary expression (?:), but I still can’t avoid the if statement afterward.

var page = path.parse(path.join(__dirname, (req.params[0] === '') ? 'index.html' : req.params[0]))
if (page.ext === '') page = path.parse(path.join(__dirname, req.params[0], 'index.html'))

Is there a way to do it without repeating code? I’d like to avoid assigning page more than once.

+++
I’ve come up with a less verbose way of doing it, and it only requires assigning page once. Though it still requires calling path.parse() more than once.

var filepath = path.join(__dirname, req.params[0] || 'index.html')
var page = path.parse(path.join(filepath, (path.parse(filepath).ext === '') ? 'index.html' : ''))

+++
After discovering path.extname(<String>), I realized I don’t need to parse it beforehand. So this simplifies to:

var filepath = path.join(__dirname, req.params[0] || 'index.html')
var page = path.parse(path.join(filepath, (path.extname(filepath) === '') ? 'index.html' : ''))