texts: Creating linked list data with iterator pattern

texts:
I've created a linked list to use it in SquareList.  I've started to create a linked list based on just that.  I want my class to follow the iterator pattern.  How can it be improve to use vector iterator?

#ifndef LINKEDLIST_HPP
#define LINKEDLIST_HPP

#include <stdlib.h>

template <typename Object>
class Linkedlist
{
  private:
    // The basic doubly linked Linkedlist node.
    // Nested inside of Linkedlist, can be public
    // because the Node is itself private
    struct Node
    {
        Object  _data;
        Node   *_prev;
        Node   *_next;

        Node( const Object & d = Object( ), Node * p = NULL, Node * n = NULL )
          : _data( d ), _prev( p ), _next( n ) { }
    };

  public:

  public:
    Linkedlist( )
      { init( ); }

    ~Linkedlist( )
    {
        clear( );
        delete _head;
        delete _tail;
    }

    Linkedlist( const Linkedlist & rhs )
    {
        init( );
        *this = rhs;
    }

    const Linkedlist & operator= ( const Linkedlist & rhs )
    {
        if( this == &rhs )
            return *this;
        clear( );
        for( const_iterator itr = rhs.begin( ); itr != rhs.end( ); ++itr )
            push_back( *itr );
        return *this;
    }

    // Return iterator representing beginning of Linkedlist.
    // Mutator version is first, then accessor version.
    iterator begin( )
      { return iterator( _head->_next ); }

    const_iterator begin( ) const
      { return const_iterator( _head->_next ); }

    // Return iterator representing endmarker of Linkedlist.
    // Mutator version is first, then accessor version.
    iterator end( )
      { return iterator( _tail ); }

    const_iterator end( ) const
      { return const_iterator( _tail ); }

    // Return number of elements currently in the Linkedlist.
    int size( ) const
      { return _size; }

    // Return true if the Linkedlist is empty, false otherwise.
    bool empty( ) const
      { return size( ) == 0; }

    void clear( )
    {
        while( !empty( ) )
            pop_front( );
    }

    // front, back, push_front, push_back, pop_front, and pop_back
    // are the basic double-ended queue operations.
    Object & front( )
      { return *begin( ); }

    const Object & front( ) const
      { return *begin( ); }

    Object & back( )
      { return *--end( ); }

    const Object & back( ) const
      { return *--end( ); }

    void push_front( const Object & x )
      { insert( begin( ), x ); }

    void push_back( const Object & x )
      { insert( end( ), x ); }

    void pop_front( )
      { erase( begin( ) ); }

    void pop_back( )
      { erase( --end( ) ); }

    // Insert x before itr.
    iterator insert( iterator itr, const Object & x )
    {
        Node *p = itr.current;
        _size++;
        return iterator( p->_prev = p->_prev->_next = new Node( x, p->_prev, p ) );
    }

    // Erase item at itr.
    iterator erase( iterator itr )
    {
        Node *p = itr.current;
        iterator retVal( p->_next );
        p->_prev->_next = p->_next;
        p->_next->_prev = p->_prev;
        delete p;
        _size--;

        return retVal;
    }

    iterator erase( iterator start, iterator end )
    {
        for( iterator itr = start; itr != end; )
            itr = erase( itr );

        return end;
    }

  private:
    int   _size;
    Node *_head;
    Node *_tail;

    void init( )
    {
        _size = 0;
        _head = new Node;
        _tail = new Node;
        _head->_next = _tail;
        _tail->_prev = _head;
    }
};

#endif


texts: Set id in constructor, or generate it when asked for?

texts:
I'm using PHP, I have a class that generates an id based on the calling class, so the id of the class won't change after it has been initialised, now I'm wondering which of my two methods is preferrable.

Set the id in the constructor
Generate the id when asked for

/* Set  the id in the constructor */

abstract class Badge
{
    protected $activities;
    protected $id;

    abstract public function check();

    public function __construct(array $activities)
    {
        $this->activities = $activities;
        $this->id = $this->getId();
    }

    public function getId(): string
    {
        $class = explode('\\', get_class($this));
        $classWithoutNamespace = array_pop($class);
        $snakeCased = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $classWithoutNamespace));

        return "{$snakeCased}_{$this->target}";
    }

    public function toArray(): array
    {
        return [
            'id' => $this->id,
        ];
    }
}

/* Generate the id when asked for */

abstract class Badge
{
    protected $activities;

    abstract public function check();

    public function __construct(array $activities)
    {
        $this->activities = $activities;
    }

    public function getId(): string
    {
        $class = explode('\\', get_class($this));
        $classWithoutNamespace = array_pop($class);
        $snakeCased = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $classWithoutNamespace));

        return "{$snakeCased}_{$this->target}";
    }

    public function toArray(): array
    {
        return [
            'id' => $this->getId(),
        ];
    }
}

```


texts: Django Rest Framework model relations for a Gallery app

texts:
I'm creating a school project, a Gallery app. I have the following entities: Profile, Album, Image, Tag, Like, Comment, but I'm a little bit confused with relations. I created them all, but I'm not sure everything is good.

Profile:

class Profile(models.Model):
    user            = models.OneToOneField(User)
    albums          = models.ManyToManyField("albums.Album", blank=True)
    commented       = models.ManyToManyField("comments.Comment", blank=True, unique=False)
    liked           = models.ManyToManyField("likes.Like", blank=True)
    profile_picture = models.ImageField( blank=True, null=True, upload_to='profile_pics')
    timestamp       = models.DateTimeField(auto_now_add=True)
    updated         = models.DateTimeField(auto_now=True)

Album:

class Album(models.Model):
    name        = models.CharField(max_length=120, blank=False, null=False)
    owner       = models.ForeignKey("profiles.Profile")
    description = models.TextField( max_length=500, null=True)
    images      = models.ManyToManyField("images.Image", related_name="album_images", blank=True)
    is_public   = models.BooleanField(default=False)
    timestamp   = models.DateField(auto_now_add=True)
    updated     = models.DateField(auto_now=True)

Image

class Image(models.Model):
    name        = models.CharField(max_length=120, blank=False, null=True)
    album       = models.ForeignKey("albums.Album", related_name="album_id", null=True, blank=True)
    image       = models.ImageField(verbose_name="Image", blank=True, null=True, upload_to='img')
    description = models.TextField(max_length=500, null=True, blank=True)
    comments    = models.ManyToManyField("comments.Comment", related_name="all_comments", blank=True, unique=False)
    likes       = models.ManyToManyField("likes.Like", related_name="all_likes", blank=True, unique=False)
    tags        = models.ManyToManyField("tags.Tag", related_name="all_tags", blank=True)
    is_public   = models.BooleanField(default=False)
    timestamp   = models.DateField(auto_now_add=True)
    updated     = models.DateField(auto_now=True)

Tags

class Tag(models.Model):
    name      = models.CharField(max_length=120, blank=False, null=False)
    images    = models.ManyToManyField("images.Image", blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated   = models.DateTimeField(auto_now=True)

Likes

class Like(models.Model):
    owner     = models.ManyToManyField("profiles.Profile")
    image     = models.ManyToManyField("images.Image")
    timestamp = models.DateTimeField(auto_now_add=True)
    updated   = models.DateTimeField(auto_now=True)

Comments

class Comment(models.Model):
    owner     = models.ManyToManyField("profiles.Profile", unique=False)
    image     = models.ManyToManyField("images.Image", unique=False)
    content   = models.TextField(max_length=500, blank=False, null=False)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated   = models.DateTimeField(auto_now=True)

How does it look to you? Am I wrong somewhere?


texts:
I'm working on a calculator for educational purposes and was asked to include a rule that multiplies/divides before it adds/subtracts.

Let's assume I have the following equation:

2 + 2 * 2

Windows built-in calculator would return 8, since it just goes down the line without parantheses.

The correct answer however would be 6.

So my code first splits the entire equation into a List<string>:

string equation = "2 + 2 * 2"
List<string> equationList = equation.Split(' ').ToList();
//Result:
//2
//+
//2
//*
//2

Then it checks if equationList contains an asterisk or slash:

if (equationList.Contains("*")) equationList = PunktVorStrich("*", equationList);
if (equationList.Contains("/")) equationList = PunktVorStrich("/", equationList);

This automatically calls the following function PunktVorStrich:

private List<string> PunktVorStrich(string symbol, List<string> equationList)
{
    while (equationList.Contains(symbol))
    {//loops in case there are multiple instances of the given symbol
        int position = equationList.IndexOf(symbol); //position of the symbol
        int before = int.Parse(equationList.ElementAt(position - 1)); //position of the number before the symbol
        int after = int.Parse(equationList.ElementAt(position + 1)); //position of the number after the symbol
        equationList.RemoveAt(position - 1);
        equationList.RemoveAt(position - 1);
        equationList.RemoveAt(position - 1);//Remove all 3 elements
        //finally calculate and "replace" the equation-part with the result
        if(symbol == "*")
        {
            equationList.Insert(position - 1, (before * after).ToString());
        }else if(symbol == "/")
        {
            equationList.Insert(position - 1, (before / after).ToString());
        }
    }
    return equationList;
    //equationList =
    //2
    //+
    //4
}

And finally the program loops through the remaining equation:

bool number = true; //This ensures that the equation is split between operators and values
int total = 0; //Sum of the current equation
string lastOperator = String.Empty; //Stores the last operator

foreach (string term in equationList)
{
    if (number)
    {
        if (lastOperator == "") total = int.Parse(term);
        if (lastOperator == "+") total = total + int.Parse(term);
        if (lastOperator == "-") total = total - int.Parse(term);
    }
    number= !number;
    lastOperator = term;
}

Finally I can return the equation with

MessageBox.Show(total.ToString());

I'm however not exactly happy with this solution, since I personally think that took a few steps too much to achieve my goal. Is there anything I can do better?


texts: Add an attribute to specific XML Elements in Scala

texts:
supposed I have an XML like

<root>
  <topic>
    <name>foo</name>
  </topic>
  <subject>
    <name>foo</name>
  </subject>
  <subject>
    <name>bar</name>
  </subject>
</root>

I want to add attributes to all <name> tags if they are children of a <subject>, bot not if they are children of a <topic>.
My current approach is:

// Select all names which are childs of a subject

val names: Seq[Node] = (xml \\ "subject" \\ "name").theSeq

  private class AddAttributes(foo: Seq[Node]) extends RewriteRule {
    override def transform(n: Node): Seq[Node] = {
      n match {
        case elem: Elem if foo.contains(elem) => elem.copy(attributes = new UnprefixedAttribute("role", "nrol:full", Null))
        case other => other
      }
    }
  }

new RuleTransformer(new AddAttributes(names))(prepXml)

While this works, I wonder if there is a more "scalatic" way of doing this?


texts:
I'm starting to look at Python and its facilities. I've just tried to make one simple program using some base libraries.

I would like to hear some comments about anything you've noticed - style, readability, safety, etc.

#!/usr/bin/python2.6 -u

import urllib2
import simplejson
import zlib
from optparse import OptionParser

class StackOverflowFetcher:
    """Simple SO fetcher"""
    def getUserInfo( self, userId ):
        response = urllib2.urlopen( 'http://api.stackoverflow.com/1.1/users/' + str(userId) )
        response = response.read()
        jsonData = zlib.decompress( response, 16+zlib.MAX_WBITS )
        return simplejson.loads( jsonData )

    def getUserDisplayName( self, userId ):
        return self.getUserInfo( userId )['users'][0]['display_name']

    def getUserViewCount( self, userId ):
        return self.getUserInfo( userId )['users'][0]['view_count']

    def getUserReputation( self, userId ):
        return self.getUserInfo( userId )['users'][0]['reputation']

if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option("-u", "--userId", dest="userId", help="Set userId (default is 1)", default=1 )
    parser.add_option("-n", "--display-name", action="store_true", dest="show_display_name", default=False, help="Show user's display name")
    parser.add_option("-v", "--view_count", action="store_true", dest="show_view_count", default=False, help="Show user's profile page view count")
    parser.add_option("-r", "--reputation", action="store_true", dest="show_reputation", default=False, help="Show user's reputation")
    (options, args) = parser.parse_args()

    userId = options.userId
    show_display_name = options.show_display_name
    show_view_count = options.show_view_count
    show_reputation = options.show_reputation

    if ( (not show_display_name) and (not show_view_count) and (not show_reputation) ):
        show_display_name = show_view_count = show_reputation = True

    fetcher = StackOverflowFetcher()
    if ( show_display_name ) : print fetcher.getUserDisplayName( userId )
    if ( show_view_count) : print fetcher.getUserViewCount( userId )
    if ( show_reputation ) : print fetcher.getUserReputation( userId )

Python version 2.6


texts: Finding number of primes till n - Sieve of Eratosthenes

texts:
I've written a ruby implementation for Sieve of Eratosthenes algorithm, however benchmarking it against the Ruby's Prime module I have still a far slower algorithm - and I am struggling to understand why.

require 'set'

def numbers_with_multiples_less_than n
  (2...(Math.sqrt(n)).ceil)
end

def primes_till n
  possible_primes = Set.new(2...n)

  (numbers_with_multiples_less_than n).each do |i|
    if possible_primes.include? i
      possible_primes = possible_primes - Set.new(multiples i**2,i,n)
    end
  end

  possible_primes
end

def count_prime_till n
  primes_till(n).count
end

def multiples start,step_size,max
  (start...max).step(step_size)
end

Running it against,

puts Benchmark.measure { Prime::EratosthenesGenerator.new.first(1000).count }
  0.000000   0.000000   0.000000 (  0.000437)

Compared to mine,

puts Benchmark.measure {count_prime_till 7920}
  0.020000   0.000000   0.020000 (  0.025582)

Please let me know how can I improve the running time, and as always, readability.


texts: Trie Data Structure Implementation in C++11 using Smart Pointers

texts:
This implementation is part of my open source project forest.

I wrote the following header file to implement a trie data structure that supports inserting and searching strings consisting of 26 lower-case letters of the English alphabet. I am looking forward to hearing your opinion about this implementation and any suggestions/fixes you may have.

/**
 * @file trie.h
 */

#ifndef TRIE_H
#define TRIE_H

#include <iostream>
#include <string>
#include <memory>

#define ALPHABET_SIZE 26

/**
 * @brief The forest library namespace
 */
namespace forest {
  namespace trie {
    /**
     * @brief trie node struct
     */
    struct node {
      std::shared_ptr<node> children[ALPHABET_SIZE];
      bool end;
      /**
       * @brief Constructor of a trie node
       */
      node() {
        this->end = false;
        for (int i = 0; i < ALPHABET_SIZE; i++) {
          this->children[i] = NULL;
        }
      }
    };
    /**
     * @brief trie class
     */
    class tree {
    private:
      std::shared_ptr<node> root;
    public:
      tree() {
              root = std::make_shared<node>();
      }
      /**
       * @brief Inserts the given key into the trie
       * @param key The key to be inserted
       * @return void
       */
      void insert(const std::string &key) {
        std::shared_ptr<node> n = root;
        for (int i = 0; i < key.length(); i++) {
          int index = key[i] - 'a';
          if (n->children[index] == nullptr) {
            n->children[index] = std::make_shared<node>();
          }
          n = n->children[index];
        }
        n->end = true;
      }
      /**
       * @brief Searches for the given key in the trie
       * @param key The key to be inserted
       * @return true if key exists in the trie and false otherwise
       */
      const bool search(const std::string &key) {
        std::shared_ptr<node> n = root;
        for (int i = 0; i < key.length(); i++) {
          int index = key[i] - 'a';
          if (n->children[index] == nullptr) {
            return false;
          }
          n = n->children[index];
        }
        return (n != nullptr && n->end == true);
      }
    };
  }
}

#endif


texts: Wait until thread is stopped from within thread

texts:
This is an abbreviated version of a serial receiver that can be started and stopped like a resource. The idea is that a thread will listen to an InputStream and dispatch received data to registered listeners. Effectively this converts a pull-style InputStream to push-style CommunicationListener (own interface). While it works perfectly for my purposes (closing the receiver stops the thread and cleans up resources), I think it's bad practice that the receiver can't close itself. I wonder if I have the wrong approach here.

Ignore the lack of thread-safety/@Nullable/etc in this example, it's all present in the production version.

public class TempReceiver {
    public static void main(String... args) {
        TempReceiver receiver = new TempReceiver();
        receiver.open();
    }

    private InternalThread receiveThread = new InternalThread();

    public void open() {
        receiveThread.start();
    }

    public void close() { // blocking call
        receiveThread.join(1000); // Why no exception when self-joining?

        if (receiveThread.isAlive())
            throw new RuntimeException("Timeout while stopping thread"); // printed

        receiveThread = null; // clean up resources
    }

    class InternalThread extends Thread {
        public void run() {
            try {
                System.out.println("Receiver busy");
                Thread.sleep(500);

                // Invoke listener here with received data.
                // Some listener decides that the receiver can be closed.
                close();
            } catch (InterruptedException e) { }
        }
    }
}


texts:
I coded a python solution for the question below. I am after the fastest solution. Also, I would be grateful if you could point out parts that are not pythonic / inefficient.

  Question: A website requires the users to input username and password
  to register. Write a program to check the validity of password input
  by users. Following are the criteria for checking the password:

  At least 1 letter between [a-z]
  At least 1 number between [0-9]
  At least 1 letter between [A-Z]
  At least 1 character from [$#@]
  Minimum length of transaction password: 6

import warnings
password = 'P@ss1234'
def check_number(s):
    ''' Check whether the input string is a digit. '''
    try:
        int(s)
        return True
    except:
        # do not catch error
        return False
def check_validity(pw):
    ''' Return True if input pw is valid, and return False if invalid.'''
    special_chars = ['$','#','@']
    if isinstance(pw,str): pw=list(pw) # I could have appointed to a diff var name
    else: warnings.warn('Password has to be a string object.')
    res = False
    valid_dict={'small_let':False, 'num':False, 'special_chars':False,
                'cap_let':False, 'len':False } # is using a dict efficient?
    if len(pw)>= 6: valid_dict['len']=True
    for i in pw:
        if i.islower(): valid_dict['small_let'] = True
        if i in special_chars: valid_dict['special_chars'] = True
        if i.isupper(): valid_dict['cap_let'] = True
        if not valid_dict['num']:  valid_dict['num'] = check_number(i)
    if all(valid_dict.values()): res = True
    return res

print check_validity(password)

P.S: I am not interested in a module / package that can do this faster or more securely. There does not actually exist a website or a username, this is a simple coding exercise.

Also, linked to this post.


texts: wrote a new library for my electron app - MyText.js

texts:
Recently I started learning Electron - so I wrote a new javascript library for my personal use in the app - MyText.js - to implement a code-editor like interface to my App like auto indent, auto-open-close parenthesis,braces .

As full source cannot be inserted here (due to question restrictions) - so I have provided a link to my project 1.

var text = text || (function(id){

    var textarea = document.getElementById(id);

    textarea.onkeydown = function(e){
        if(window.event.shiftKey){
            if(e.key == "("){
                e.preventDefault();
                var start = this.selectionStart;
                var end = this.selectionEnd;
                var val = this.value;
                this.value = val.slice(0,start) + "()" + val.slice(end);
                this.selectionEnd=start+1;
            }

            // similar logic for other characters

        }

        if(e.keyCode == 13){
            e.preventDefault();
            var start = this.selectionStart;
            var end = this.selectionEnd;
            var val = this.value;
            var indent = this.value.substring(0,start);
            indent = indent.match(/(^|\n)([ ]*)[^\n]*$/);
            indent = indent[2];
            if(val[start-1] == "{" || val[start-1] == "[" || val[start-1] == "("){
                var previous_indent=indent;
                indent+="    ";
                indent = "\n" + indent + "\n" + previous_indent;
                this.value = val.slice(0,start) + indent + val.slice(end);
                this.selectionEnd = start+5+previous_indent.length;
            }

            else if(val[start-1] == ":"){
                indent = "\n" + indent + "    ";
                this.value = val.slice(0,start) + indent + val.slice(end);
            }

            else{
                var previous_indent=indent;
                indent = "\n" + indent;
                this.value = val.slice(0,start) + indent + val.slice(end);
                this.selectionEnd = start+1+previous_indent.length;
            }
        }

        if(e.keyCode == 8){
            var start = this.selectionStart;
            var end = this.selectionEnd;
            var val = this.value;
            if((val[start-1] == "{" && val[start] == "}") || (val[start-1] == "[" && val[start] == "]") || (val[start-1] == "(" && val[start] == ")") || (val[start-1] == "\"" && val[start] == "\"") || (val[start-1] == "\'" && val[start] == "\'")){
                e.preventDefault();
                this.value = val.slice(0,start-1) + val.slice(start+1);
                this.selectionEnd = start-1;
            }
            else{

            }
        }

        if(e.keyCode == 9){
            e.preventDefault();
            var start = this.selectionStart;
            var end = this.selectionEnd;
            var val = this.value;
            var indent = "    ";
            this.value = val.slice(0,start) + indent + val.slice(end);
            this.selectionEnd = start + 4;
        }
    };
});

It is working for me in electron (its not working in firefox - I think due to window.event) - So I want a general code review of my code - Thanks


texts: My approach on nextjs cluster with socket.io

texts:
I'm interested in feedback on my approach to handling cluster on Next.js SSG app with express hosted on Heroku.
The app is working however, please let me know if this is the wrong approach or if you see any potential mistake.
Project specs:

sticky-session : ^1.1.2
express : ^4.17.1
next :  ^10.0.5
socket.io : ^2.4.0
socket.io-client :  ^2.4.0
socket.io-redis :  ^5.4.2

Server code:
const sticky = require("sticky-session");
const app = require("express")();
const server = require("http").Server(app);
const io = require("socket.io").listen(server);
io.set("transports", ["websocket"]);
const redis = require("socket.io-redis");

const PORT = process.env.PORT || 3000;
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const nextApp = next({ dev });
const handle = nextApp.getRequestHandler();

const keys = require("./config/keys");
const mongoose = require("mongoose");
const cookieSession = require("cookie-session");
const passport = require("passport");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const sslRedirect = require("heroku-ssl-redirect").default;

io.adapter(redis(keys.REDIS_URL));

const worker = () => {
    nextApp
        .prepare()
        .then(() => {
            app.use(cookieParser());

            app.use(bodyParser.json());

            app.use(
                cookieSession({
                    maxAge: 30 * 24 * 60 * 60 * 1000,
                    keys: [keys.cookieKey],
                })
            );

            app.use(passport.initialize());
            app.use(passport.session()); // persistent login sessions

            // IMPORT MODELS
            mongoose.connect(keys.mongoURI, {
                useNewUrlParser: true,
                useUnifiedTopology: true,
            });

            const db = mongoose.connection;

            db.once("open", function () {
                console.log("MongoDB database connection established successfully");
            });
            db.on("error", console.error.bind(console, "MongoDB connection error:"));

            require("./sockets/index")(io);
            require("./routes/api")(app, io);

            app.get("*", (req, res) => {
                return handle(req, res);
            });
        })
        .catch((ex) => {
            console.error(ex.stack);
            process.exit(1);
        });
};

//sticky.listen() will return false if Master
if (!sticky.listen(server, PORT)) {
} else {
    worker();
}

On the client I simply use:
const socket = io({ transports: ["websocket"] });

Heroku settings:
heroku features:enable http-session-affinity


texts: shared_instance implementation using C++ and RAII

texts:
I created a little singleton-like class that gets deleted when there is no reference to it anymore (so its lifetime shall be somewhat predictable). I aimed to make it thread-safe.

#include <memory>
#include <mutex>

template< typename t_type >
struct shared_instance
{
    static std::shared_ptr< t_type > get_shared_instance()
    {
        static std::weak_ptr< t_type > weak;
        static std::mutex mutex;

        auto result = weak.lock();
        if( nullptr == result )
        {
            std::unique_lock< std::mutex > lock{ mutex };

            result = weak.lock();
            if( nullptr != result )
            {
                return result;
            }

            result = std::make_shared< t_type >();
            weak = result;
        }
        return result;
    }
};

template< typename t >
struct context
{
    context()
    : instance{ shared_instance< t >::get_shared_instance() }
    { }

private: std::shared_ptr< t > instance;
};

I would be glad if you could comment on the implementation itself and how I could tackle non-default-constructible objects (I know of perfect forwarding and variadic templates but I have not found an elegant way to evaluate them lazily).


texts: Am I using Q the right way or is there a better way to do what I'm doing?

texts:
I'm using Q to flatten out some callbacks in my unit tests and return a promise to mocha (which knows to wait until the promise is resolved before running the next test).

Originally I had this code:

it ('resetCount should cause the count to reset as if there were no documents yet.', function () {
    // Now save user and check if its _id is what nextCount said.
    user.save(function (err) {
        should.not.exists(err);
        user._id.should.eql(0);

        // Call nextCount to check the next number. Should be one.
        user.nextCount(function (err, count) {
            should.not.exists(err);
            count.should.eql(1);

            // Now reset the count.
            user.resetCount(function () {
                // Call nextCount again to check that the next count is reset. Should be zero.
                user.nextCount(function (err, count) {
                    should.not.exists(err);
                    count.should.eql(0);
                    done();
                });
            });
        });
    });
});

With Q I turned it into this:

it('resetCount should cause the count to reset as if there were no documents yet.', function () {
    var userSchema = new mongoose.Schema({
        name: String,
        dept: String
    });
    userSchema.plugin(autoIncrement.plugin, 'User');
    var User = db.model('User', userSchema);

    // Create user and save it.
    var user = new User({name: 'Charlie', dept: 'Support'});
    // Now save user and check if its _id is what nextCount said.
    q.nmcall(user, 'save')
        .then(function (user) {
            user._id.should.eql(0);
            return q.nmcall(user, 'nextCount');
        })
        .then(function (count) {
            count.should.eql(1);
            return q.nmcall(user, 'resetCount');
        })
        .then(q.nmcall(user, 'nextCount'))
        .then(function (count) {
            count.should.eql(0);
        }, function (err) {
            should.not.exists(err);
        });

});

I no longer have to call the done callback because of how mocha understands to wait for the promise to resolve. I am new to Q so I'm wondering if I've done things the most efficient way. It seemed like calling node-style mongoose methods with q.nmcall (alias for q.invoke) made the most sense. However, if you think you could write the same code better then please let me know where I can improve it.


texts: Determining the cardinality of sets defined by recursively following indexes

texts:
Problem :

  A zero-indexed array A consisting of N different integers is given.
  The array contains all integers in the range [0..N−1]. Sets S[K] for 0
  ≤ K < N are defined as follows:

  S[K] = { A[K], A[A[K]], A[A[A[K]]], ... }.

  Sets S[K] are finite for each K.

  Write a function that, given an array A consisting of N integers,
  returns the size of the largest set S[K] for any array input.

This is my solution :

    public int solution(int[] A) {

         int arrayLength = A.length;
         int maxsize = 0;
         int count = 0;
         Set<Integer> resultSet = null;

         if(arrayLength <= 0)
         return 0;

         for(int i = 0; i < arrayLength; i++) {
           Set<Integer> tempSet = new LinkedHashSet<Integer>();
           int tempNum = A[i];
           count = 0;
           while(!tempSet.contains(tempNum)){
               tempSet.add(tempNum);
               tempNum = A[tempNum];
               count++;
           }
           if(count > maxsize) {
              maxsize = count;
              resultSet = tempSet;
           }
        }
         return maxsize;
     }

For example, given array A such that:

  A[0] = 5    A[1] = 4    A[2] = 0
  A[3] = 3    A[4] = 1    A[5] = 6
  A[6] = 2

the function should return 4, because set S[2] equals { 0, 5, 6, 2 } and has four elements. No other set S[K] has more than four elements.

My solution normally works but gives TIMEOUT ERROR for large sizes. How can I optimize the complexity of this code from O(N*R) to O(N)?


texts: Codewars: N-dimensional Von Neumann Neighborhood in a matrix

texts:
Task:
For creating this challenge on Codewars I need a very performant
function that calculates Von Neumann Neighborhood in a N-dimensional
array. This function will be called about 2000 times
The basic recursive approach:

calculate the index span influenced by the distance
if the index is in the range of the matrix go one step deeper into the next dimension
if max dimension is reached - append the value to the global neigh list isCenter is just a token that helps to NOT INCLUDE the cell
itself to the neighbourhood. There is also remaining_distance that
reduce the span.

You probably do not need to understand the process of this deep math so good. But maybe someone Python experienced can point me to some basic performance upgrade potential the code has.
Questions:

What I am curious about. Is .append inefficient? I heard list comprehensions are better than append.
Would not (0 <= dimensions_coordinate < len(arr)) changed to len(arr) <= dimensions_coordinate or dimensions_coordinate < 0) boost the code?
Are there performance differences between == and is?
Is dimensions = len(coordinates)... if curr_dim == dimensions:... slower than if curr_dim == len(coordinates)?
if you understood the math do you see a way to do it iterative? Because I heard recursions are slower in python and theoretical informatics says "Everything recursive can be iterative"

The whole code:

matrix is a N-dimensional matrix
coordinates of the cell is a N-length tuple
distance is the reach of the neighbourhood

def get_neighbourhood(matrix, coordinates, distance=1):
    dimensions = len(coordinates)
    neigh = []
    app = neigh.append

    def recc_von_neumann(arr, curr_dim=0, remaining_distance=distance, isCenter=True):
        #the breaking statement of the recursion
        if curr_dim == dimensions:
            if not isCenter:
                app(arr)
            return

        dimensions_coordinate = coordinates[curr_dim]
        if not (0 <= dimensions_coordinate < len(arr)):
            return

        dimesion_span = range(dimensions_coordinate - remaining_distance,
                              dimensions_coordinate + remaining_distance + 1)
        for c in dimesion_span:
            if 0 <= c < len(arr):
                recc_von_neumann(arr[c],
                                 curr_dim + 1,
                                 remaining_distance - abs(dimensions_coordinate - c),
                                 isCenter and dimensions_coordinate == c)
        return

    recc_von_neumann(matrix)
    return neigh


texts:
I need to write a function that searches the two-tier board according to certain parameters, which works, but I question whether there is a simpler, lighter way to perform this task.

<?php
function findValue(array $array, array $parameters, $multipleResoult = false){
    $result = array();//used when $multipleResoult == true
    $suspicious = false;
    foreach($array as $childArray){
        foreach($parameters as $k => $p){
            if(array_key_exists($k,$childArray)){
                if($childArray[$k] == $p){
                    $suspicious = $childArray;
                } else {
                    $suspicious = false;
                    continue 2;
                }
            } else {
                $suspicious = false;
                continue 2;
            }
        }
        if(is_array($suspicious)){
            $result[] = $suspicious;
            if($multipleResoult == true){
                $suspicious = false;
            } else {
                break;
            }
        }

    }
    return $result;
}
$arr =     Array
    (
        0 => Array
        (
            "id" => 1,
            "id_shop" => 1,
            "id_lang" => 1,
            "id_product" => 1,
            "id_field" => 3,
            "field_value" => "zxczxc"
        ),

    // find if single and multiple
    1 => Array
    (
            "id" => 2,
            "id_shop" => 1,
            "id_lang" => 2,
            "id_product" => 1,
            "id_field" => 3,
            "field_value" => "sdfsdfsdf"
        ),

    2 => Array
    (
            "id" => 3,
            "id_shop" => 1,
            "id_lang" => 2,
            "id_product" => 2,
            "id_field" => 3,
            "field_value" => "sdfsdfsdf"
        ),
    // find if multiple
    3 => Array
    (
            "id" => 3,
            "id_shop" => 1,
            "id_lang" => 2,
            "id_product" => 1,
            "id_field" => 3,
            "field_value" => "sdfsdfsdf"
        )

);
echo '-----------------SINGLE----------------------';echo "\n";echo '<pre>';
print_r(findValue($arr, array(
    'id_shop' => 1,
    'id_field' => 3,
    'id_lang'=> 2,
    'id_product' => 1)
                 ));
echo '-----------------MULTIPLE----------------------';echo "\n";echo '<pre>';
print_r(findValue($arr, array(
    'id_shop' => 1,
    'id_field' => 3,
    'id_lang'=> 2,
    'id_product' => 1)
                 ,true));
?>


texts: Averaging numbers from a file, obeying Single Responsibility Principle

texts:
Task:

  Given comma_separated.txt file with string:

1,2,3,4,5,6,7,8,9,10,11,12...,n

  Calculate the average value.

  For example: 1,2,3 should be equal 2 (float) as result.

Here is my solution in C:

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

int element_counter;
float* all_elements;

void mark_element_as_read() {
  element_counter += 1;
}

int get_number_of_read_elements() {
  return element_counter;
}

float* expand_array_stack_for(float* elements) {
  return realloc(elements, get_number_of_read_elements() * sizeof(elements));
}

void append_float(float element) {
  all_elements = expand_array_stack_for(all_elements);
  all_elements[get_number_of_read_elements()] = element;
}

float* get_collection() {
  return all_elements;
}

float* read_from_file(char* filename) {
  FILE *file_opened;

  file_opened = fopen(filename, "r");
  char elements[255];
  char * element;

  while (fgets(elements, sizeof(elements), file_opened) != NULL) {
    element = strtok(elements, ",");

    while (element != NULL) {
      append_float(strtof(element, NULL));
      mark_element_as_read();
      element = strtok(NULL, ",");
    }
  }

  free(element);
  fclose(file_opened);

  return get_collection();
}

int main() {
  float sum = 0.0, average;
  float *elements = read_from_file("comma_separated.txt");
  int i = 0;

  for (i = 0; i < get_number_of_read_elements(); i++) {
    sum += elements[i];
  }

  average = sum / get_number_of_read_elements();

  printf("average = %f\n", average);

  return 0;
}

This is my very first time coding in C. I used to code in Ruby, Java and PHP, so maybe this code would be a little bit "high leveled".


texts:
Explanation is in the function. Please point out any egregious errors:

create function api.ConstantTimeCompare (
    @x varbinary(8000) = 0x00
  , @y varbinary(8000) = 0x00
)
/*
    What? Compares two variable length binary strings byte by byte in constant time.

    When? Cryptography.

    Why? Given the strings 0x1234 and 0x1213 a simple equality comparison will stop processing after
         it hits the first mismatch at byte position 3. An opponent who only knows @x can exploit this
         feature to guess @y by trying thousands of comparisons and gathering statistics on how long
         each one took.

         In other words, assuming that it takes 100 milliseconds to compare at 16 byte string an
         opponent can rely on the fact that string that only takes 15 milliseconds to process is a
         worse guess than ones that take more than 15 milliseconds. A 50 millisecond comparison in
         this scenario means that @x is a 50% match of @y (from byte 1-8).

    How? Set up a loop based on the length of @x and perform a byte by byte XOR. If @result is still 0
         after all iterations then @x is equal to @y. If the comparison is meant to be secure then the
         untrusted string should be @x and the trusted string should be @y.
 */
returns bit
with schemabinding
as
begin;
    declare @i int = 0;
    declare @l int = DataLength(@x);
    declare @result int = @l - DataLength(@y);

    while (@i < @l)
    begin;
        set @result = ((@result ^ Substring(@x, @i, 1)) ^ Substring(@y, @i, 1));
        set @i = @i + 1;
    end;

    set @result = case @result when 0 then 1 else 0 end;

    return @result;
end;


texts:
I'm just looking for some feedback:

import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.JPanel;

public class Clock extends JFrame {

    public Clock () {
        setContentPane(new ScreenSaver());
    }

    public static void main(String[] args) {

        Clock clock = new Clock();

        clock.setSize(685, 80);
        clock.setUndecorated(true);
        clock.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        clock.setBackground(Color.BLACK);
        clock.setResizable(false);
        clock.setVisible(true);
        clock.toFront();

    }
}

Second class:

public class ScreenSaver extends JPanel implements ActionListener {

    public String stringDate;
    public JComboBox colorList;
    public Color userColor = Color.RED;
    public JPanel panel = new JPanel();
    public JButton button = new JButton("Alarm Clock");
    public static String time = "";
    public static Date date;
    public static DateFormat df;

    public ScreenSaver () {
        date();
        setLayout(new BorderLayout());
        Timer timer = new Timer(1000, this);
        timer.start();

        panel.setBackground(new Color(0,0,0,0));
        panel.setLayout(new BorderLayout());

        add(panel, BorderLayout.PAGE_START);

        String [] colorName = {"Red", "Blue", "Yellow", "Green", "Pink", "Grey"};
        colorList = new JComboBox(colorName);
        colorList.setBackground(Color.BLACK);
        panel.add(colorList, BorderLayout.LINE_START);

    }

    public void date() {
        df = new SimpleDateFormat("EEE,MMM d yyyy - h:mm:ss a");
        date = new Date();
        stringDate = df.format(date);

    }

    public void actionPerformed(ActionEvent e) {
        if (colorList.getSelectedItem().equals("Red"))
        userColor = Color.RED;
        else if (colorList.getSelectedItem().equals("Blue"))
        userColor = Color.BLUE;
        else if (colorList.getSelectedItem().equals("Yellow"))
        userColor = Color.YELLOW;
        else if (colorList.getSelectedItem().equals("Green"))
        userColor = new Color(5, 200, 51);
        else if (colorList.getSelectedItem().equals("Pink"))
        userColor = new Color(249, 100, 178);
        else if (colorList.getSelectedItem().equals("Grey"))
        userColor = Color.GRAY;

        colorList.setForeground(userColor);

    }

    public void paintComponent(Graphics g) {
       date();
       super.paintComponent(g);
       g.setColor(Color.BLACK);
       g.fillRect(0, 0, 685, 100);

        Font font = null;
        try {
            font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResource("/DIGITALDREAMFAT.ttf").openStream());
        } catch(FontFormatException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }

        GraphicsEnvironment gen = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gen.registerFont(font);
        font = font.deriveFont(30f);
        g.setFont(font);

       g.setColor(userColor);
       g.drawString(stringDate, 10, 60);
       repaint();

    }
}


texts: ES6 template literal tag function and polyfil fetch

texts:
The goal of this is to create an easy to use front-end interface to work with graphql APIs. Can anyone tell me if there are any inefficiencies or areas of improvement on my implementation? It would be much appreciated!

// @flow

import 'whatwg-fetch'

let uri: string = ''
let headers: Object = {}

function compile(strs: Array<string>, expressions: Array<any>): string {
  let query: string = strs[0]
  for (let i: number = 0; i < expressions.length; i++)
    query += `${expressions[i]}${strs[i + 1]}`
  return query
}

function post(query: string): Promise<Object> {
  return fetch(uri, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      query
    })
  }).then(res => res.json())
    .then(json => json.data)
    .catch(err => err)
}

const Ez: Object = {

  config(options: Object): void {
    uri = options.uri || options.url || ''
    headers = options.headers || { 'Content-type': 'application/json' }
  },

  ql(strs: Array<string>, ...exp: Array<any>): Promise<Object> {
    const query: string = compile(strs, exp)

    return post(query)
  },

  pql(query: string): Promise<Object> {
    return post(query)
  }

}

export default Ez

An example call would look something like this:

Ez.ql`
  {
    lot(number: 5) {
      permits
      totalSpaces
    }
  }
`


texts:
Find The Duplicates

Given two sorted arrays arr1 and arr2 of passport numbers, implement a function findDuplicates that returns an array of all passport numbers that are both in arr1 and arr2. Note that the output array should be sorted in an ascending order.

Let N and M be the lengths of arr1 and arr2, respectively. Solve for two cases and analyze the time & space complexities of your solutions: M ≈ N - the array lengths are approximately the same M ≫ N - arr2 is much bigger than arr1.

My approach:

import java.io.*;
import java.util.*;
import java.lang.*;

class Solution {

  static int[] findDuplicates(int[] arr1, int[] arr2) {
    // your code goes here
    int i = 0, j = 0, k = 0;
    ArrayList<Integer> ans = new ArrayList<>();
    while(( i < arr1.length) && (j < arr2.length))
    {
      if(arr1[i] < arr2[j])
          i++;
      else if(arr1[i] == arr2[j])
      {
          ans.add(arr1[i]);
          k++;
          i++;
          j++;
      }
      else
          j++;
     }
    int[] arr = new int[ans.size()];

    for(int l = 0; l < ans.size(); l++) {
    if (ans.get(l) != null) {
        arr[l] = ans.get(l);
    }
}
    return arr;
  }
   //M = arr1.length, N = arr2.length
  //Time = O(M+N)
  //Space = O(min(M,N))

I have the following questions regarding my code:

1) How can I improve the time and space complexity of my code?

2) Is there a better way(lesser lines of code, better data structures) that can be used to improve the code?

Source: Mock interview


texts:
Intro -> I have to convert an excel file, which comes usually in this way:

to a Json file that must looks like this:

"DE": {
   "Title":"Title_DE",
   "Subtitle":"Subtitle_DE",
   "Title_2":"Title_2_DE",
   "Subtitle_2":"Subtitle_2_DE"
}
"GR": {
   "Title":"Title_GR",
   "Subtitle":"Subtitle_GR",
   "Title_2":"Title_2_GR",
   "Subtitle_2":"Subtitle_2_GR"
}
"EN": {
   "Title":"Title_EN",
   "Subtitle":"Subtitle_EN",
   "Title_2":"Title_2_EN",
   "Subtitle_2":"Subtitle_2_EN"
}

What I've done -> I have used this node module xlsx to parse the excel file. The code currently works but something in my mind tells me that was not the best way to do it or at least there was a clearest or a smartest way.

const XLSX = require('xlsx');
const fs = require('fs');
let workbook = XLSX.readFile('./src/xls/test.xlsx');
let sheet_name_list = workbook.SheetNames; //--> sheet names
let isocodes = [];
let labels = [];
let copy = [];
let obj = {};
let j = 0;

sheet_name_list.map(sheet => { //--> sheet names loop
    let worksheet = workbook.Sheets[sheet];
    for (index in worksheet) {
        let idCol = index.substring(1, 3);
        let idRow = index.substring(0, 1);
        if (idCol === "1") {
            isocodes.push((worksheet[index].v).trim()); //--> isocodes
        }
        if (idRow === "A") {
            labels.push((worksheet[index].v).trim()); //--> labels
        }
        if (idRow != "A" && idCol != "1") {
            copy.push(worksheet[index].v); //--> copy
        }
    }
});

isocodes.shift(); //--> delete undefined
labels.shift();
copy.shift();

isocodes.map(iso => { //--> create object to convert
    obj[iso] = {};
    for (let i = 0; i < labels.length; i++) {
        obj[iso][labels[i]] = copy[(i * isocodes.length) + j];
    }
    j++;
});
//--> write json files in their folder
fs.writeFile('src/lang/desktop.json', JSON.stringify(obj).replace(/\\n|\\r/g, ''), 'utf8', console.log("desktop json file created"));
fs.writeFile('src/lang/mobile.json', JSON.stringify(obj).replace(/\\n|\\r/g, ''), 'utf8', console.log("mobile json file created"));

Please share your thoughts!!!


texts: Remove a key from a hash table efficiently

texts:
I am trying to remove a key from a hash table, which is built using linear probing. Removing a key works fine but I know I need to rehash a portion of the table after the removal but my method down below is not quite efficient. It basically rehashes the whole table that is unnecessary. Is there anyway that I could improve the performance while rehashing.

bool remove(int x, int H[], int m)
{
    int hashVal = hash(x, m);
    for (int i = 0; H[(hashVal + i) % m] != EMPTY; i++)
    {
        if (H[(hashVal + i) % m] == x)
        {
            H[(hashVal + i) % m] = EMPTY;

           //Rehash the table
           //I think the problem is here. This for loop condition can be better
            for (int k = 1; H[(hashVal + i + k) % m] != EMPTY ; k++)
            {
                int keyShiftUp = H[(hashVal + i + k) % m];

                H[(hashVal + i + k) % m] = EMPTY;

                insertLP(keyShiftUp, H, m);

                cout << "keyShiftUp: " << keyShiftUp << ends;
            }
            return true;
        }
    }
return false;
}


texts: Reading numbers from a file with lazy ByteString

texts:
This is my code for lazily reading a very large file which contains numbers separated by a new line character. Is there a way to simplify this using the ByteString module or would I have to use Data.Text

import Data.ByteString.Lazy.Char8 as L
main = do
  contents <- L.getContents
  print (sumFile contents)
     where sumFile x = sum $ Prelude.map tups $ Prelude.map L.readInt (L.words x)
         where read' = tups.(L.readInt)

tups :: (Num a) => (Maybe (a, b)) -> a
tups (Just (a,b)) = a
tups Nothing = 0


texts: Implementing lock within a Python script

texts:
I've written a script in Python using multiprocessing to handle multiple process at the same time and make the scraping process faster. I've used locking within it to prevent two processes from changing its internal state. As I'm very new to implement locking within multiprocessing, I suppose there is room for improvement.

What the scraper does is collect the name, address and phone number of every coffee shop traversing multiple pages from Yellowpage listings.

import requests
from lxml.html import fromstring
from multiprocessing import Process, Lock

link = "https://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los%20Angeles%2C%20CA&page={}"
itemstorage = []

def get_info(url,lock,itemstorage):
    response = requests.get(url).text
    tree = fromstring(response)
    for title in tree.cssselect("div.info"):
        name = title.cssselect("a.business-name span")[0].text
        try:
            street = title.cssselect("span.street-address")[0].text
        except IndexError: street = ""
        try:
            phone = title.cssselect("div[class^=phones]")[0].text
        except IndexError: phone = ""
        itemstorage.extend([name, street, phone])
    return printer(lock,itemstorage)

def printer(lock,data):
    lock.acquire()
    try:
        print(data)
    finally:
        lock.release()

if __name__ == '__main__':
    lock = Lock()
    for i in [link.format(page) for page in range(1,15)]:
        p = Process(target=get_info, args=(i,lock,itemstorage))
        p.start()


texts: Scraping the names of a whole category with a three-liner code

texts:
I've written a script in python using BeautifulSoup to parse the name of different coffee shops spreading across 51 pages in yellowpage website. I'm thrilled to see that it works perfectly. Except for importing libraries, I used three lines of code to do this. I think this time I've done this errorlessly.

Here is what I've tried with:

import requests
from bs4 import BeautifulSoup

for i in range(1, 52):
    for title in BeautifulSoup(requests.get("https://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los+Angeles%2C+CA&page={0}".format(i)).text, "lxml").findAll("h2",{"class":"n"},"a"):
        print(title.text)


texts:
I have a base and derived class since I need to have different kinds of concrete classes.
I cannot use the getInstance() function in the base class since I cannot make it both static and virtual.

class ITrafficEventsReturner {

    public:    virtual ~ITrafficEventsReturner() {} ;

    protected:

       ITrafficEventsReturner() { };

       // no definition for copy constructor and assignment operator
       ITrafficEventsReturner(const ITrafficEventsReturner&);
       ITrafficEventsReturner& operator=(const ITrafficEventsReturner&); };

    class ConcreteTrafficReturner : public ITrafficEventsReturner {

    public:
        static ConcreteTrafficReturner* getInstance() {
          if (myself == 0)
          {
             myself = new ConcreteTrafficReturner();
          }

          return myself;    }

       ~ConcreteTrafficReturner()
        {
          if (myself)
          {
             delete myself;
             myself = 0;
          }
        }

    private :    ConcreteTrafficReturner() : ITrafficEventsReturner()    {

       };

       static ConcreteTrafficReturner* myself; };

    ConcreteTrafficReturner* ConcreteTrafficReturner::myself = 0;

    int main()
    {
       ITrafficEventsReturner* ConcreteTrafficReturner =
            ConcreteTrafficReturner::getInstance();

       delete ConcreteTrafficReturner;
    };

This seems to be the possible solution :

class SingletonInterface
{
public:
   template <class T>
   static T& getInstance()
   {
      return T::getInstance();
   }

private:
   SingletonInterface() { };
};

class TrafficGenerator
{
public:

   static TrafficGenerator& getInstance()
   {
      static TrafficGenerator obj;
      return obj;
   }

   void whatAmI()
   {
      std::cout << " I am Traffic Generator" << std::endl;
   }

private:

   TrafficGenerator () {};
};

int main()
{

   TrafficGenerator& hTG = SingletonInterface::getInstance<TrafficGenerator>() ;
   hTG.whatAmI();
};


texts: Function to find a certificate in either the user or the machine store

texts:
I wanted a function that would return a certificate, given its serial number, regardless of which store it is in. It has to do almost the same exact thing but twice (once for each store). To keep it encapsulated I wrote the "same thing" bit as a lambda, sort of like a Javascript programmer might.

public X509Certificate FindClientCertificate(string serialNumber)
{
    Func<StoreLocation, X509Certificate> find = (location) =>
    {
        X509Store store = new X509Store(location);
        store.Open(OpenFlags.OpenExistingOnly);
        IEnumerable certs = store.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, true);
        return certs.OfType<X509Certificate>().FirstOrDefault();
    };
    return find(StoreLocation.CurrentUser) ?? find(StoreLocation.LocalMachine);
}

Questions:

Is the purpose and implementation of this function easier to read with the lambda expression? Or is this utterly confusing?
Is there any performance loss or other sort of hidden cost of using a lambda expression as a nested function?

I'm looking forward to C#7 local functions :)


texts: Safely using android 'Context' inside threads

texts:
Oftentimes I find myself using context inside threads, multiple times. The problem is that I do not want to hold a long-lived strong reference of it in my threads to avoid leaking it. I keep a weakReference to it in global space and when my activity dies, it will obviously not prevent any GC events or such.

I have made the following approach to using context in threads:

public interface UseContext<Result, Param extends Context> {
    Result work(Param context);
}

public static <T extends Context, Result> Optional<Result> useContext(final WeakReference<T> reference,
                                                                      final UseContext<Result, T> task) {

    final T context;
    final boolean contextLost = (context = reference.get()) == null;
    final boolean isActivity = context instanceof Activity;

    if (contextLost)
        return Optional.absent();
    final boolean activityIsFinishing = (isActivity && ((Activity) context).isFinishing());
    if (activityIsFinishing)
        return Optional.absent();

    return Optional.fromNullable(task.work(context));
}

Whenever I have to use context inside a thread, I do this (example) :

        MiscUtils.useContext(reference, activity -> {
            activity.runOnUiThread(() -> Toast.makeText(activity, message, Toast.LENGTH_SHORT).show());
            return null;
        });

Is this a correct approach? Also, I'm not entirely convinced that holding a strong reference to Context in global space and using it in runnable is a bad idea. I understand that it was something to do with anonymous inner classes causing memory leaks.


texts:
I am trying to convert myself from using mysql extension to using PDO, with that being said I was curious if I am going about this the right way.

I have a custom logging system that I built I am wondering if the way I implemented this would work or not. I am planning on duplicating the main functions of PDO and doing the same as what I did prepare?

What I wanted to know is if the way I turned on exceptions and internally using try/catch blocks to capture and log errors then rethrowing the exception after I logged the error is the right way to do this or is there another more efficient way of doing this.

class rDB extends PDO {

private $dsn    = "mysql:host=10.10.10.43";
private $user   = "user";
private $pass   = "pass";

/**
 * @var Logger Writes messages to custom csv log based on debug level of 1-5
 * 1 Being Critical Error, 5 Being a simple Note
 */
private $logger;

public function __construct($logger) {

    $this->logger = $logger;
    $this->logger->log(5, 'Connecting to MySQL DB');

    try {
        /* Call to Parent Function */
        parent::__construct($this->dsn, $this->user, $this->pass);

        $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $this->logger->log(5, 'Connected to MySQL DB');
    }
    catch(PDOException $e) {
        $this->logger->log(2, 'Connection to MySQL DB Failed-> '.$e->getPrevious());
        throw $e;
    }
}

public function prepare($statement, array $driver_options = 'array()') {
    try {
        $this->logger->log(5, 'Preparing statement');
        /* Call to Parent Function */
        $value = parent::prepare($statement, $driver_options);
    }
    catch(PDOException $e) {
        $this->logger->log(2, 'Error preparing statement-> '.$e->getMessage());
        throw $e;
    }
    $this->logger->log(5, 'Statement is prepared.');
    return $value;
}
}


texts:
I am trying to learn flex and have created this simple program. The rule for comments works correctly for single line comments such as:

// this is a comment

and this:

/* this is also a comment */

My code:

ID [A-Z][A-Za-z0-9]
KEYWORD if|else|then|for|fi|loop|pool|proc|func
OPERATOR "+"|"-"|"/"|"*"|"&"|"%"
PUNCTUATION ":"|","
%%
{ID} printf("An Id found:%s\n",yytext);
{KEYWORD} printf("An Keyword found:%s\n",yytext);
{OPERATOR} printf("An Operator found:%s\n",yytext);
{PUNCTUATION} printf("An Punctuation found:%s\n",yytext);
[/][/].*

"/*".*"*/"

%%
int yywrap(){
  return 1;
}
main(){
  yylex();
}

I'd be interested in comments on this and particularly ways to improve the code, such as for being able to detect multi-line comments.


texts: Take postcodes and get the Lat long information from them

texts:
I had an interview task which was the final stage, however, the feedback I got back for my solution was that it lacked effort and structure. I would be grateful to know how my solution could be improved. I used postcode.io to get the latitude and longitude from the post codes.
Here is the Description:

Brief: Create a server application that allows a user to input one or more postcodes, and then returns location-specific information
based on the postcode entered.
Requirements: At least one of the external APIs made available to you should be used to retrieve the information that your API returns.
You are not limited to using only one, and are free to use as many of
them as you like (inc. any other external resources) in order to
provide useful data.

Based on the above I made the following program.
app.js
import * as express from "express";
import * as axios from "axios";

const app = express();
app.use(express.json());

app.get("/", (req, res) => {
  res.send("Server is up and running ");
});

app.get("/postcode/:postcode", async (req, res) => {
  const postcode = req.params.postcode;
  await getLatlonFromPostcode(postcode).then((data) => {
    res.send(data);
  });
});

app.post("/postcodes", async (req, res) => {
  const postCodes = req.body.postcodes;
  const result = await getAdressForMultiplePostCodes(postCodes).then(
    (response) => {
      return returnLatLonObj(response.result);
    }
  );
  res.json(result);
});

//Return the lat and lon for a single postcode
export async function getLatlonFromPostcode(postcode) {
  try {
    const res = await axios
      .get(`https://api.postcodes.io/postcodes/${postcode}`)
      .then((response) => {
        const lat = response.data.result.latitude.toString();
        const lon = response.data.result.longitude.toString();
        return `${lat}, ${lon}`;
      });
    return res;
  } catch (error) {
    console.error(error);
  }
}

//Return array of addresses from Postcode array
export async function getAdressForMultiplePostCodes(postcodes) {
  try {
    const res = await axios
      .post("https://api.postcodes.io/postcodes", {
        postcodes,
      })
      .then((response) => {
        return response.data;
      });
    return res;
  } catch (error) {
    console.error(error);
  }
}

//Grab Latitude and Longitude and convert Array to object
function returnLatLonObj(arr) {
  return arr.reduce((prev, curr) => {
    prev[curr.result.latitude] = curr.result.longitude;
    return prev;
  }, {});
}

export default app;

This is my index.js
import app from "./app";

app.listen(3000, () => {
    console.log("server listening on port 3000");
})

This was my test file, which I used jest for.
import { getLatlonFromPostcode } from "../app";

describe("getLatlonFromPostcode", () => {
  test("it should return latlon for given postcode", async () => {
    const latlon = await getLatlonFromPostcode("ox495nu");
    expect(latlon).toEqual("51.655929, -1.069752");
  });
});

describe("getLatlonFromPostcode in uppercase", () => {
  test("it should return latlon for given postcode", async () => {
    const latlon = await getLatlonFromPostcode("OX49 5NU");
    expect(latlon).toEqual("51.655929, -1.069752");
  });
});

describe("getLatlonFromPostcode with spaces between the postcode", () => {
  test("it should return latlon for given postcode", async () => {
    const latlon = await getLatlonFromPostcode("OX49 5NU");
    expect(latlon).toEqual("51.655929, -1.069752");
  });
});


texts: Employee name auto-complete on card scan

texts:
Im currently running an employee name substitution on card scan.
Overall the code takes the entry trough the gun scan, "scan" trough the hidden reference sheet to find a match and then input the actual complete name.
I had to implement that feature to my code so that names are always written the same (for futur data treatment purpose).
If y'all have some tip, hint or other proposition to optimise the code.
One of my goal would be for it to auto-fill with any entry (right now mostly working with operator numbers) or to suggest entries based on what's written in real time in a scrolling menu (if it's not too much).
Here's my codes :
Sub Workbook_sheetChange(ByVal Sh As Object, ByVal Target As Range)
Application.EnableEvents = False
Application.ScreenUpdating = False
If Not Intersect(Target, Sh.Range("C5:C8")) Is Nothing Then 'If change in "no.employé" cells

Call Employe ' Call name standardization macro

End If
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub

Sub Employe()
' Standardization of the operator name macro
' The code automaticly enters the employee names by is number entry
' Therefore permits employee to scan their pass and get their full names automaticly

Dim ash As Worksheet
Set ash = ActiveSheet ' Identify active sheet
Dim positionInitCaseNom1enY As Long: positionInitCaseNom1enY = 5 'First "Name" cell row position
Dim positionCaseNomEnX As Long: positionCaseNomEnX = 3           '"Name" cells culumn position
Dim k As long: k = positionInitCaseNom1enY                    ' Counter incrément position
Dim no As Variant  ' Value of name cell (changes every loop)
Dim i As Integer   ' Row integer

    For i = 0 To 3
    k = k + i       ' Up a row (first 0)
    no = ash.Cells(k, positionCaseNomEnX).Value ' Gives "no" the current "Name" cell value

        If no <> "" Then   ' Vérify if theres something in "Name" cell
        Dim nos As String
        nos = CStr(no)     ' no to string (now nos)
        Dim valeurnorm As Range
        Set valeurnorm = Sheets("Liste Employé").Range("A2:A200").Find(nos)
        ' Looking for a match in name reference sheet

            If valeurnorm Is Nothing Then ' If no match found
                If MsgBox("Entrer un numéro d'employé valide" & vbNewLine & "Le numéro d'employé entrée est le suivant: " & nos, 5 + vbCritical, "Erreur") = vbRetry Then
                ' Msgbox that the employee entered a false number and to retry

                    ash.Cells(k, positionCaseNomEnX).Value = "" ' Clear old number
                    ash.Cells(k, positionCaseNomEnX).Select     ' Reselect cases

                End If
            Else ' If name is in the reference sheet

                ash.Cells(k, positionCaseNomEnX).Value = valeurnorm ' Change the value of the entry for the complete name
            End If

        End If
  Next
End Sub

Sorry for all of the typos, i need to translate everything and my written english is kinda s***.


texts: Pulling data quickly from mongodb with node.js

texts:
I am currently struggling with a request I am making to my server that is taking more than 4 seconds! I cut out a lot of the cruft to hopefully make it easier to read. Excuse my horrible variable names. I looked for a while online and it seems that .toArray() is slow for MongoDB. However I would defer to someone with more knowledge.

socket.on('userInput', function (exampleMarket) {

    //example of a collection name
    //var exampleMarket = 'FTSE100';
    var red = {};

    APP.db2.collection(exampleMarket + '-market', function(err, res) {

        if (res === null) {
            logger.log('no match in database 1')
            return
        }

        res.find().toArray(function (err,doc) {

            red=doc;

        });

    });

    var green= {

        collection  : [],
        type        : 'market',
        open        : [],
        high        : [],
        low         : [],
        volume      : [],
        close       : [],
        date        : [],
        code        : [],
        description : [],
        frequency   : [],
        fromDate    : [],
        lastUpdate  : [],
        toDate      : [],
        name        : [],
        color       : [],
        movement    : [],
        difference  : [],
        point       : [],
        tail        : [],
        chartdata   : {
            xaxis   : [],
            yaxis   : []
        }

    };

    APP.db.collection(exampleMarket, function(err, res) {

        if (res === null) {
            logger.log('no match in database 1')
            return
        }

        //logs fast
        logger.log('test1')
        socket.emit('Share', 'test1')

        res.find().toArray(function (err,doc) {
            //No errors
            logger.log(err)

            for (var i = 0; i < doc.length; i++) {

                if (doc[i].code === undefined) {
                    green.marketOverview = doc[i].market;
                    continue;

                }

                green.collection.push(exampleMarket);
                green.chartdata.xaxis.push(doc[i].date);
                green.chartdata.yaxis.push(doc[i].open);
                green.name.push(doc[i].name);

                green.toDate.push(doc[i].toDate);
                green.color.push(doc[i].color);
                green.movement.push(doc[i].movement);
                green.difference.push(doc[i].difference);
                green.point.push(doc[i].point);
                green.tail.push(doc[i].tail);

                green.open.push(doc[i].open[0]);
                green.date.push(doc[i].date[0]);
                green.high.push(doc[i].high[0]);
                green.low.push(doc[i].low[0]);
                green.volume.push(doc[i].volume[0]);
                green.close.push(doc[i].close[0]);
                green.code.push(doc[i].code);

            }

            green.marketName = exampleMarket;

            socket.emit('Share', green, red);

            //this takes about 3 seconds to log out
            logger.log('test2')
            socket.emit('Share', 'test2')

        });
        //logs fast
        socket.emit('Share', 'test3')
    });

});


texts: Regular expressions - match only specified string length

texts:
I'm learning regex. Here I'm checking a string of type aA1 but want also to check it is only 3 characters long.  Is there a better way of doing it please?

str = raw_input("input in form 'aA1' please >")
check = re.compile("[a-z][A-Z][0-9]")
if len(str) == 3:
    validate = check.match(str)
    if validate:
        print "Correct string"
    else:
        print "Incorrect string"
else:
    print "Wrong length"


texts: Creating a Ruby gem that talks to another gem

texts:
I am working on creating an interface gem that works with the Jira-Ruby gem.

I have several questions and would like a general review for both my code and my attempt at creating a gem (I've never written one before). Any advice on where to go next would also be appreciated.

File structure:

jira_interface
   lib
      jira_interface
          config.rb
          version.rb
          app_interface.rb
      jira_interface.rb
   jira_interface.gemspec
   #...etc files, I used bundle's gem command to set up

My main module (jira_interface.rb) looks like this:

require "jira_interface/version"
require "jira"
require "jira_interface/config"
require "jira_interface/app_interface"

module JiraInterface

  def get_jira_client
      @client = Jira::Client.new(USERINFORMATION)
  end

  def get_project(project_name)
     @client.Project.find(project_name)
  end

end

And my app_interface.rb looks like this:

class AppInterface < JiraInterface
  before_filter :get_jira_client

  def create_issue(issue_desc, project)
    issue = @client.Issue.build
    issue.save({"fields"=>{"summary"=> issue_desc, "project"=> {"id" => project.id}, "issuetype"=> {"id"=> "1"}}})
  end

  def update_issue(issue_id)
    issue = @client.Issue.find(issue_id)

    comment = issue.comments.build
    comment.save({"body"=> "This happened again at #{Date.time}"})
  end

  def get_issues(issue_desc, project_name)
    project = get_project(project_name)

    if project.issues.detect { |issue| issue.fields['summary'].include?(issue_desc) }
      update_issue(issue.id)
    else
      create_issue(issue_desc, project)
    end
  end

end

The goal is pretty simple: call get_issues() from the rails app when an error happens. If the error is already documented, post a comment saying that it happened again. If it's not, then create a new issue.

To the best of my knowledge, this should work because I've been following the examples found online.  However, I've been having a heck of a time just testing it. If anyone could suggest a good way of testing this, that would be much appreciated.


texts:
I would like to see suggestions if my code could be more improved. In my controller I have a line:

self.bool_value = False  # for testing

which in my opinion should not be there, because I put it there only for testing purposes, but I did not find any way around. In addition I would like to know whether you guys test the __init__ method as well, because I see no point in it. And another question would be, if you guys would test if the parameter req was called in the execute method. Any other suggestions to improve this code are welcomed.

My Controller looks like this:

from typing import Callable
from source.controller.RequestModel import RequestModel
from source.boundaries.AbstractInputBoundary import       AbstractInputBoundary

class Controller:

abstractInputBoundary: AbstractInputBoundary
bool_function: Callable[[bool], bool]
bool_value: bool

def __init__(self, abstract_input_boundary, bool_function=lambda _:     True):
    self.abstractInputBoundary = abstract_input_boundary
    self.bool_function = bool_function
    self.bool_value = True

def process_input(self) -> None:
    """
    Waits for the input of the User in order to call a usecase
    :rtype: None
    """
    while self.bool_function(self.bool_value):
        self.bool_value = False  # for testing
        inp: str = input()

        if inp == "show data":
            req = RequestModel()
            req.setRequest(inp)
            self.abstractInputBoundary.execute(req)

My Test looks like the following:

import unittest
from source.controller.Controller import Controller
from unittest.mock import patch
from unittest.mock import MagicMock

class TestController(unittest.TestCase):

def test_process_input(self):
    """
    This tests, whether after the input "show data" in the controller object a boundary object is called
    """

    def switch_function(switch_bool):
        if switch_bool is True:
            return True
        else:
            return False

    with patch('builtins.input') as inp:
        inp.return_value = "show data"
        boundary = MagicMock()
        boundary.execute = MagicMock()
        controller = Controller(boundary, switch_function)
        controller.process_input()
        assert boundary.execute.called


texts:
The program assignment:

  A drunkard in a grid of streets randomly picks one of four directions
  and stumbles to the next intersection, then again randomly picks one
  of four directions, and so on. You might think that on average the
  drunkard doesn't move very far because the choices cancel each other
  out, but that is not the case. Represent locations as integer pairs
  (x,y). Implement the drunkard's walk over 100 intersections, starting
  at (0,0) and print the ending location.

I created this Drunkard class:

import java.util.*;

class Drunkard {
    int x, y;
    Drunkard(int x, int y) {
    this.x = x;
    this.y = y;
    }
    void moveNorth() {
    this.y -= 1;
    }
    void moveSouth() {
    this.y += 1;
    }
    void moveEast() {
    this.x += 1;
    }
    void moveWest() {
    this.x -= 1;
    }
    void report() {
    System.out.println("Location: " + x + ", " + y);
    }
}

And this DrunkardTester class to test the above class

import java.util.Random;

public class DrunkardTester {
    public static void main(String[] args) {
    Random generator = new Random();
    Drunkard drunkard = new Drunkard(0, 0);
    int direction;
    for (int i = 0; i < 100; i++) {
        direction = Math.abs(generator.nextInt()) % 4;
        if        (direction == 0) { // N
        drunkard.moveNorth();
        } else if (direction == 1) { // E
        drunkard.moveEast();
        } else if (direction == 2) { // S
        drunkard.moveSouth();
        } else if (direction == 3) { // W
        drunkard.moveWest();
        } else {
        System.out.println("Impossible!");
        }
    }
    drunkard.report();
    }

}

It complies and runs fine, and it prints a different coordinate location each time I run it, but I just wanted to get a few other pairs of eyes on it to see if there are any glaring errors.

Also, on my DrunkardTester class is there anyway to eliminate the "Impossible!" else statement? I wasn't really sure if that was necessary or what else could be put there.


texts: Division without using addition, multiplication or division

texts:
Could you please tell me if there is better way of performing division without +, * or /?

I've tested this code for different values of a and b.  Could you please tell me if there is a cleaner solution?

   private static int divide(int a , int b){

        if(a<b) return a;
        boolean isNeg=false,sign=true,bothNegative=false;
        int quotient=1;

        if( a<0 && b<0 ){
            bothNegative=true;
        }else if(a<0||b<0) {

            isNeg=true;
            sign=true;

        }

            a=Math.abs(a);
            b=Math.abs(b);
            int s=add(a,-b);

            while(Math.abs(s)>=Math.abs(b)){
                b=add(b,b);
                s=add(a,-b);
                quotient=add(quotient,1);
                 if(isNeg){
                    sign=!sign;
                }
            }

            if(bothNegative){
                return quotient;
            }else if(isNeg && !sign){
                quotient=add(0,-quotient);
             }

            return quotient;

    }
    private static int add(int a , int b){
            do{
                a=a^b;
                b=(a^b)&b;
                b=b<<1;
            }while(Math.abs(b)!=0);

            return a;
        }


texts: Most basic HTML website - naming and CSS rules

texts:
I'm trying to accomplish something very simple as seen here.

HTML

Link

Link

Link

CSS

.container {
    padding-left: 80px;
    padding-right: 80px;
}
#header {
    height: 50px;
    line-height: 50px;
    background-color: blue;
}
#header_nav {
    float:right;
}
#header_nav li {
    display: inline-block;
}

Questions:

Am I using the IDs and classes correctly?  For example, should header be an ID or class?
Is my naming convention ok?
Should I be using nested rules instead? E.g #header ul li { ...  }
Is this the best way to achieve this layout?

Any advice at this stage would be good, so I can take these practices forward when doing the next steps of the structure.


texts:
I created a simple number-guessing game.  Do I need to divide this program into functions?  Please offer suggestions.

#include<iostream>
#include<string>
#include<ctime>

void drawLine(int n, char symbol);
void rules();

int main()
{
    int amount;
    int bettingAmount;
    int guess;
    int dice;
    std::string playerName;

    drawLine(60,'_');
    std::cout << "\n\n\n\t\tCASINO GAME\n\n\n\n";
    drawLine(60,'_');
    std::cout << "\n\nEnter Your Name : ";
    std::getline(std::cin, playerName);
    std::cout << "\n\nEnter Deposit amount to play game : ";
    std::cin >> amount;
    char choice;
    do
    {
        system("cls");
        rules();
        std::cout << "\n\nYour current balance is $ " << amount << "\n";

        do
        {
            std::cout <<playerName<<", enter money to bet ";
            std::cin >> bettingAmount;
            if(bettingAmount > amount)
                std::cout << "Your betting amount is more than your current balance\n\nRe-enter data\n ";
        }while(bettingAmount > amount);

        do
        {
            std::cout << "Guess your number to bet between 1 to 10 :";
            std::cin >> guess;
            if(guess <= 0 || guess > 10)
                std::cout << "Please check the number!! should be between 1 to 10\n\nRe-enter data\n ";
        }while(guess <= 0 || guess > 10);

        srand(time(0));
        dice = rand()%10 + 1;

        if(dice == guess)
        {
            std::cout << "\n\nGood Luck!! You won Rs." << bettingAmount * 10;
            amount = amount + bettingAmount * 10;
        }
        else
        {
            std::cout << "Bad Luck this time !! You lost $ "<< bettingAmount <<"\n";
            amount = amount - bettingAmount;
        }

        std::cout << "\nThe winning number was : " << dice <<"\n";
        std::cout << "\n"<<playerName<<", You have $ " << amount << "\n";
        if(amount == 0)
        {
            std :: cout << "You have no money to play ";
            break;
        }
        std::cout << "\n\n-->Do you want to play again (y/n)? ";
        std::cin >> choice;
    }while(choice =='Y'|| choice=='y');

    std::cout << "\n\n\n";
    drawLine(70,'=');
    std::cout << "\n\nThanks for playing game. Your balance amount is $ " << amount << "\n\n";
    drawLine(70,'=');

    return 0;
}

void drawLine(int n, char symbol)
{
    for(int i=0; i<n; i++)
        std::cout << symbol;
    std::cout << "\n" ;
}

void rules()
{
    system("cls");
    std::cout << "\n\n";
    drawLine(80,'-');
    std::cout << "\t\tRULES OF THE GAME\n";
    drawLine(80,'-');
    std::cout << "\t1. Choose any number between 1 to 10\n\t2. If you win you will get 10 times of money you bet\n\t3. If you bet on wrong number you will lose your betting amount\n\n";
    drawLine(80,'-');
}

// END OF PROGRAM


texts:
I'd like to verify that the security of this JavaScript code is correctly doing what I believe it's doing.  Its intended purpose is to generate xkcd-style passwords randomly in the visitor's browser.

When the page loads, the full wordlist is loaded into the browser synchronously (>350K words) and then generates a secure seed.

  $(document).ready(function() {
    wordlist = [];

    $.ajax({ url: '../xkcd_wordlist.txt',
      async: false,
      success: function(data) {
        wordlist = data.split('\n');
      }
    });

    Math.seedrandom();
    updatePasswordField();
  });

There are various other UI things happening before the main updatePasswordField function is called, but I've omitted those for brevity.  Once the updatePasswordField is called, it randomly chooses from the list that was fetched earlier.

wordlist[Math.floor(Math.random()*wordlist.length)]

I can't see anything wrong with this setup, but would like to make sure I can get a second set of eyes (or as many as would like) before I declare it secure.

From a position of security, is this sufficiently random?

Relevant code sections:

  function updatePasswordField() {
    // Generate and Return the XKCD style password
    var step;
    var final_xkcd_password = "";
    var number_of_words = $('#word-count').val();

    for (step = 0; step < number_of_words; step++) {
      final_xkcd_password = final_xkcd_password + " " + wordlist[Math.floor(Math.random()*wordlist.length)];
    }
  };

  $(document).ready(function() {
    wordlist = [];

    $.ajax({ url: '../xkcd_wordlist.txt',
      async: false,
      success: function(data) {
        wordlist = data.split('\n');
      }
    });

    Math.seedrandom();
    updatePasswordField();
  });


texts:
I am using if statements within my functions to validate form fields and then on the isset event.

I want to be able to create many different functions to validate various fields groups, and it seems that this statement could grow very long:

if (($namecheck === TRUE) && ($emailcheck ===TRUE) && ($messagecheck ===TRUE)) {

This also causes the alert for each function if no data is entered. I can circumvent this by making statements if one proves false, then stop, but it is only getting messier and messier.

I don't need my code written for me. As such, I am interested in what you suggest, in terms of if statements, using switch or loop instead, or any other ideas.

I am not so much wanting a solution here, as reasons for why some ways are better than others. For the purposes of this discussion, I am not concerned with client side validation. It is a focus on PHP functions only.

<?php

include ("contact.html");

function namecheck ($fname, $lname) {
    $regexp ="/^[A-Za-z]+$/";
//filter through names
 if (preg_match($regexp,$fname,$lname)) {
     return TRUE; }
    else {
        echo'<script type="text/javascript">alert("Enter your names.")</script>';
        return FALSE; }}

function emailcheck ($email1, $email2) {
$regexp="/^[a-zA-A-Z0-9_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$/";
//validate email address
if (preg_match($regexp,$email1,$email2)) {
    return TRUE; }
    else {
        echo '<script type="text/javascript">alert ("Enter a valid email address.")</script>';
        return FALSE; }}

function messagecheck ($message) {
$regex = "/^[a-zA-Z0-9.?!_-]+$/";
//validate message text
if (preg_match($regex,$message)) {
    return TRUE;}
    else{
        echo'<script type="text/javascript">alert("Enter your message.")</script>';
        return FALSE; }}

if (isset($_POST['submit'])) {

  $fname=$_POST['fname'];
  $lname=$_POST['lname'];
  $namecheck=namecheck($fname);
  $email1=$_POST['email1'];
  $email2=$_POST['email2'];
  $emailcheck=emailcheck($email1,$email2);
  $message = $_POST['message'];
  $messagecheck=messagecheck($message);

   if (($namecheck === TRUE) && ($emailcheck ===TRUE) && ($emailcheck ===TRUE)) {

    $subject="website contact";
    mail("myemail", $subject ,$message , "From: $email1");
     echo '<script type="text/javascript"> alert("Your form has been submitted.") </script>';  }  }

?>


texts:
I am reading from a Networkstream, and the response code is:

private async void GetResponse(NetworkStream stream)
{
  while (true)
  {
    var readBuffer = new byte[4096];
    var asyncReader = await stream.ReadAsync(readBuffer, 0, readBuffer.Length);
    var result = RemoveBytes(readBuffer, new byte[] { 130, 119, 126, 118, 48, 49, 12, 19, 14 });
    List<byte> l = null;
    var w = 1;
    while (w > 0)
    {
      w = FindPattern(result, new byte[] { 1, 0, 131 }, new[] { false, true, false });
      if (w <= 0) continue;
      l = result.ToList();
      l.RemoveAt(w);
      l.RemoveAt(w);
      l.RemoveAt(w);
      Buffer.BlockCopy(l.ToArray(), 0, result, 0, result.Length - 3);
    }
    if (l != null) txtBoxMessagesIn.Text += Encoding.ASCII.GetString(l.ToArray()) + Environment.NewLine;
    if (asyncReader <= 0) break;
  }
}

I initially remove a group of know bytes using:

public static byte[] RemoveBytes(byte[] input, byte[] pattern)
{
  if (pattern.Length == 0) return input;
  var result = new List<byte>();
  int i;
  for (i = 0; i <= input.Length - pattern.Length; i++)
  {
    var foundMatch = !pattern.Where((t, j) => input[i + j] != t).Any();
    if (foundMatch) i += pattern.Length - 1;
    else result.Add(input[i]);
  }
  for (; i < input.Length; i++)
  {
    result.Add(input[i]);
  }
  return result.ToArray();
}

Then I have the following method to search for a pattern with a wilcard in a byte array:

public static int FindPattern(byte[] body, byte[] pattern, bool[] wild, int start = 0)
{
  var foundIndex = -1;
  if (body.Length <= 0 || pattern.Length <= 0 || start > body.Length - pattern.Length || pattern.Length > body.Length) return foundIndex;
  for (var index = start; index <= body.Length - pattern.Length; index += 4)
    if (wild[0] || (body[index] == pattern[0]))
    {
      var match = true;
      for (var index2 = 1; index2 <= pattern.Length - 1; index2++)
      {
        if (wild[index2] || (body[index + index2] == pattern[index2])) continue;
        match = false;
        break;
      }
      if (!match) continue;
      foundIndex = index;
      break;
    }
  return foundIndex;
}

I think the remove bytes method is fine, but the way I search for the wilcard pattern and copy the array seems a bit clunky. Credit to the author of the wildcard search code which can be found here.


texts:
I built a simple console version of the rock paper scissors game. I would love to get some constructive criticism!

Questions

How could I code this in an object-oriented way?
Did my code follow the DRY principle?

Link to code

Repl: https://repl.it/@antgotfan/CrowdedGreenFlatassembler

        var moves, result, images, relativePath, playerSelection, computerSelection;

    moves = {
        rock: 0,
        paper: 1,
        scissors: 2,
    };

    function init() {

        result = {
            player: 0,
            tie: 0,
            computer: 0
        };
    }

    init();

    function convertMoves() {
        // when any rock paper scissor button is clicked

        // then return that string into the moves object

        // return a number corresponding to the handsign.
        playerSelection = prompt("Please choose rock, paper, or scissors!");
        return moves[playerSelection];
    }

    function computerPlay() {
        var movesValues = Object.values(moves);
        var random = Math.floor(Math.random() * movesValues.length);
        return movesValues[random];
    }

    function playRound(playerSelection, computerSelection) {
        computerSelection = computerPlay();
        playerSelection = convertMoves();

        var processResult = (3 + computerSelection - playerSelection) % 3;

        if (!processResult) {
            ++result.tie;
            console.log('tie');
        } else if (1 === processResult) {
            ++result.computer;
            console.log('Computer won');
        } else {
            ++result.player;
            console.log('Player won');
        }

        return result;
    }

    function game() {
        for (var perRound = 1; perRound < 5; perRound++) {
            playRound(playerSelection, computerSelection);
        }
    }

    game();
    console.log(playRound(playerSelection, computerSelection));


texts:
I'm writing to some serial comm port with specific bytes set into buffer. My protocol for write buffer is written below. Platform is Windows and IDE is Visual C++.

Byte 0 will have message type indicator (Byte)
Byte 1-4 will have message number (Uint32)
Byte 5-8 will have unix epoch time (Uint32)
Byte 13-14 will have number of sample packets (Uint16)
Bytes 15+ (upto 60) will have sample data packets (Uint16)
Byte 15+(No of samples*2) will have end of message (Byte)

Now I'm concern about buffer building (raw Bytes) from integer or short values.

void ConvertIntToByte(int iValue, BYTE* ucRawBuffer, int iOffset)
{
  ucRawBuffer[iOffset]   = ((iValue >> 24) & 0xFF);
  ucRawBuffer[iOffset+1] = ((iValue >> 16) & 0xFF);
  ucRawBuffer[iOffset+2] = ((iValue >> 8) & 0xFF);
  ucRawBuffer[iOffset+3] = (iValue & 0xFF);
}

void ConvertShortToByte(short iValue, BYTE* ucRawBuffer, int iOffset)
{
  ucRawBuffer[iOffset]   = (iValue >> 8) & 0xFF;
  ucRawBuffer[iOffset+1] = iValue & 0xFF;
}

void DataThreadFunction()
{
  while(!m_bClosed)
  {
    DWORD dwRet = WaitForSingleObject(m_hDataSendEvent, INFINITE);
    if(dwRet == WAIT_OBJECT_0)
    {
      ResetEvent(m_hDataSendEvent);

      int iUTCTime = GetEpochTime();
      m_iMsgSequence++;
      ASSERT(m_iMaxSamples != 0);

      BYTE ucXmtdat[60] = {0};
      ucXmtdat[0] = 0x0B;
      ConvertIntToByte(iUTCTime, ucXmtdat, 1);
      ConvertIntToByte(m_iMsgSequence, ucXmtdat, 5);
      ConvertIntToByte(m_iMaxSamples, ucXmtdat, 13);
      int iOffset = 15;
      // m_data - member vector populating from some other method
      for(unsigned int i = 0; i < m_data.size(); i++)
      {
        short iCurrData = m_data[i];
        ConvertShortToByte(iCurrData, ucXmtdat, iOffset);
        iOffset += sizeof(unsigned short);
      }

      m_data.clear();
      iOffset = 15+(m_iMaxSamples*2);
      ucXmtdat[iOffset] = 0xCA;

      bool bSuccess = m_objComm.WriteCommPort(ucXmtdat, 60);
    }
  }
}


texts: Simple HttpClient usage for integration tests in .NET Core

texts:
I have this simple setup for a .NET Core project which is just a very basic HttpClient usage to do some simple integration tests to a RESTful API. For now the test project remains separated from the main API project, that's why it's built on .NET Core for now, using NUnit as test framework as well. But because of that I have the freedom to change it anytime.

For now, the implementation is very simple, like this:

public static HttpClient _client1;
public static HttpClient _client2;

[OneTimeSetUp]
public void OneTimeSetUp()
{
    _client1 = new HttpClient {BaseAddress = new Uri("https://address1.com")};
    _client1.DefaultRequestHeaders.Add("API-KEY", "token_here");

    _client2 = new HttpClient {BaseAddress = new Uri("https://address2.com")};
    _client1.DefaultRequestHeaders.Add("API-KEY", "token_here");
}

//[OneTimeTearDown]
//public void OneTimeTearDown()
//{
    //_client1?.Dispose();
    //_client2?.Dispose();
//}

That's the main test class, but considering that later it will become a more robust test suite and it's going to be added on main project, I've found that I can use HttpClientFactory like this, which produces the same test results and I can modelate the services to be added to the API solution later.

public static HttpClient _client1;
public static HttpClient _client2;

[OneTimeSetUp]
public void OneTimeSetUp()
{
    var services = new ServiceCollection();

    services.AddHttpClient("Client1", client =>
    {
        client.BaseAddress = new Uri("https://address1.com/");
        client.DefaultRequestHeaders.Add("KEY", "token_here");
    });

    services.AddHttpClient("Client2", client =>
    {
        client.BaseAddress = new Uri("https://address2.com/");
        client.DefaultRequestHeaders.Add("KEY", "token_here");
    });

    var factory = services.BuildServiceProvider().GetService<IHttpClientFactory>();

    _client1 = factory.CreateClient("Client1");
    _client2 = factory.CreateClient("Client2");
}

//[OneTimeTearDown]
//public void OneTimeTearDown()
//{
    //_client1?.Dispose();
    //_client2?.Dispose();
//}

My main problem is that we have two main API addresses that will be used under production environment and I'm not sure if this implementation is appropriated. Everything works as expected on both scenarios when called on tests...

[TestFixture, Parallelizable(ParallelScope.All)]
public class TestCase : Setup
{
    [Test]
    public async Task Get()
    {
        var response = await _client1.GetAsync("v1/Endpoint");
            response.EnsureSuccessStatusCode();
        var result = await response.Content.ReadAsStringAsync();

        Assert.NotNull(response);
        Console.WriteLine(JToken.Parse(result));
    }
}

So it will be the same for _client2 and in a lot of tests...

As I said, it works as expected on both ways, but since I'm new at this and didn't found much about this kind of integration test separated from the main API reference project, I'm not so sure about how I built it, so any other and more experienced views about it will be very much appreciated.

EDIT: I had the need to run all the tests in parallel, so I was generating an ObjectDisposedException with the Parallelizable attribute. Removing the OneTimeTearDown with the client disposing calls solved the problem, but I have doubts if that's the correct way to use HttpClient as well, as it still gives the expected results.


texts: Add method to Ruby's Enumerable module that produces every nth element

texts:
The task is to enhance the Enumerable module with a method nth().

The method shall create a new list, which contains every nth-element of the object, when it is invoked.

For example: [2, 4, 6, 8, 10, 12].nth(2) shall return [4, 8, 12]

Here's my implementation:

module Enumerable
  def nth(n)
    i = 0
    ordinal = 1
    relevant_iteration = n * ordinal

    self.select do | num |
        i += 1

        if i == relevant_iteration
          ordinal += 1
          relevant_iteration = ordinal * n

          num
        end
    end
  end
end

print [2, 4, 6, 8, 10, 12].nth(2) # => [4, 8, 12]
print "\n"
print (4..12).nth(3)  # => [6, 9, 12]

It works as expected and it has passed the unit-tests.

But: My solution isn't elegant. At least that's my own impression.

Could my code be improved in regard to more compactness?
Is my code readable and understandable?
What could be improved?


texts: Dynamically set angular directive template

texts:
I have recently upgraded to AngularJS 1.5 and as the title says, I want to use different templates depending on a value in the item object passed.

After some research I found multiple ways to accomplish my task and I have picked out two of the (many) ways I found. Since I'm still quite new at Angular I was curious about the best way to do it performance wise.

1st way

angular.module('MyModule').directive('myDirective',
  ['$templateRequest', '$compile', function ($templateRequest, $compile) {
    return {
        restrict: 'EA',
        replace: true,
        scope: {
            item: '='
        },
        link: function (scope, element, attr) {
            if (scope.item.component != null) {
                scope.template = 'js/MyModule/directives/my-directive/my-component.html';
            } else if (scope.item.question != null) {
                scope.template = 'js/MyModule/directives/my-directive/my-question.html';
            }

            $templateRequest(scope.template)
                .then(function(html){
                    var template = angular.element(html);
                    element.append(template);
                    $compile(template)(scope);
                });
        }
    };
}]);

2nd way

angular.module('Testview').directive('learningPlayerBody', function () {
    return {
        restrict: 'EA',
        replace: true,
        template: '

',
        scope: {
            item: '='
        },
        link: function (scope, element, attr) {
            scope.getTemplateUrl = function() {
                if (scope.item.component != null) {
                    scope.template = 'js/MyModule/directives/my-directive/my-component.html';
                } else if (scope.item.question != null) {
                    scope.template = 'js/MyModule/directives/my-directive/my-question.html';
                }
            };
        }
    };
});


texts: Using Guava to reduce code complexity (and possibiliy to improve readability) of null check and assign default value

texts:
Below is my java code with some complexity,

String input;
double a;

if (null != input && !input.isEmpty()) {
    a = Double.parseDouble(input);
} else {
    a = defaultValue;
}

With Guava, we can compress the code from 5 lines into a 'single' line,

a = Double.parseDouble(
        Objects.firstNonNull(Strings.emptyToNull(input), defaultValue)
    );

The complexity is reduced but readability is getting worst. Any comment on improving readability at the same time reducing complexity?