Login system using bcrypt and MySQL, to be used for any future projects Main function will ask what the user wants to do. LoginSystem class will handle the sign up and login process as well with the checking if password is right. passwordHashing will use bcrpyt to salt and hash the password.
import bcrypt
from loginDbMySQL import insert, logging_in

def main():

    login_instance = LoginSystem()
    check = True

    while check == True:
        value = input("1-Login, 2-Sign-up, 3-Exit\n")
        if value == "1":
            login_instance.login()
            check = True
        elif value == "2":
            login_instance.sign_up()
            check = True
        elif value == "3":
            check = False

class LoginSystem():

    def sign_up(self):
        username = input("Enter a username: ")
        password = input("Enter a password: ")

        password_hash = self.passwordHashing(password)
        insert(username, password_hash)

    def login(self):
        username = input("Enter a username: ")
        password = input("Enter a password: ")

        password_hash = logging_in(username)
        self.comparePassword(password, password_hash)

    def passwordHashing(self, password):

        password_bytes = password.encode('utf8')

        salt = bcrypt.gensalt(14)

        password_hash_byte = bcrypt.hashpw(password_bytes, salt)

        password_hash_str = password_hash_byte.decode()

        return password_hash_str

    def comparePassword(self,password,password_hash):

        if bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8')):
            print("Welcome")
        else:
            print("Incorrect Information")

if __name__ == "__main__":
    main()

loginDbMySQL handles the database insertion, checking, and query's
import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="*******",
    database="*******"
)

mycursor = mydb.cursor()

def insert(username,password_hash):

    mycursor = mydb.cursor(buffered=True)
    select_query = "SELECT usernames FROM login_table WHERE usernames= %s"
    mycursor.execute(select_query, (username,))
    check = mycursor.fetchone()

    if check == None:
        mycursor.execute("INSERT INTO login_table (usernames, password_hashs) VALUES (%s,%s)", (username, password_hash))
        mydb.commit()
        print("Account created!")

    else:
        print("Account already exist.")

def logging_in(username):

    mycursor = mydb.cursor(buffered=True)
    select_query = "SELECT * FROM login_table WHERE usernames= %s"
    mycursor.execute(select_query, (username,))
    check = mycursor.fetchone()

    if check == None:
        print("Incorrect information.")
    else:
        return check[1]

Let's start with the SQL and your loginDbMySQL stuff first.
You should probably reconsider the naming of your SQL table columns.
Bare minimum reproducible example with a table that has automatic incrementation, a UID as the primary key, and the username field 'username' and 'passwd_hash'.  You should name colums to be descriptive of the value per record, not as plurals unless you are storing multiple items for each field in the record.
So, let's make the table accordingly, and also have a unique constraint on usernames - you don't want duplicate usernames.  The username also becomes the primary key since we want unique usernames:
create or replace table login_tests.login_table
(
    uname varchar(50) not null,
    passwd_hash varchar(1000) not null
);

alter table login_tests.login_table
    add primary key (uname);

Note we're using uname as the primary key, so you can only have unique usernames.  This is entirely permitted in SQL.
SQL query mechanisms being used are NOT SQL-Injection-Safe!
Next, let's look at one of the glaring problems in your code:  your queries and routines are not injection-safe!  I can easily pass a value in that can escape the 'argument' being called and simply cause chaos with SQL injections.  The way around this is to build predetermined procedures in the DB and call that, and then pass the arguments in with callproc calls.
To start with, you have three separate queries - one to determine if a user exists, one to insert a user, and then a similar select query for logging in.  But, we can use the same SELECT for the same task!  Saves us code!
Also, you aren't really using SELECT functions for anything other than checking if a username exists on insert (fixed later), and getting hashed pw data for a given username.
Firstly, on the MySQL side we need to create the functions.
CREATE PROCEDURE GetPWHash(username varchar(50))
BEGIN
    SELECT passwd_hash FROM login_table WHERE uname = username;
END;

CREATE PROCEDURE GetUserData(username varchar(50))
BEGIN
    SELECT * FROM login_table WHERE uname = username:
END;

CREATE PROCEDURE AddUser(username varchar(50), pass_hash varchar(1000))
BEGIN
   INSERT INTO login_table(uname, passwd_hash) VALUES (username, pass_hash);
   COMMIT;
END;

We'll then call the relevant procedures with a cursor.callproc(ProcedureName, [argument]) call instead.  It's not considered smart to build your queries in strings because it is typically extremely unlikely you will be able to properly escape the queries.  The callproc function will automatically escape them before passing them to the function.
You'll see me replace your functions accordingly as we go and edit each function and call.  So let's begin with those.
INSERT function doesn't need a select to check if the user exists - DB insert will simply fail if a user exists because of PrimaryKey restrictions.
You're doing testing here with an extra DB call which requires more disk I/O for reading.
So let's simply rewrite your insert function entirely.  It's not really pythonic in its current state, and you make an unnecessary extra DB call.
Further, you should consider a DB cursor for each one, without global declarations.  So I'll provide you some revisions.
Let's start with your insert function:
def insert(username, password_hash):
    cursor = mydb.cursor(buffered=True)
    cursor.callproc('AddUser', [username, password_hash])
    cursor.close()

We should not access the 'username' ahead of time, we can simply catch the error (the callproc function throws a mysql.connector.errors.IntegrityError class error when we violate a constraint).  No need to check if the user exists already, and as I included earlier I wrote a COMMIT into the AddUser function.  No need to make the db commit as a result, it commits after it adds!  (Actually confirmed this checking the DB after the callproc!)
Logging In Function: Use callproc!
Again, we should be using callproc and such so you eliminate an SQL Injection risk.  Further, your 'logging in' function in loginDbMySQL is... not really 'logging in'.  It's more fetching user data, so let's name it accordingly.
def logging_in(username):

    mycursor = mydb.cursor(buffered=True)
    mycursor.callproc('GetUserData', [username])
    select_query = "SELECT * FROM login_table WHERE usernames= %s"
    data = mycursor.fetchone()
    # INCOMPLETE FUNCTION

But because this is an incomplete function that does nothing, I essentially suggest removing it.
And in its place put a useful function - getUserPWHash - which will call the SQL and only return the PW hash for the specified user (if it exists).
def getUserPWHash(username):
    mycursor = mydb.cursor(buffered=True)
    mycursor.callproc('GetPWHash', [username])
    data = mycursor.fetchone()
    return data

This will be useful later, as you will see when we dig into your other code.

So, taking into account the SQL bits, we have a bunch of code tweaks on the flipside in your login.py script.
Let's start with your LogInSystem class.
Code Duplication - can be reduced by adding a staticmethod for prompting for credentials
You have two cases where you would benefit from a separate function from which you can request credentials.  Registration, and logging in.  Let's start by adding a new method to your class for this - called promptForCreds.  This is going to have a special decorator - @staticmethod - this tells the system that this function is able to stand on its own and does NOT require a dependency on the object itself (self) in the declaration of the method:
@staticmethod
def promptForCreds():
    username = input("Enter a username: ")
    password = input("Enter a password: ")

    return username, password

This will eventually be used here in your sign up and login functions.  We'll apply this in a later revision suggestion.
Reduce the need of multiple variables - like in the SQL sections.
So you end up having a bunch of one-time-use variables in passwordHashing, like you did in the SQL bits.
We can simply replace the use of variables to hold values by directly putting the variables in line.  If we name the items accordingly, we don't need additional variables to hold them, since it's clear what the objects are (they're already arguments passed into functions!)
Oh, and the passwordHashing method can also be a @staticmethod object too - it doesn't depend on any other components within your class specifically.
@staticmethod
def passwordHashing(password):
    return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(14)).decode('utf-8')

This looks long but it can be broken across multiple lines if you keep the parenteses around the bcrypt.hashpw call.  But, this reduces those one-use variables AND puts everything into a simple return call - and only one of them.  No extra variables!
Another static method - comparePassword
This one's a minor change and pretty simple - just add a decorator ahead of comparePassword.
@staticmethod
def comparePassword(password, password_hash):
    if bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8')):
        print("Welcome")
    else:
        print("Incorrect Information")

Remove code duplication in sign_up and login.
And now here's why i created that new method - we get to take four lines of code and condense it into two.  This code is duplicated, yes, but we don't have to run the prompt twice individually.
def sign_up(self):
    username, password = self.promptForCreds()
    insert(username, self.passwordHashing(password))

def login(self):
    username, password = self.promptForCreds()
    password_hash = getUserPWHash(username)
    self.comparePassword(password, password_hash)

See what I did here?  Username and password are obtained by the other function and then returned.  Saves us from having to create the prompt twice!  See what niceness I did there?
So your LoginSystem class becomes this:
class LoginSystem:
    @staticmethod
    def promptForCreds():
        username = input("Enter a username: ")
        password = input("Enter a password: ")
        return username, password

    @staticmethod
    def passwordHashing(password):
        return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(14)).decode('utf-8')

    @staticmethod
    def comparePassword(password, password_hash):
        if bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8')):
            print("Welcome")
        else:
            print("Incorrect Information")

    def sign_up(self):
        username, password = self.promptForCreds
        insert(username, self.passwordHashing(password))

    def login(self):
        username, password = self.promptForCreds
        password_hash = getUserPWHash(username)
        self.comparePassword(password, password_hash)

Now, let's look at your main() function.
Non-pythonic way of iterating over the checks!
You're doing something I wouldn't do here, which is using while var == True.  Pythonically, you can reduce this to this:  just do while var: for iterating while a variable is True.  However, I suggest you do something else, which (once again) reduces the memory usage by not needing to define a variable.
def main():
    login_instance = LoginSystem()

    while True:
        value = input("1-Login, 2-Sign-up, 3-Exit\n")
        if value == "1":
            login_instance.login()
        elif value == "2":
            login_instance.sign_up()
        elif value == "3":
            pass  # Do nothing, we'll just exit as normal.
        else:
            continue  # Continue prompting until we get a valid value.

        break

This reduces the complexity and need to assign True or False.  Just iterate infinitely and break on any value that is valid (1, 2, or 3), or keep going and prompting more until we get only one valid value.
You really should be triggering errors or returning Bools for your login functionality though.
The only problem with your approach is you have no way to catch whether a login was successful or not (or the same case with a registration).
You can approach this in one of two ways - either return errors on failures, or make your functions return a boolean instead of just printing statements.
I suggest you rename your comparePassword function to validateCredentials and then adjust it to return a True or False - True for valid credentials, False for invalid.  Or, just return the result of bcrypt.checkpw:
@staticmethod
def validateCredentials(password, password_hash):
    return bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8'))

Now, we'll use this for login functionality:
def login(self):
    username, password = self.promptForCreds
    password_hash = getUserPWHash(username)
    if self.validateCredentials(password, password_hash):
        print("Welcome!")
    else:
        print("Invalid Login")

Note that simply printing output is simple - you really should consider making this return a bool as well.  This way you can utilize the results.
So that would look like this:
def login(self):
    username, password = self.promptForCreds
    password_hash = getUserPWHash(username)
    return self.validateCredentials(password, password_hash)

This would then mean we have a revise later for when value is 1:
# ...
        if value == "1":
            if login_instance.login():
                print("Welcome!")
            else:
                print("Access denied")

Now, we have a similar case with insert but we're going to use error codes instead.
Back in loginDbMySQL way earlier in this review, I basically removed print statements and error checking from your insert function.  This was intentional, because we'll handle insert via error code data/returns.
So, in the conditional for when value is 2:
        elif value == "2":
            try:
                login_instance.sign_up()
                print("Sign up complete.")
            except mysql.connector.errors.IntegrityError:
                print("Unable to register account.")

This ultimately makes it a more usable login system function.  It requires a single import added though - mysql.connector.errors.  This is so we can import the error class for the exception handler.

The code with all my revisions:
login.py:
import bcrypt
import mysql.connector.errors
from loginDbMySQL import insert, getUserPWHash

class LoginSystem:
    @staticmethod
    def promptForCreds():
        username = input("Enter a username: ")
        password = input("Enter a password: ")
        return username, password

    @staticmethod
    def passwordHashing(password):
        return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(14)).decode('utf-8')

    @staticmethod
    def validateCredentials(password, password_hash):
        return bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8'))

    def sign_up(self):
        username, password = self.promptForCreds
        insert(username, self.passwordHashing(password))

    def login(self):
        username, password = self.promptForCreds
        password_hash = getUserPWHash(username)
        return self.validateCredentials(password, password_hash)

def main():
    login_instance = LoginSystem()

    while True:
        value = input("1-Login, 2-Sign-up, 3-Exit\n")
        if value == "1":
            if login_instance.login():
                print("Welcome!")
            else:
                print("Access denied")
        elif value == "2":
            try:
                login_instance.sign_up()
                print("Sign up complete.")
            except mysql.connector.errors.IntegrityError:
                print("Unable to register - username already taken.")
        elif value == "3":
            pass  # exit
        else:
            continue

        break

if __name__ == "__main__":
    main()

loginDbMySQL.py:
import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="*******",
    database="*******"
)

def insert(username, password_hash):
    mycursor = mydb.cursor(buffered=True)
    mycursor.execute("AddUser", [username, password_hash])
    mycursor.close()
    print("Account created!")

def getUserPWHash(username):
    mycursor = mydb.cursor(buffered=True)
    mycursor.callproc('GetPWHash', [username])
    data = mycursor.fetchone()
    return data
```


Router for personal use This is router I created for use, however, I wish to refactor this code and make this more robust. I would really appreciate anyone who can:

Point out how to make this code more robust, clean and flexible in terms of reusability where the user of this module can easily alter the configuration, etc to his/her needs without possibly altering the source code.
Point out where code can be refactored and possibly how.
Point out how the code could be made more efficient.

Point out places where I have breached any principles of OOP.

Implementation:

$router = new Router\Router();
/**
 * The arguments for the method createRoute:
 * First Argument - URI
 * Second Argument - Namespace or Classname of which the method will be executed.
 * Third Argument - The method to be run in the specified namespace/class in the second argument.
 */
$router->createRoute('/', 'PageController', 'showHome');
$result = $router->runRouter();

Source Code:

<?php
namespace Router;

class Router
{
    private $routes = array();
    private $patternForURIs = '/\{[a-zA-Z0-9]*\}/';

    public function createRoute($uri, $class, $method)
    {
        $result = $this->checkWhetherParametersAreRequired($uri);

        if($result != false) {
            $this->routes[] = [$uri, $class, $method, $result];
            return true;
        }

        $this->routes[] = [$uri, $class, $method];
        return true;
    }

    public function checkWhetherParametersAreRequired($uri)
    {
        if(preg_match_all($this->patternForURIs, $uri, $matches)) {
            return $matches[0];
        }
        return false;
    }

    public function runRouter()
    {
        $routesWhichExpectParameters = array();

        foreach($this->routes as $route) {
            if(isset($route[3])) {
                $routesWhichExpectParameters[] = $route;
            }
            if($route[0] === $_SERVER["REQUEST_URI"]) {
                return $route;
            }
        }

        foreach($routesWhichExpectParameters as $route) {
            $route[0] = ltrim($route[0], '/');
            $route[0] = explode('/', $route[0]);
            $partsToConfirm = count($route[0]);

            $requestURI = ltrim($_SERVER["REQUEST_URI"], '/');
            $requestURI = explode('/', $requestURI);
            $partsAvailable = count($requestURI);

            if($partsToConfirm != $partsAvailable) {
                continue;
            }

            $confirmedParts = 0;

            $numberOfParametersToDetect = count($route[3]);
            $numberOfParametersDetected = 0;
            $detectedParameters = array();

            for($iterator = 0; $iterator < $partsToConfirm; $iterator++) {
                if($route[0][$iterator] == $requestURI[$iterator]) {
                    $confirmedParts++;
                    continue;
                } else if(preg_match($this->patternForURIs, $route[0][$iterator])) {
                    $confirmedParts++;
                    $detectedParameters[] = array(
                        $route[3][$numberOfParametersDetected] => $requestURI[$iterator]
                    );

                    $numberOfParametersDetected++;
                    continue;
                }
            }

            if(($numberOfParametersDetected == $numberOfParametersToDetect) && ($partsToConfirm == $confirmedParts)) {
                $route[4] = $detectedParameters;
                return $route;
                break;
            }
        }
        return false;
    }
}

You need to decide on the Domain Objects that represent concepts in your current model.

A Route object should encapsulate the data to do with a route. If you look at Symfony's Route you'll see that it is simply an object with some properties, getters and setters, and that's about it (apart from a few select helper functions). This is also known as an Entity, the end object that you get back.

So, now you know that you want to get back some Route entities (@return Route[] in phpdoc), you should:

Create a Route object which merely represents a route
Take a look at the Factory Pattern and create a factory for these

The object API I would then expect to be using would be:

$router = new Router(new RouteFactory);
/** @var Route $route */
$route = $router->createRoute('/', 'PageController', 'showHome');

Somewhere in the Router, it would call RouteFactory::create($param1, $param2 ...) to actually make a Route object.

Don't expect the user to remember to call createRoute() followed by runRoute(). If one can't be run before the other, then it looks like you're trying to implement the builder creational pattern (which is for optional parameters). Your createRoute() method should return a Route object.

In the context of routing itself, you'll likely want something called a Resolver. That is, something you pass a Route to, and it instantiates the thing you are routing to. In an 'MVC' framework, you have a ControllerResolver - so you would create a Route, call ControllerResolver::resolve(Route $route) and that would contain the logic to decide what controller to create based on the contents of the Route object (so it'd do things like class_exists($controllerName) etc.

It looks like you're trying to design some generic router, but it is doing too many things. Focus on making the following seperately:

An object representing your route (Route)
An object responsible for creating a route from $_POST etc (RouteFactory::createFromGlobals($_POST) (or similar))
An object responsible for taking your Route and doing what you want to do with it (ControllerResolver (or similar))

Separate the actions out that you want to do, contextually, and you'll achieve better SoC.

Also, you shouldn't be accessing any superglobals ($_*) within this class, you should pass them in instead. This means that during testing you fake (or 'mock') the data you pass in with relative ease and test that your object still functions as you expect over different scenarios.


find longest common substring in space O(n) I am working on the class question find the longest common substring from 2 strings but I would like to return the longest common substring instead of just size of longest common substring.like

s1 = 'abcdex', s2 = 'xbcdey' => 'bcde'
s1 = 'abcxyx', s2 = 'xbcydey' => 'bc'

The way I do it is using dynamic programming to create a memo table and update each cell that required space \$O(n * m)\$. How can I implement the code so I can only using space as \$O(n)\$?

    def longestCommonSubstring(self, s1, s2):
        """
        :type s: str
        :rtype: str
        """
        m, n = len(s1), len(s2)
        dp = [[''] * (n + 1) for _ in range(m + 1)]
        max_len = ''
        for i, ic in enumerate(s1):
            for j, jc in enumerate(s2):
                dp[i][j] = dp[i - 1][j - 1] + ic if ic == jc else ''
                max_len = dp[i][j] if len(max_len) < len(dp[i][j]) else max_len
        return max_len

PEP 8

You are following most of the PEP 8 style guidelines.  One that you are breaking is method names should be snake_case; your function should be named longest_common_substring.

Tricky Code

Your dp matrix is properly allocated to the size m+1 by n+1.

When you index your matrix, you access [i-1][j-1] with \$0 \le i \lt m\$ and \$0 \le j \lt n\$.  This means you never access the last allocated row m or the last allocated column n, but instead rely on accessing the -1 row and the -1 column wrapping around to reach these "unused" spaces.  This is "surprising" code at best, and "crashing" code if translated to a different programming language.

It would be better to add one to the indices used to index the dp matrix.  The simplest way would be to start the i and j enumerations at one:

    for i, ic in enumerate(s1, 1):
        for j, jc in enumerate(s2, 1):

Useless else

Expand out this ... if ... else ... statement:

            max_len = dp[i][j] if len(max_len) < len(dp[i][j]) else max_len

Initially, this produces:

            if len(max_len) < len(dp[i][j]):
                max_len = dp[i][j]
            else:
                max_len = max_len

But we can immediately see the else: clause is a no-op, and can be removed:

            if len(max_len) < len(dp[i][j]):
                max_len = dp[i][j]

Which reads much more clearly than the original.

From \$O(n m)\$ to \$O(n)\$ space

During the first iteration of outer loop, you only access rows -1 and 0.  During the second iteration of outer loop, you only access rows 0 and 1.  During the third iteration of outer loop, you only access rows 1 and 2.  Etc.  You only need two rows of the dp matrix!

More over, you create the 0 row from the -1 row, you create the 1 from the 0 row, you create the 2 row from the 1 row, and so on.

Do you really need to keep the dp matrix?  Or could you use a previous_row and a current_row?  Only storing two length n rows reduces your space to \$O(2n)\$, which is simply \$O(n)\$.


Class that calls initiates the validation of itself and then initiates the assignment of offers Please see the code below:

public class Customer
{
    public int _iD { get; set; }
    public decimal _salary { get; set; }
    public List<String>_assignedOffers { get; set;  }
    private AbstractValidator<Customer> _validator;
    private IRulesOfferCalculator _rulesOfferCalculator;

    public Customer(AbstractValidator<Customer> validator, IRulesOfferCalculator rulesOfferCalculator)
    {
        _validator = validator;
        _rulesOfferCalculator = rulesOfferCalculator;
    }

    public void AssignOffers()
    {
        ValidationResult results = _validator.Validate(this);
        if (results.IsValid)
        {
            _assignedOffers = _rulesOfferCalculator.CalculateOffers(this);
        }
        else
        {
            _validator.ValidateAndThrow(this);
        }
    }
}

It is a Domain Layer class in a rich domain model.  I have used FluentValidation for the validation. The Service Layer (WFC) creates an instance of Customer and initialises it.

The concern I have is that the class has two responsibilities:

Validate the customer.  If validation fails then thrown an exception.  Validation can fail if the customer is under 21 years old etc
If validation fails then throw an exception with reason for failure in the exception string.  If validation is successful then assign offers (_assignedOffers  is an instance variable)

I have two questions:

Is it bad practice to throw an exception if validation fails? Is there a better way to notify the user if validation fails?
Does this class have too many responsibilities i.e.

validate and
assign offers.

Alternatively the Service Layer could call: Validate and then call AssignOffers if Validate is successful.  However, I believe this would make the domain model anemic.

Please be aware that I am building a rich domain model.

Is it bad practice to throw an exception if validation fails? Is there a better way to notify the user if validation fails?

It depends but usually validations return some kind of a validation result.

  Does this class have too many responsibilities i.e. validate and assign offers.

Actually not. They are not the responsibilities of this class. Validation is injected and provided via a service so it's fine.

I would worry more about its design.

The constructor requries two parameters but their corresponding properties are not readonly so you could just use them. More appropriate would to use fields or make the properties get only and private.

public void AssignOffers()
{
    ValidationResult results = _validator.Validate(this);
    if (results.IsValid)
    {
        _assignedOffers = _rulesOfferCalculator.CalculateOffers(this);
    }
    else
    {
        _validator.ValidateAndThrow(this);
    }
}

It's a weird process. It first validates the object and then calculate the offer. The Offer property should be a getter-only property and use the calculator to get the value and the validation should take place where the other properties necessary for the calculation are set because they need to be validated as apparently they can be invalid.


Recognizing number representation (and convert to decimal) from the base prefixes Here is what appears to be a fairly easy problem:

  Write a program that prompts the user to enter several integers in any
  combination of octal, decimal, or hexadecimal, using the 0 and
  0x base prefixes; interprets the numbers correctly; and converts
  them to decimal form. Then your program should output the values in
  properly spaced columns like this:

0x4    hexadecimal    converts to     4      decimal
0123   octal          converts to     83      decimal
65     decimal        converts to     65      decimal

Here is a first (working) draft:

const string info ("This program recognizes multiple base prefixed numbers  dec:none, hex:0x, oct:0\nand converts them into decimals.\n");
const string prompt ("Please enter numbers with random base prefixes.\n>>");

const char octprefix ('0');
const char hexprefixLower ('x');
const char hexprefixUpper ('X');
const int inputLoop = 2;

int main(){
try{
    cout << info;

    string num;
    vector<string> inputNumbers;

    int numDecimals(0);
    vector <int> inputDecimals;

    for (int i=0; i < inputLoop; i++){
        // get number with prefix
        cout << prompt;
        cin >> num;
        inputNumbers.push_back(num);

        // return number (# of characters) back to cin stream for reinterpretation
        for (int i=0; i < num.length(); i++) cin.unget();

        // unset default flags so that prefixes are considered
        // and numbers with different bases converted directly to decimals
        cin.unsetf(ios::dec | ios::oct | ios::hex);
        cin >> numDecimals;
        inputDecimals.push_back(numDecimals);
    }

    // discern base from prefix
    // checks first two characters of every vector element to determine base prefix
    for (int i=0; i < inputNumbers.size(); i++){
        if (inputNumbers[i][0] != octprefix){
            cout << inputNumbers[i] <<" decimal "<<" converts to "<< inputDecimals[i]  <<" decimal\n";
        }
        if (inputNumbers[1][0] == octprefix && (inputNumbers[1][1] != hexprefixLower && inputNumbers[1][1] != hexprefixUpper)){
                cout << inputNumbers[i] <<" octal "<<" converts to " << inputDecimals[i] <<" decimal\n";
        }
        if (inputNumbers[1][0] == octprefix && (inputNumbers[i][1] == hexprefixLower || inputNumbers[i][1] == hexprefixUpper)){
                cout << inputNumbers[i] <<" hexadecimal "<<" converts to " << inputDecimals[i] <<" decimal\n";
        }
    }

}catch(exception& e){
    cerr << e.what() << endl;
    getchar();
}

getchar();
getchar();
return 0;
}

Are there any existent, unknown to me, language facilities that can be used to convert string to number that contains base prefix (0x, 0, i.e. numbers like: 020, 0x16, etc); facilities that recognize number base representation?

I'm trying to make it look more modular and separate it in different functions with a single task (read input, prefix recognition algorithm, print result), any ideas are welcome!

I see a number of things which may help you improve your code.

Be aware of what the standard doesn't say

Your use of unget() is not portable and will not work reliably.  The standard does not guarantee that an infinite number of characters will be buffered, and that's if the stream is buffered at all.  See this question for more details.

Use standard library functions where available

There is already a function std::stoi() which does the conversion you seek.  That is, it converts a std::string into an integer, applying the base conversions as specified.

Create functions to clarify your code

One thing that the code must do is to identify which base is specified by the source string.  Since what you need is a string identifying the base, such as "hexadecimal", given an input number as a string, we can write something simple like this:

const std::string& baseid(const std::string& str)
{
    static const std::string bases[]{
        "decimal", "octal", "hexadecimal"
    };
    enum baseid { DEC, OCT, HEX };
    if ((str.length() < 2) || (str[0] != '0'))
        return bases[DEC];
    return str[1] == 'x' ? bases[HEX] : bases[OCT];
}

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  Know when to use it and when not to (as when writing include headers).

Eliminate return 0 at the end of main

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.

Don't wrap entire programs in a try clause

Rather than take the lazy way out and have a single massive block of code within the try clause, it's generally better to isolate specific things that might fail and deal with them individually and intelligently.  If you're not going to do anything useful with the output, it's probably better not to even have a try ... catch construct.

Use the appropriate #includes

This code uses a number of things that are in specific #include files but the code (as posted) does not show them.  Generally, reviewers have an easier time if you post an entire compilable program instead of just a non-compilable extract.

An alternative approach

Using the baseid function shown above, here's a much simpler program to accomplish this this:

numbase.cpp

#include <iostream>
#include <string>
#include <vector>

const std::string& baseid(const std::string& str)
{
    static const std::string bases[]{
        "decimal", "octal", "hexadecimal"
    };
    enum baseid { DEC, OCT, HEX };
    if ((str.length() < 2) || (str[0] != '0'))
        return bases[DEC];
    return str[1] == 'x' ? bases[HEX] : bases[OCT];
}

int main(){
    const std::string info ("This program recognizes multiple base prefixed numbers  dec:none, hex:0, oct:0x\nand converts them into decimals.\n");
    std::cout << info;
    std::string num;
    std::vector<std::string> inputNumbers;

    while (std::cin >> num)
        inputNumbers.push_back(num);
    for (const auto &n : inputNumbers)
        std::cout << n << " " << baseid(n) <<" converts to "
                << stoi(n,0,0) <<" decimal\n";
}


Node.JS Automatic Poem Generator As a simple programming exercise, I wrote a piece of Node.JS code which generates random poems. It is based on a list of articles (kind of), nouns, linking verbs, and adjectives. It then combines them into lines, and eventually stanzas.

var articles = "The,All of the,Most of the,Some of the,My,Your,His,Her,Their,Our,Everybody's,Almost all of the,That,I knew that the,We knew that the,She knew that the,He knew that the,They knew that the".split(",");
var nouns = "darkness,morning,light,feeling,beauty,love,hatred,expression,message,happiness,sadness,anger,frustration".split(",");
var lv = "was,had been.will be,could be,might be,should have been,would have been,could have been".split(",");
var adjectives = "abstract,mysterious,permanent,unfortunate,intricate,confusing,true,false,fake,a lie,a stranger,a friend,serene,confusing,an enemy,terrible,enchanting,mine,yours,his,hers,theirs,ours,fortunate,understood,mine,interesting,mutual,artistic,musical".split(",");
var x;

var ta = articles[Math.floor(Math.random() * articles.length)];
var tb = nouns[Math.floor(Math.random() * nouns.length)];
var final = ta + " " + tb + "\nby Julian Lachniet\n------------------\n"

for (x = 0; x < 16; x++) {
  var a = articles[Math.floor(Math.random() * articles.length)];
  var b = nouns[Math.floor(Math.random() * nouns.length)];
  var c = lv[Math.floor(Math.random() * lv.length)];
  var d = adjectives[Math.floor(Math.random() * adjectives.length)];
  final += a + " " + b + " " + c + " " + d + ".\n";
  if (x % 4 == 3) {
    final += "\n";
  }
}

cr = new Date
final += "(c) " + cr.getFullYear();

console.log(final);

The poems are really quite silly, but any individual line out of context might seem normal.

He knew that the darkness
by Julian Lachniet
------------------
They knew that the darkness was mutual.
All of the sadness would have been serene.
Most of the feeling could have been artistic.
We knew that the sadness was intricate.

We knew that the feeling could be mine.
Your light had been.will be a lie.
They knew that the beauty would have been understood.
Their love would have been intricate.

They knew that the happiness should have been mine.
His frustration should have been mysterious.
Some of the darkness should have been musical.
That message might be unfortunate.

Your light might be enchanting.
Everybody's hatred should have been enchanting.
His expression could be interesting.
Their hatred would have been mine.

(c) 2017

I have several issues with my code already, which I don't really know how to change:

What is a better way to name the "dictionary" arrays (articles, nouns, lv, adjectives)?
Is there a more effective way to represent arrays than CSVs? I decided against using a standard array due to how much space it takes up.

Any tips/pointers would be appreciated.

I am not well versed in coding node.js as I'd like to be (I can read and debug, but learning to program in it is still ongoing) and I did not see anything that said I could not present an answer using a compatible language, so I converted your code into SmartBASIC.

If you were expecting node.js code, I will understand. I needed a quick way to show you several areas where you can improve on your own program, and suggestions that will smarten your program's AI. For yes, SIRI seems to be human like, it is not perfect. And it is harder to have a computer write something in one of the arts, whether a poem, lyrics or even a short story.

I did notice one slight error. In the statement below, you have a period instead of a comma, which will get you strange errors (had been.will be):

var lv = "was,had been.will be,could be,might be,should have been,would have ...

I experimented with several ideas, and several show promise. I incorporated them in my SmartBASIC program, which I commented thoroughly.

Your dictionary is limited, but I found out that this is not always a bad thing. I experimented with nouns, verbs, adjectives and articles where I created several hundred in each, and while it was still hit or miss, it was more miss than yours hit. Quantity does not always equate to quality.

One of the problems I noticed is when you want to use a color. Rarely does a color stand alone, nor does it always work with every word. A "white beard" is fine, but what is a "white crash?"

But a white crash can be poetic if the theme is right. That later.

So with colors, I created in my table colors with modifier tags. These are color words with a tag at the end so the program knows that another word is needed after a color word is used.

Here is a sample DATA statement that you should be able to convert to a "VAR[" Table:

DATA "*beard","fool","white*","black*","green*","blue*","yellow*","red*","light beams","*river","*garment","*ship","*snake","*snakes","*sails","voice+","ship+","ocean blue"

What you want to look at are the words with an "" in front of or at the end. The "" is my token that color is involved, and a modifier is needed.

If the "" is before the word, then I need to add a color before it. If the "" is after the word, then it is a color word and it needs a modifier.

I also created a table of colors only for the times I need to add a color to the front of a word. The word can be a noun or a verb. "White lightning," depending on how it is used, can be a noun or a verb. If you said "White lighning struck a tree," it is a noun. "Dear ole Fred, lay dead, when met by white lightning" could be considered a verb/adverb use.

The second thing is the "+" modifier. In the same DATA statement, the word "voice+" means it needs a modifier after it. I created a specific table for this type of modifier.

You will see in my code that since I used a random generator to start either with an article or verb, every word is in or converted to lowercase. I had to create another modifier, "@" that is placed in front of proper nouns or words that must be capitalized, no matter where in the sentence they appear. @moon and @sun are two examples in my DATA statements.

The third thing that shows promise is to create files that you can read into your VAR tables, but with a twist. I am currently creating theme-based poems. So I created files with words that are used in a particular theme.

For example, "hope" is one of the themes I am developing, so I am using everything from other poets to a thesaurus to even the Bible to gather as many words, Articles, Nouns, Verbs, Adjectives, and Modifiers that fit the theme of "hope" along with some generic words that would work.

This is where you asked if it would be better to have .CSV instead of tables. It will add flexibility to what your computer program writes about. You would have a VAR table with just themes, and .CSV file names for each theme that holds your vocabulary for that theme. You would first randomly pick a theme, load your tables, then can randomly pick your words.

By moving your tables out to .CSV files, you allow for many different types of dictionaries. And you can even get as complex as having a main theme and a sub-theme and load the appropriate dictionaries.

Another improvement I demonstrated in my code is that sentence structure does not always have to be article-noun-verb-adjective. It doesn't even have to always be subject-noun-verb or noun-verb-subject. Try starting one of your lines with a verb instead of an article. Then you can use verb-noun-subject or even article-verb-noun-adjective.

For example, "Stepping on Mike's foot felt great" shows how a verb can start a sentence.

I mentioned subject. For now, you can use nouns, but you may want to eventually create another table with just items that are considered "subjects." "Science" is a subject. "A Dear John letter" can be a subject rather than a noun. A "Divorce" can also be a subject.

I tried to keep to the same logic you used, but I wrote as vanilla a BASIC program as I possibly could so those with other dialects need to change very little. Like statement separator (!) or some of the statements for lower and upper-case. With minimal changes, I had this working in techBASIC.

But Javascript, being a C-based language, there are enough similarities to BASIC that you should have no problems adapting the routines in my code below into your program.

Not a plug, but incase there are those who never heard of SmartBASIC, it is an app (less than $5 in iTunes) that runs a pretty robust BASIC dialect on iPad and iPhones, and comes with the ability to create Xcode apps for distribution on iTunes. You also do not need access to the internet to run and test your programs.

This code works when run in SmartBASIC and is not broken code.

Here is it with the changes I made (commented):

/*
Poem Generator
By George McGinn (Poems by SmartBASIC)

Program uses very little AI in the beginning as once I have all the
word pieces in place, the AI will then determine if a word needs a
qualifier before or after it.

As this program grows, so will its AI, and the next phase will have it
learning words, for example, if it chooses a "A" and the next word
begins with a vowel, it will correct the "a" to an "an", thus its start
of learning grammar.

UPGRADES/BUG FIXES:
v1.0 - March 1, 2017
    Translation from simple NODE.js program
    Initial logic with limited vocabulary

v1.5 - March 4, 2017 (Minor upgrade - only because this was also v1 updates)
    Improved vocabulary by adding:
       17+ Articles
       31+ Nouns/Subjects
       35+ Verbs/Adverbs
       15+ Adjectives
       28+ Color Modifiers (new)
    Randomize start (Article or Verb)
    Improved AI to now include:
       – Capitalization at start of line
       – Created word capitalization modifier tag
       – Added Color Table for words needing a color before it
       – Added additional word and new color modifier table
       – Added Noun modifier table for before and after tagged noun
    The AI can now do rudimentary word enhancement by addind modifiers
    from specialized tables, including colors and added nouns, verbs,
    and adjectives before or after a noun. It is capable of recognizing
    words that require capitalization. However, the title still does
    not work right
*/

OPTION BASE 1
RANDOMIZE

REM Initialize variables/arrays (comments to prevent confusion)

x=0                                            REM Index to poem length (# lines)
i=0                                            REM Index to loading Arrays
cr$=CHR$(10)                                   REM Add a Carriage-Return character
Author$ = "By George McGinn"                   REM Name of Programmer running code
DIM article$(35),noun$(60),verb$(46),adjective$(45)
DIM colormodifier$(28),colortable$(7),nounmodifiers$(14)

REM Load Arrays from Data Statements

GOSUB LoadWordArrays

REM Pick a 2-word title

ta$ = article$(RND (35)+1)
b$=LOWSTR$(noun$(RND(60)+1))
b1$=LOWSTR$(noun$(RND(60)+1))
IF LEFT$(b$,1)="@"  OR LEFT$(b1$,1)="@" THEN GOSUB CheckForCapitalization
IF RIGHT$(b$,1)="*" OR RIGHT$(b$,1)="+" THEN GOSUB CheckForModifierAfter
IF LEFT$(b$,1)="*"  OR LEFT$(b$,1)="+"  THEN GOSUB CheckForModifierBefore
tb$=b$

Title$ = ta$ & " " & tb$

REM Create the poem, 16 lines in 4 4-line stanzas

PRINT Title$
PRINT Author$
PRINT!PRINT

REM NOTE: b1 & c1 placeholders for future use as modifiers, or
REM       to initially use b1 & c1 as modifiers themselves.
FOR X=1 TO 16
    a$=LOWSTR$(article$(RND(35)+1))             REM Pick an Article
    b$=LOWSTR$(noun$(RND(60)+1))                REM Pick a primary noun
    b1$=LOWSTR$(noun$(RND(60)+1))               REM Pick a noun-color modifier
    c$=LOWSTR$(verb$(RND(46)+1))                REM Pick a primary verb
    c1$=LOWSTR$(verb$(RND(46)+1))               REM Pick a verb modifier
    d$=LOWSTR$(adjective$(RND(45)+1))           REM Pick an adjective
    bc$=LOWSTR$(colormodifier$(RND(28)+1))      REM Pick a modifier for a color
    color$=LOWSTR$(colortable$(RND(7)+1))       REM Pick a color as a modifier
    nounmod$=LOWSTR$(nounmodifiers$(RND(14)+1)) REM Pick a non-color noun modifier

REM Check for modifiers to nouns
    IF LEFT$(b$,1)="@"  OR LEFT$(b1$,1)="@" OR LEFT$(bc$,1)="@" THEN GOSUB CheckForCapitalization
    IF LEFT$(b$,1)="*"  OR LEFT$(b$,1)="+"  THEN GOSUB CheckForModifierBefore
    IF RIGHT$(b$,1)="*" OR RIGHT$(b$,1)="+" THEN GOSUB CheckForModifierAfter

 REM Capitalize the first word of each sentence or stanza (whether noun or verb)
REM r=whether or not the sentence will start with a verb or article
    r=RND(2)+1
    IF r=1 THEN
       z=LEN(a$)
       a$=CAPSTR$(LEFT$(a$,1)) & RIGHT$(a$,z-1)
       Line$=a$ & " " & b$ & " " & c$ & " " & d$
    ELSE
       z=LEN(c$)
       c$=CAPSTR$(LEFT$(c$,1)) & RIGHT$(c$,z-1)
       Line$=c$ & " " & b$ & " " & d$
    ENDIF
    IF X%4=0 THEN Line$=Line$ & "." & cr$
    PRINT Line$
NEXT X

endPROG:
   PRINT!PRINT!PRINT "© 2017 "&Author$&" (if it is good), All Rights Reserved"
   PRINT "Date/Time Stamp: "&CURRENT_MONTH ()&"/"&CURRENT_DATE ()&"/"&CURRENT_YEAR ()&" at "&CURRENT_HOUR()&":"&CURRENT_MINUTE()&":"&CURRENT_SECOND()
   END

REM FUNCTIONS, SUBROUTINES, LABELED DATA STATEMENTS
REM ***********************************************

LoadWordArrays:
REM ***********************************************
REM Load Arrays from Data Statements

REM Load Articles
    For i=1 TO 35!READ article$(i)!NEXT i
REM Load Nouns
    FOR i=1 TO 59!READ noun$(i)!NEXT i
REM Load Verbs
    FOR i=1 TO 46!READ verb$(i)!NEXT i
REM Load Adjectives
    FOR i=1 TO 45!READ adjective$(i)!NEXT i
REM Load Color Modifiers
    FOR i=1 TO 28!READ colormodifier$(i)!NEXT i
REM Load Color Table
    FOR i=1 to 7!READ colortable$(i)!NEXT i
REM Load Noun Modifiers
    FOR i=1 to 14!READ nounmodifiers$(i)!NEXT i
RETURN

CheckForCapitalization:
REM Check for modifiers (@=Capitalize Word)
IF LEFT$(b$,1)="@" THEN
   z=LEN(b$)
   b$=RIGHT$(b$,z-1)
   b$=CAPSTR$(LEFT$(b$,1)) & RIGHT$(b$,z-2)
ENDIF
IF LEFT$(b1$,1)="@" THEN
   z=LEN(b1$)
   b1$=RIGHT$(b1$,z-1)
   b1$=CAPSTR$(LEFT$(b1$,1)) & RIGHT$(b1$,z-2)
ENDIF
IF LEFT$(bc$,1)="@" THEN
   z=LEN(bc$)
   bc$=RIGHT$(bc$,z-1)
   bc$=CAPSTR$(LEFT$(bc$,1)) & RIGHT$(bc$,z-2)
ENDIF

RETURN

CheckForModifierBefore:
REM Check for modifiers Before

REM "*" the noun needs a color before it
IF LEFT$(b$,1)="*" THEN
   z=LEN(b$)
   b$=RIGHT$(b$,z-1)
   b$=color$ & " " & b$
ENDIF

REM "+" the noun needs another noun to follow it (selection from noun modifier)
IF RIGHT$(b$,1)="+" THEN
   z=LEN(b$)
   b$=LEFT$(b$,z-1)
   b$=nounmod$ & " " & b$
ENDIF

RETURN

CheckForModifierAfter:
REM Check for modifiers after

REM "*" the noun is a color only color-friendly nouns considered
IF RIGHT$(b$,1)="*" THEN
   z=LEN(b$)
   b$=LEFT$(b$,z-1)
   b$=b$ & " " & bc$
ENDIF

REM "+" the noun needs another noun to follow it (selection from noun modifier)
IF RIGHT$(b$,1)="+" THEN
   z=LEN(b$)
   b$=LEFT$(b$,z-1)
   b$=b$ & " " & nounmod$
ENDIF

RETURN

REM DATA Statements for Poem Generator

REM 35 Articles
articles:
DATA "The","All of the","Most of the","Some of the"
DATA "My","Your","His","Her","Their","Our","Everybody's","Almost all of the"
DATA "That","I knew that the","We knew that the","She knew that the","He knew that the","They knew that the","And the coming","Oh, the","A spring of","Beyond the","Within the","And the","Alone, alone,","I fear","I looked upon","A","But where the","Like","A still and","Alone","All alone, a","The moving","It is"

REM 60 Nouns
nouns:
DATA "darkness","morning","morning+","light","feeling","feeling+","beauty","love","hatred","happiness","sadness","anger","frustration","expression","message","ship","lips","mouth","voice","garment","saint","snake","snakes","water","fire","lead","dreams","air","ghost","sails","sleep","river","cloud","@moon","@sun","waters","life","stars","the stars","lightning","beams","beams+","*beard","fool","white*","black*","green*","blue*","yellow*","red*","light beams","*river","*garment","*ship","*snake","*snakes","*sails","voice+","ship+","ocean blue"

REM 46 Verbs (lv)
verbs:
DATA "was","had been","will be","could be","might be","should have been","would have been","could have been","drunk","drank","lite","heavy","blessed","glossy","velvet","flash","kind","coiled","swarm","swarmed","fire","pity","filled","fill","moved","wind","danced","steep","wide","steep and wide","thick","light","roar","loud","more loud","lightning","struck","fell","more horrible","horrible","awful","hit","huge","holds","long","surrounds"

REM 45 Adjectives
adjectives:
DATA "abstract","mysterious","permanent","unfortunate","was unfortunate"
DATA "intricate","confusing","serene","confusing"
DATA "true","false","fake","a lie"
DATA "a stranger","a friend","an enemy"
DATA "terrible","enchanting","is mine","was yours","is his","is hers","was theirs","was ours"
DATA "fortunate","was understood","mine","interesting","is mutual","with an artistic flair","was musical"
DATA "golden pond","glossy lake","blessed","moment","unaware","no","yes","sure"
DATA "like","dreams","between","inbetween","alone","than that"

REM 28 Color modifiers
colormodifiers:
DATA "morning","light","beauty","love","ship","lips","garment","knight","saint","snake","snakes","water","fire","ghost","sails","river","cloud","@moon","@sun","waters","stars","lightning","beams","beard","velvet","flash","grass","book"

REM 7 Color table entries
colortable:
DATA "red","yellow","blue","green","white","black","orange"

REM 14 Noun Modifier Table (Nouns, Verbs/Adverbs, Adjectives)
nounmodifier:
DATA "sunshine","light","glow","fog","of peace","of love","blue","great","unloved","sad","happy","loved","of light","of love"


Dissecting a Y-shaped list Problem statement:

  Two singly linked lists join at a common node, making a Y shape. It is guaranteed that the common tail does not loop back. Find the junction node. Linear time, constant space.

It is an exercise for my students; nothing competitive.

This is what's provided:

list.h

#ifndef LIST_H
#define LIST_H

#include <stddef.h>

typedef struct node_s node_t;

size_t list_size(node_t * head, node_t ** tail);
node_t * list_tail(node_t * head);
node_t * list_reverse(node_t * head);
node_t * list_nth_node_unguarded(node_t * head, size_t n);
#ifdef EXERCISE_TEST
void list_link_node(node_t * from, node_t * to);
node_t * create_silly_list(size_t n);
#endif
#endif

list.c

#include "list.h"
#include <stdlib.h>

struct node_s {
    node_t * next;
};

void list_link_node(node_t * from, node_t * to)
{
    from->next = to;
}

size_t list_size(node_t * head, node_t ** tail)
{
    node_t dummy = { .next = head };
    head = &dummy;

    size_t size = 0;

    while (head->next) {
        size++;
        head = head->next;
    }

    if (tail) {
        *tail = head;
    }

    return size;
}

node_t * list_tail(node_t * head)
{
    node_t dummy = { .next = head };
    head = &dummy;

    while (head->next) {
        head = head->next;
    }

    return head;
}

node_t * list_reverse(node_t * head)
{
    node_t * prev = NULL;

    while (head) {
        node_t * next = head->next;
        head->next = prev;
        prev = head;
        head = next;
    }

    return prev;
}

node_t * list_nth_node_unguarded(node_t * head, size_t n)
{
    while (n--) {
        head = head->next;
    }
    return head;
}

#ifdef EXERCISE_TEST
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>

node_t * find_junction(node_t *, node_t *);

node_t * create_silly_list(size_t n)
{
    node_t * head = calloc(n, sizeof(*head));
    for (size_t i = 1; i < n; ++i) {
        head[i - 1].next = &head[i];
    }
    return head;
}

bool test_excersize(size_t size1, size_t size2, size_t junction_index)
{
    node_t * head1 = create_silly_list(size1);
    node_t * head2 = create_silly_list(size2);
    node_t * tail2 = list_tail(head2);
    node_t * real_junction = list_nth_node_unguarded(head1, junction_index);
    list_link_node(tail2, real_junction);
    node_t * junction = find_junction(head1, head2);
    free(head1);
    free(head2);
    return junction == real_junction;
}

int main()
{
    printf("%d\n", test(10, 20, 5));
    printf("%d\n", test(10, 20, 0));
    return 0;
}
#endif

Makefile

CFLAGS += --std=c99 -g -DEXERCISE_TEST

SRC := list.c main.c junction.c
OBJ := $(SRC:%.c=%.o)
DEP := $(SRC:%.c=%.d)

main: $(OBJ)
    $(CC) -o $@ $^

%.o: %.c
    $(CC) -c $(CFLAGS) -o $@ $<

%.d: %.c
    $(CC) -c -MM -MT $(CFLAGS) -o $@ $<

-include $(DEP)

This is what is expected:

junction.c

#include "list.h"
#include <assert.h>

node_t * find_junction(node_t * head1, node_t * head2)
{
    node_t * tail1;
    node_t * tail2;

    size_t x1_plus_y = list_size(head1, &tail1);
    size_t x2_plus_y = list_size(head2, &tail2);

    assert (tail1 == tail2);

    list_reverse(head1);
    size_t x1_plus_x2 = list_size(head2, 0);
    list_reverse(tail1);

    size_t x1_minus_x2 = x1_plus_y - x2_plus_y;
    size_t x1 = (x1_plus_x2 + x1_minus_x2) / 2;

    return list_nth_node_unguarded(head1, x1);
}

Students are fluent in c; in fact, a given part is mostly understood.

Questions:

Am I doing something wrong? I am mostly concerned with overflows in x1_minus_x2 = x1_plus_y - x2_plus_y.
Is it a good exercise, or the algebra jumps out like Jack off the box?
At the first glance, size_t list_size(node_t * head, node_t ** tail); violates the SRP. Really it does not, because tail computation comes free of cost. Is it obvious, or should I emphasize on it?

Is it a good exercise, or the algebra jumps out like Jack off the box?

The algebra is fine. That size_t x1_minus_x2 = x1_plus_y - x2_plus_y line wouldn't be necessary (IMHO even reduces readability), but apart from that it's reasonable.

However, your solution is worse than it needs to be. It merely stays in-place, while the optimal solution to this problem can treat the input as read-only and limit the working-set to constant space.

Your solution also depends on list_reverse being implemented as in-place and manipulating the original list. Depending on such behavior is IMHO pretty bad design. In fact, if I hadn't checked the source of list_reverse, I would have expected it to return a reversed copy instead. Which would obviously break your solution.

I would expect that your students will mostly just reverse both lists, traverse in lockstep and identify the last common node that way. Students have a tendency to trade algebra for brute force, if possible.

Smarter students will just read the length of both lists, skip the length difference, and then walk in lockstep until they find the common element. Which then also would fit better within the space complexity requirements, and requires no manipulation of the lists.


Get item from database by ID and get all items from database I have 2 methods for getting data from the database (the data I get are both List of tuples with doubles and datetimes in it). I would like to know if it is possible to use one method for both queries.

How can I make this code DRY? In my opinion I'm defining 2 methods which clearly does nearly the same. How can I improve this? I've read some about predicates and delegates but I'm not sure how to apply them here.

 private IEnumerable<Tuple<double, DateTime>> GetCarHdopById(int id)
        {
            var tp = new List<Tuple<double, DateTime>>();
            db.OpenConnection();
            var result = db.QueryDatabaseById("SELECT avg(hdop),to_char(datetime, 'YYYY-MM-DD') as average_hdop FROM positions where unitid = :id group by to_char(datetime, 'YYYY-MM-DD');",id);
            while (result.Read())
            {

                var avgHdopPerCar = Convert.ToDouble(result[0]);
                var date = Convert.ToDateTime(result[1]);
                tp.Add(new Tuple<double, DateTime>(avgHdopPerCar, date));
            };
            db.CloseConnection();
            return tp;

        }

        private List<Tuple<double, DateTime>> GetCarHdopTotalCarsPerDay()
        {
            var tp = new List<Tuple<double, DateTime>>();
            db.OpenConnection();
            var result = db.QueryDatabase("SELECT avg(hdop),to_char(datetime, 'YYYY-MM-DD') as average_hdop FROM positions group by to_char(datetime, 'YYYY-MM-DD');");
            while (result.Read())
            {

                var avgHdopPerCar = Convert.ToDouble(result[0]);
                var date = Convert.ToDateTime(result[1]);
                tp.Add(new Tuple<double, DateTime>(avgHdopPerCar, date));
            };
            db.CloseConnection();
            return tp;
        }

Query database method (I can probably overload this one):

   public NpgsqlDataReader QueryDatabase(string query)
    {
        var command = new NpgsqlCommand(query, conn);
        command.Connection = conn;
        return command.ExecuteReader();
    }

     public NpgsqlDataReader QueryDatabaseById(string query, int parameters)
    {
        var command = new NpgsqlCommand(query, conn);
        command.Parameters.Add("id",NpgsqlDbType.Integer);
        command.Prepare();
        command.Parameters[0].Value = parameters;
        command.Connection = conn;
        return command.ExecuteReader();
    }

First some general information. Your code currently solves a specific problem of the "object relational impedance mismatch" in a specific way. Consider to minimize the effort and complexity to handle this mismatch by using an object-relational mapping framework. Here is the thing: Every single step of code improvement code will lead towards an implementation of an more generalized object-relational mapper anyway. But that will be a hard way to go. Every answer given will be one of those:

Write your own OR-Mapper
Use an existing OR-Mapper
Develop your code towards an OR-Mapper
Ignore the problem through adding specific code that makes your solution more inflexible

I don't think that 1. or 2. will be covered here. I will ignore 4 because we are here to improve code. Therefore I will only provide some steps of 3.

The first step to remove redundancy is to identifiy the parts that need to be flexible. In your case you may need a new class of objects that holds following information:

table column name (unitid)
the type of the table column (NpgsqlDbType.Integer)
value to query (id)
the placeholder within the query (":id")

So what you have built then is something like a QueryParameter for a specific table (average_hdop).

Now you can generalize your parameter of the query-method:

private List<Tuple<double, DateTime>> GetCarHdops(List<QueryParameter> queryParams)

With this information you will be able to built your where-clause dynamically through string concatenation. This will be some effort and error prone. Furthermore you are currently restricted to one conjunction. You have to decide between "and" or "or". And make sure to omit the where-clause in the whole if the queryParams are empty.

The parameter will be passed to the method "QueryDatabase" as well. There you can built your "NpgsqlCommand" dynamically.

This is only a suggestion to develop the code in the "right" direction. As you already asked to avoid redundancy on this way you also gain flexibility.

The flexibility now ends at the level where you want to built queries with "and" and "or". If you want to do that you must have somethig like the Criteria-API in JPA (Java). But as I said I won't cover that in this answer.

One other thing you should think about: db.OpenConnection(); and db.CloseConnection(); are perfect candidates be extracted to a template. (see https://en.wikipedia.org/wiki/Template_method_pattern)


Converting domain-specific regular-expressions to a list of all matching instances There seem to be several questions floating around Stackexchange regarding how to take a python regular expression list the matching instances.  This problem is a bit different because 1) I'm need to start off with a domain-specific regex system, not just the standard python regex, and 2) the possible matches for any given location in string are limited to a specific 'alphabet' of characters.

The current implementation works, but I've got a nagging feeling there's a much more succinct way to do it.

import numpy as np

def shorthand_to_instances(shorthand,alphabet):
    """
    Converts the shorthand-notation for bioinformatics 'motifs'
    into the all the instances of sequences they would match.
    Brackets means "it could be any of these letters" in this location.
    Curly braces means "it's *not* one of these letters" in this location,
    it can be any letter in the given "alphabet" except these.
    Lowercase "x" means it could be any of the letters in the given
    "alphabet".

    >>> binf_motifs_to_sequences('T[AG]','AGCT')
    ['TA', 'TG']

    >>> binf_motifs_to_sequences('T{A}T','AGCT')
    ['TGT', 'TCT', 'TTT']

    >>> binf_motifs_to_sequences('G{AGC}AGTC','AGCT')
    ['GTAGTC']

    >>> binf_motifs_to_sequences('xGTC','AGCT')
    ['AGTC', 'GGTC', 'CGTC', 'TGTC']

    """
    instances=[]
    shc = shorthand
    while len(shc)>0:
        char = shc[0]
        assert char in alphabet+'['+']'+'{'+'}'+'x', "Failed assert: '{0}'".format(char)
        if char in alphabet:
            # it's in the alphabet
            if len(instances)==0:
                instances.append(char)
            else:
                for i in list(np.arange(len(instances))):
                    instances[i] += char
            shc = shc[1:]
        elif char=='[':
            # it's a 'one of these'
            chargroup,c,e = shc[1:].partition(']')
            if len(instances)==0:
                for char in chargroup:
                    instances.append(char)
            else:
                newinstances = []
                for i in list(np.arange(len(instances))):
                    stem = instances[i]
                    for char in chargroup:
                        newinstances.append(stem+char)
                instances = newinstances
            shc = shc[len(chargroup)+2:]
        elif char=='{':
            # it's a 'not this / not these'
            chargroup0,c,e = shc[1:].partition('}')
            chargroup = alphabet.translate(None,chargroup0)
            if len(instances)==0:
                for char in chargroup:
                    instances.append(char)
            else:
                newinstances = []
                for i in list(np.arange(len(instances))):
                    stem = instances[i]
                    for char in chargroup:
                        newinstances.append(stem+char)
                instances = newinstances
            shc = shc[len(chargroup0)+2:]
        elif char=='x':
            # it's an 'any char'
            chargroup = alphabet
            if len(instances)==0:
                for char in chargroup:
                    instances.append(char)
            else:
                newinstances = []
                for i in list(np.arange(len(instances))):
                    stem = instances[i]
                    for char in chargroup:
                        newinstances.append(stem+char)
                instances = newinstances
            shc = shc[1:]
        else:
            break

    return instances

if __name__ == "__main__":
    import doctest
    doctest.testmod()

1. Review

This is clear, well-documented code.
The doctests all call binf_motifs_to_sequences but your function is named shorthand_to_instances so all the doctests fail.
There's no need to have this kind of infrastructure for running doctests:

if __name__ == "__main__":
    import doctest
    doctest.testmod()

since you can easily run doctests from the command line using Python's -m option:

python -m doctest mymodule.py

Assertions should be used for programming errors (conditions that you believe can't happen), but this assertion:

assert char in alphabet+'['+']'+'{'+'}'+'x'

is really a runtime error (it might happen if bad data was passed to the function), so it would be better to raise an exception.
A given shorthand can have exponentially many matching sequences. For example, xxxx already has 256 matching sequences over a four-character alphabet. For this reason, I would avoid returning a list of matching sequences, as this requires building a list and storing all the sequences in memory. It would be better to generate the sequences one at a time.

2. Simplifying

The way to make this kind of code simpler is to use functional decomposition to divide it into pieces that are simpler to understand, implement, and test.

A sensible division into two pieces would be to first, parse the shorthand notation, producing some kind of data structure; and second, take the data structure and generate the matching sequences. Since the alphabet is likely to be small, the natural data structure to use is just a sequence of strings giving the characters that match at each position. So given the shorthand xT[AG]{AT} over the alphabet ACGT, the intermediate data would be the sequence ['ACGT', 'T', 'AG', 'CG'].

(If alphabets were expected to be much larger, then this might be somewhat wasteful in space, and so there might be a need to have a more sophisticated data structure here.)

I've called the first step "parsing" but really it's so simple that it's just lexical analysis and in Python this can be done simply by writing a regular expression that matches a token, and calling re.finditer to loop over the tokens:

import re

class ParseError(Exception): pass

def shorthand_parse(shorthand, alphabet):
    """Parse bioinformatics shorthand notation and generate strings giving
    the characters in alphabet that are allowed to match at each
    position in the sequence.

    Square brackets means "it could be any of these letters" in this
    location. Curly braces means "it's *not* one of these letters" in
    this location (it can be any letter in the given alphabet except
    these). Lowercase "x" means it could be any of the letters in the
    given alphabet.

    >>> list(shorthand_parse('xT[AG]{AT}', 'ACGT'))
    ['ACGT', 'T', 'AG', 'CG']

    """
    # Use set() to remove duplicates, and sorted() to ensure that the
    # output is in a canonical order (for predictability and testing).
    alphabet = set(alphabet)
    alphabet_str = ''.join(sorted(alphabet))
    shorthand_re = r'''(x)             # Any character in alphabet
                      |([{0}])         # Single character
                      |\[([{0}]*)\]    # One of these characters
                      |{{([{0}]*)}}    # Not one of these characters
                      |(.)             # Anything else is an error
                    '''.format(alphabet_str)
    for m in re.finditer(shorthand_re, shorthand, re.VERBOSE):
        x, single, oneof, noneof, error = m.groups()
        if x:
            yield alphabet_str
        elif single:
            yield single
        elif oneof:
            yield ''.join(sorted(set(oneof)))
        elif noneof:
            yield ''.join(sorted(alphabet - set(noneof)))
        else:
            raise ParseError("unexpected character '{}'".format(error))

Now that we have the strings of characters that are valid at each position, we want the Cartesian product of those strings. This can be computed by itertools.product, and in fact the output of shorthand_parse is already in the right format for input to that function:

import itertools

def shorthand_sequences(shorthand, alphabet):
    """Generate all sequences matching the given bioinformatics shorthand
    notation over the given alphabet.

    >>> list(shorthand_sequences('T[AG]', 'AGCT'))
    ['TA', 'TG']
    >>> list(shorthand_sequences('T{A}T', 'AGCT'))
    ['TCT', 'TGT', 'TTT']
    >>> list(shorthand_sequences('G{AGC}AGTC', 'AGCT'))
    ['GTAGTC']
    >>> list(shorthand_sequences('xGTC', 'AGCT'))
    ['AGTC', 'CGTC', 'GGTC', 'TGTC']
    >>> list(shorthand_sequences('[AG]{AT}[CG]', 'AGCT'))
    ['ACC', 'ACG', 'AGC', 'AGG', 'GCC', 'GCG', 'GGC', 'GGG']

    """
    for seq in itertools.product(*shorthand_parse(shorthand, alphabet)):
        yield ''.join(seq)


Trying to avoid a double full scan with aggregates in query I have a statistics query I'm trying to run against the below table:

CREATE TABLE "*****"."RUN_D"
(
"WHSE_CODE" CHAR(12 BYTE),
"RUN_NUM" NUMBER(*,0),
"SHEET_NUM" NUMBER(*,0),
"SHEET_SEQ" NUMBER(*,0),
"COUNT_DATE" DATE,
"COUNTED" CHAR(1 BYTE),
"ITEM_NUM" CHAR(30 BYTE),
"BIN_CODE" CHAR(10 BYTE),
"STOCK_UOM" CHAR(10 BYTE),
"ON_HAND" NUMBER(12,3),
"SNAP_COST" NUMBER(15,5),
"COUNTED_OH" NUMBER(12,3),
"COUNTER_NAME" CHAR(20 BYTE),
"USER_CODE" CHAR(30 BYTE),
"COUNT_VARIANCE" CHAR(1 BYTE),
"ORG_CODE" CHAR(2 BYTE),
"DIV_CODE" CHAR(8 BYTE),
"LOT_CODE" CHAR(20 BYTE),
"UPDATED" CHAR(1 BYTE)
)

I have the following query which works correctly but EXPLAIN PLAN is telling me that it requires a double table scan, which I'm trying to avoid.

Query:

SELECT
  tot.run_num, tot.whse_code, TRUNC(tot.count_date) AS Count_Date,
  CAST((vary.Variance_Count / COUNT(tot.item_num) * 100) AS DECIMAL(10,2)) AS Percentage_Count_Variance,
  CAST((vary.Variance_Cost / SUM(tot.snap_cost * tot.on_hand) * 100) AS DECIMAL(10,2)) AS Variance_Percentage,
  CAST(vary.Variance_Cost AS DECIMAL(10,2)) AS Total_Value_Variance
FROM run_d tot
JOIN
(SELECT run_num, COUNT(item_num) AS Variance_Count, SUM(snap_cost * (counted_oh - on_hand)) AS Variance_Cost
 FROM run_d
 WHERE counted_oh - on_hand != 0
 GROUP BY run_num) vary ON tot.run_num = vary.run_num
WHERE TRUNC(tot.count_date) BETWEEN TO_DATE('07/01/2014','MM/DD/YYYY') AND TO_DATE('07/21/2014','MM/DD/YYYY')
GROUP BY tot.run_num, tot.whse_code, vary.Variance_Count, vary.Variance_Cost,   TRUNC(tot.count_date)
ORDER BY tot.whse_code, tot.run_num

Is there a more efficient way that I can write this query, most specifically to avoid the double table scan?

No, I cannot see a better way. The group-by constraints are different for the selects, so there is no way to merge them in to one.

The remainder of your code looks good, except I am concerned about your % calculations.... are they accurate?

(vary.Variance_Count / COUNT(tot.item_num) * 100) AS DECIMAL(10,2)

That looks like it will be integer arithmetic all the way through, I would instead write it as:

(100.0 * vary.Variance_Count / COUNT(tot.item_num)) AS DECIMAL(10,2)


Bit packing and unpacking I needed a variadic function to pack and unpack bits into integer types. This is my first attempt:

template<typename T>
constexpr T pack(bool b)
{
    return b;
}

template<typename T, typename... Types>
constexpr T pack(bool b, Types... args)
{
    return (b << sizeof...(Types)) | pack<T>(args...);
}

template<typename T, typename... Types>
void unpack(T packed, bool& b1)
{
    b1 = packed & 1;
}

template<typename T, typename... Types>
void unpack(T packed, bool& b1, Types&... args)
{
    b1 = packed & (1 << sizeof...(Types));
    unpack(packed, args...);
}

Usage example:

int main(void)
{
    std::cout << pack<int>(1, 0, 0, 1, 0, 1, 1, 0) << std::endl; // 150
    std::cout << pack<int>(1, 0, 1) << std::endl; // 5
    int val = pack<int>(1, 0, 1);
    bool b1, b2, b3;
    unpack(val, b1, b2, b3);
    std::cout << b1 << " " << b2 << " " << b3 << std::endl; // 1 0 1
}

Does this code contain any bugs, can it be improved, and are variadic templates used appropriately here (I still don't master their syntax)?

Missing overflow check

One serious flaw that I see in this code is that the user needs to determine the number of parameters to unpack. This is a no go for a function whose output depends on a runtime input. Even worse there is no check that would tell the user that the actual number overflows the number of bits given to be unpacked into.

One possible solution would be to return an std::vector<bool> to fit the whole number.

The other solution would be to retain the current interface but to introduce error notification (by exception or return code).

Unnecessary template parameter

Another thing regarding the unpack function:
It seems that you don't need the Types parameter in the recursion end, so it becomes:

template<typename T>
void unpack(T packed, bool& b1)
{
    b1 = packed & 1;
}

Naming

The function parameter names could be better.
I assume b1 is only appropriate in the top level call of the function. I cannot decide on a better name now, but it should indicate that it is the current bit. Likewise, args should be named remainingBits or something like this.


Parsing HTML, XML into a hash map of products I'm working on a simple parser that is supposed to extract hash maps representing vinyl records from web pages (online stores) and XML files. The goal is to have a parser that I can easily run with multiple threads over a ~8 MB XML and a ~2 MB HTML file to read products into a relational database.

I know the relational database will be its own nightmare to marshal things into and to update, but learning how I can marry Clojure to a traditional database is part of my fun.

The initial parser seems to work reasonably well, but my grasp of idiomatic Clojure and my Clojure vocabulary are rudimentary at best. Do you have any suggestions?

Source on GitHub

The result of the doseq there is:

{:artist Lantlôs, :title Melting Sun, :price 12.99}
{:artist Alcest, :title Shelter, :price 12.99}
{:artist Alcest, :title Opale, :price 8.99}
{:artist Duncan Evans, :title Lodestone, :price 14.99}
{:artist Empyrium, :title Dead Winter Ways, :price 9.99}
{:artist Falkenbach, :title Asa, :price 14.99}
{:artist Negura Bunget, :title Gînd a-prins, :price 8.99}
{:artist Sol Invictus, :title Mr Cruel, :price 8.99}
{:artist LowCityRain, :title LowCityRain, :price 13.99}
{:artist Vàli, :title Forlatt, :price 14.99}
{:artist Vàli, :title Skogslandskap, :price 14.99}
{:artist Nhor, :title Within The Darkness Between The Starlight, :price 24.99}

I'm only working on one single parser (the one for Prophecy Productions in that core.clj file) right now. Once I have multiple parsers ready, I'll have to find a good way to split the project into multiple files and have some sort of centralized reader that takes the hash-maps and marshals them into a database. But I'll bug people here about that when I get there.

On top of my head, you could convert
(string/trim (html/text (first (html/select ... to a function as it's
used twice already.

In product-hash the function extract-artist-album is called twice,
so the return value should've been reused instead.

A minor style thing is the nth, personally I'd rather use first,
second, ..., unless the indexes get larger, but YMMV.

Also, the last two forms should be in a separate function so the file
can be loaded without them being executed.


Updating state with React I am creating a blog using React, MongoDB, Express and Node. I have three components: App, List, and Item. The item is a blog post; the list is a list of the blog posts, and the app includes a place to enter text and submit it. I will eventually add more functionality, but I want to determine if I am adhering to best practices for React (I doubt I am).

So in App, I getInitialState with an array of posts (posts) and a string of text for the input (postbody). I used the componentDidMount to make an AJAX GET request to my database, so the user can see all the posts.

To handle entering text I just made a simple handleChange function which updates the state of postbody.

I also have a handleClick function, which grabs this.state.postbody and then POSTs it database. However the same function also makes a separate GET request of the database to update the state of the posts array. This doesn't seem right! Shouldn't that be handled some other way and updated automatically? * This is the primary question I have. *

Also, please let me know if I need to break the components down further, or if I am violating best practices using React (e.g. changing state in the wrong place, or using props incorrectly).

var React = require('react');

var Item = React.createClass({
  render: function() {
    return (

{this.props.postbody}

    )
  }
})

var List = React.createClass({

  render: function() {
    return (

        {this.props.array.map(function(post) {

          return (
            <Item postbody={post.postbody}></Item>
          )
        })}

    )
  }
})

var App = React.createClass({

  getInitialState: function() {
    return {
       posts: [],
       postbody: ''
    }
  },

  componentDidMount: function() {
    $.ajax({
      type: 'GET',
      url: '/api/blogPosts',
      success: function(data) {
        this.setState({posts: data});
      }.bind(this)
    })
  },

  handleClick: function() {

    event.preventDefault();

    var blogPost = this.state.postbody;

    $.ajax({

      type: 'POST',
      url: '/api/blogPosts',
      data: { postbody: blogPost }
    });

    $.ajax({
      type: 'GET',
      url: '/api/blogPosts',
      success: function(data) {
        this.setState({posts: data});
      }.bind(this)
    })
  },

  handleChange: function(event) {

    this.setState({ postbody: event.target.value})
  },

  render: function() {
    return (

        <form action="/api/blogPosts" method="post">
            <input onChange={this.handleChange} type="text" name="postbody"></input>
            <button type="button" onClick={this.handleClick}>Submit</button>
        </form>
        <List array={this.state.posts} />

    )
  }
})

I'll start from what I perceive as "top" and work my way down.

  <form action="/api/blogPosts" method="post">
    <input onChange={this.handleChange} type="text" name="postbody"></input>
    <button type="button" onClick={this.handleClick}>Submit</button>
  </form>
  <List array={this.state.posts} />

You'd probably want to abstract the <form> into its own component. You can then expose a submit event, essentially just a callback handed down to a prop on the component. Your form component will call that callback, passing in the details you need for your AJAX.

Additionally, List and array don't really tell me anything. What kind of list is it? What's in the array? Better name them properly before you start scratching heads and lose hair.

Also, <input> doesn't need a closing tag.

// Better

  <PostForm onSubmit={this.handleSubmit} />
  <Posts posts={this.state.posts} />

componentDidMount: function() {
    $.ajax({
        type: 'GET',
        url: '/api/blogPosts',
        success: function(data) {
            this.setState({
                posts: data
            });
        }.bind(this)
    })
},

handleClick: function() {

    event.preventDefault();

    var blogPost = this.state.postbody;

    $.ajax({
        type: 'POST',
        url: '/api/blogPosts',
        data: {
            postbody: blogPost
        }
    });

    $.ajax({
        type: 'GET',
        url: '/api/blogPosts',
        success: function(data) {
            this.setState({
                posts: data
            });
        }.bind(this)
    })
},

I see that your GET request is redundant here. You can put that in a separate function, say loadPosts. Your functions don't really tell me anything either. Sure, they're handling a click, or respond to a mount but what are they doing?

Also, I see you're using jQuery. POST and GET requests have shorthand versions, $.post and $.get respectively.

When you handle the click, you call two AJAX operations in sequence. That sequence isn't guaranteed, especially when network latency is introduced. By the time you launched the GET, the POST might not have finished yet, and your GET return an incomplete list. It could also be that your POST succeeded, but GET failed. Usually, a POST request returns an updated version of the resource. Use that to just patch in the new data instead of retrieving the entire list.

Also, it's recommended you use the Promise interface of jQuery operations. tl;dr: use then instead of success, error, done or fail.

Since you're on React, I assume you use a transpiler setup. You can take advantage of new ES6 syntax, like arrow functions, shorthand literal assignment, shorthand literal functions

componentDidMount(){
  this.loadPosts();
},
onSubmit(post){
  this.submitPost(post);
},
loadPosts(){
  return $.get('/api/blogPosts').then(posts => this.setState({posts}));
},
submitPost(postBody){
  return $.post('/api/blogPosts', {postBody}).then(post => this.state.posts.push(post));
}

Now if your API can't handle returning the updated resource from a POST, you can simply call your GET after the POST suceeds.

submitPost(postBody){
  $.post('/api/blogPosts', {postBody})
   .then(() => this.loadPosts())
}

var List = React.createClass({

  render: function() {
    return (

        {this.props.array.map(function(post) {

          return (
            <Item postbody={post.postbody}></Item>
          )
        })}

    )
  }
})

Usually when I see nested functions, I just move out the function into the class instead of inline. Much cleaner, and less visual clutter. Also, Item doesn't really tell me what it is. What kind of item is this? If this is a post, then it should be named Post or BlogPost.

var List = React.createClass({
  createPost(post){
    return <BlogPost postbody={post.postbody}></BlogPost>
  },
  render() {
    return (

        {this.props.array.map(this.createPost)}

    )
  }
});


Finding if sequential numbers for total exists Question:
Given a sequence of positive integers A and an integer T, return whether there is a continuous sequence of A that sums up to exactly T

Example:

A = [23, 5, 4, 7, 2, 11], T = 20: True because 7 + 2 + 11 = 20
A = [1, 3, 5, 23, 2], T = 8: True because 3 + 5 = 8
A = [1, 3, 5, 23, 2], T = 7: False because no sequence in this array adds up to 7

Write code to find if sequential numbers for total exists.

Note: I'm looking for an O(N) solution. There is an obvious O(N^2) solution  but is not the final solution I'm looking for.

My answer code (in ruby) is the following. Please let me know if there is a more efficient way.

class Sequence
  def initialize(integers)
    @integers = integers
  end

  def continuous_sequence_for_total_exists?(total)
    sliced_array = slice_array(total)
    sliced_array.each do |array|
      array.each do
        if array.reduce(:+) == total
          return true
        else
          array.shift
        end
      end
    end

    return false
  end

  private

  # Slice array with any integer larger than max
  #
  # e.g.:
  # [1, 3, 5, 23, 2] => [1, 3, 5], [2]
  def slice_array(max)
    chunks = @integers.chunk{ |i| i < max || nil }
    chunks.map{ |answer, value| value }
  end
end

Your code incorrectly returns false if I give it [23, 5, 4, 7, 2, 11, 1] and a target value of 20. The answer should still be 7 + 2 + 11, but it doesn't find it.

That's because the reduce operation always runs to the end of the array, so it is unable to pick out a matching sub-sequence in the middle of a larger sequence. It can only find it, if it's at the end. I.e. it does this:

5 + 4 + 7 + 2 + 11 + 1 => 30
4 + 7 + 2 + 11 + 1     => 25
7 + 2 + 11 + 1         => 21
2 + 11 + 1             => 13 # could just give up here, really
11 + 1                 => 12
1                      => 1

=> false

However 2 + 7 + 11 would've been a valid answer.

Your example input just happens to be crafted so that you get correct results; the matching sub-sequences are always anchored to the end of an array. They're never in the middle of it.

Furthermore, by chunking using i < max you remove values that are equal to the target sum. I.e. trying [1, 3, 7, 5, 23, 2] with a target of 7 will fail, even though there is a sequence - a sequence of 1 value - that matches.

This is however easily fixed by changing the block to use i <= max.

Overall, I'd propose something like this:

def sub_sequence_equal_to?(total, values)
  sequences = values.chunk { |n| n <= total || nil }.map(&:last)

  sequences.each do |sequence|
    sequence.reduce(0) do |sum, n|
      sum += n
      sum -= sequence.shift while sum > total
      return true if sum == total
      sum
    end
  end

  false
end

It'll gradually build a sum, but also subtract the earliest values if said sum has grown too large.

So given [23, 5, 4, 7, 2, 11, 1] and a target value of 20 it'll do something like:

5                  => 5
5 + 4              => 9
5 + 4 + 7          => 16
5 + 4 + 7 + 2      => 18
5 + 4 + 7 + 2 + 11 => 29
    4 + 7 + 2 + 11 => 24
        7 + 2 + 11 => 20

=> true

It's not quite \$O(n)\$, and perhaps there's a smarter way (it'd be nice to get rid of that separate chunk step for instance). Still, it's more efficient (and works better) than the original.


Operator Overloading Tricks in C++ This method is taken from Syntactic Aspartame. This is my attempt at a generic version.

The goal is to create an operator X <NAME> Y where name is anything, and X, Y, and the return is of any type.

Here is the 'library':

#ifndef COMPUTERSCIENCE_ANGULAR_OPERATOR_H
#define COMPUTERSCIENCE_ANGULAR_OPERATOR_H

template <typename LHS, typename RHS, typename RET> struct AngularOperator;

template <typename LHS, typename RHS, typename RET>
struct InnerAngularOperator {
    const AngularOperator<LHS, RHS, RET>* outer;
    LHS* lhs;
    bool outer_l;

    RET operator>(RHS& rhs) {
        return (outer_l) ? outer->angular_lr(*lhs, rhs) : outer->angular_rr(*lhs, rhs);
    }

    RET operator<(RHS& rhs) {
        return (outer_l) ? outer->angular_ll(*lhs, rhs) : outer->angular_rl(*lhs, rhs);
    }
};

template <typename LHS, typename RHS, typename RET>
struct AngularOperator {
    explicit AngularOperator() { }

    virtual RET operator()(LHS& lhs, RHS& rhs) const = 0;
    virtual RET angular_lr(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
    virtual RET angular_rr(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
    virtual RET angular_ll(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
    virtual RET angular_rl(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
};

template <typename LHS, typename RHS, typename RET>
InnerAngularOperator<LHS, RHS, RET> operator<(LHS& lhs, const AngularOperator<LHS, RHS, RET>& outer) {
    return {&outer, &lhs, true};
};

template <typename LHS, typename RHS, typename RET>
InnerAngularOperator<LHS, RHS, RET> operator>(LHS& lhs, const AngularOperator<LHS, RHS, RET>& outer) {
    return {&outer, &lhs, false};
};

#endif //COMPUTERSCIENCE_ANGULAR_OPERATOR_H

And here is a simple implementation for string concatenation:

static const struct OP__ANG__STRING_CONCAT : AngularOperator<std::string, std::string, std::string> {
    std::string operator()(std::string& lhs, std::string& rhs) const override { return lhs + rhs; }
} C{};

And finally the usage of all of this would be:

std::string a = "123", b = "456";
std::string c = a <C> b;
// c == "123456

I think your approach is problematic, in the following senses:

You use inheritance for genericity. There's no good reason for there to be an abstract base class for such operations. The behavior of your class is compile-time-determined by the binary operator you which to represent, and nothing else.
You use virtual methods, which really have no bearing on the problem at hand. That is, I don't see any reason why such operators need vtables.
You template on the binary operator's parameter and result types, rather than the operator itself, i.e. instead of

template <typename LHS, typename RHS, typename RET>

try

template <typename Function>

with std::return_type to obtain RET and so on.
Your infix operator implementation has state - and pointer state at that, which is difficult to optimize away - instead of just using temporary values which can get discarded. Don't be so stuck on imperative programming...

I'm pretty sure you could address all three of these issues with a more templated-oriented implementation; with an intermediate class for "infix operator after having gotten the LHS" (or after having gotten the RHS) which can then take the other operator. Possibly the CRTP is relevant here.

I'm being a bit brief and a bit philosophical since I'm strapped for time. If this is too vague for you (=OP), ask for clarification and I'll expand this answer later on.


Attaching a click handler in a cross-browser way I have been attempting to have a method call, with a parameter, inside of a ternary operator to simplify some code.

Code:

 if (window.addEventListener) {
     btnArray[index].addEventListener('click', function() {
        doMassClick( btnArray[index], nameArray[index]);
     });
 } else {
     btnArray[index].attachEvent('onclick', function() {
        doMassClick( btnArray[index], nameArray[index]);
     });
 }

I was able to simplify this down to:

btnArray[index][ window.addEventListener ? 'addEventListener' : 'attachEvent'](window.addEventListener ? 'click' : 'onclick', function() {
    doMassClick( btnArray[index], nameArray[index]);
});

I'd love to know how this can be simplified/cleaned up more..

The common thing in your code is the listener.

function massClickListener() {
    doMassClick( btnArray[index], nameArray[index]);
}

Then it is easier to use the ternary:

btnArray[index][ window.addEventListener ? 'addEventListener' : 'attachEvent'](window.addEventListener ? 'click' : 'onclick', massClickListener);

Personally however, I think this is better:

if (window.addEventListener) {
    btnArray[index].addEventListener('click', massClickListener);
} else {
    btnArray[index].attachEvent('onclick', massClickListener);
}

Using the conditional operator to choose different methods is not very readable.

Another option might be to use a framework that does these kinds of things for you.


Playframework (Scala) custom exception handling I am using play framework with scala and here is a scenario on which I would like to have your opinion.

Let's say I have 2 custom exceptions that I can throw, which are EmailTaken and AuthFail. What I need to do here is, whenever any of these 2 exceptions happen, I need to return a json with 3 keys success, errorCode and message, in case of all other exceptions let Play's default error handling take charge. Now for all custom exceptions success will always be false, each exception would have a unique errorCode integer value and a unique message string both of which remain fixed for a particular exception.

Now I saw people using case class(they can be pattern matched) or class(saw some java examples) for exception but I didn't see the point of creating them because for any particular exception I don't see the point of creating more than 1 object because its attributes don't have to be changed (I could create a case class with all default parameters but why?). So I created an object for each exception and then I throw that exception object in the controller and then in the Global object I rely on the getCause of the exception.

// custom exceptions code

trait AppException extends Exception {

  val success = false
  def errorCode: Int
  def message: String

  override def fillInStackTrace(): Throwable = {
    this
  }
}

object EmailTaken extends AppException {
  val errorCode = 1
  val message = "email already used"
}

object AuthFail extends AppException {
  val errorCode = 2
  val message = "id/password dont match"
}

// in Play's controller

object Application extends Controller {
def test = Action {
    throw EmailTaken
    Ok("Test Page")
  }
}

// in Play's Global object

object Global extends GlobalSettings {

  override def onError(request: RequestHeader, ex: Throwable) = {
    ex.getCause match {
      case c: AppException =>     // a known custom exception
        Future.successful(InternalServerError(
          Json.toJson(Json.obj(
            "success"-> c.success,
            "message"-> c.message,
            "errorCode"-> c.errorCode
          ))
        ))
      case _ =>
        super.onError(request, ex)
    }
  }
}

I understand that if AuthFail was A case class I would have returned new AuthFail() and pattern matched on that exception object. Also, I could have used isInstanceOf[AppException] to check for custom exceptions. But are there any problems with this approach? Also, what are the other good approaches I can take? I don't have much experience with Scala or Java.

You are right to not create classes for AuthFail and EmailTaken.
These really sense as instances, rather than classes,
as they are special cases of AppException.

For example if AppException was a class, then AuthFail and EmailTaken would be best as instances of that class:

class AppException(val errorCode: Int, val message: String) extends Exception {
  val success = false
}

val emailTaken = new AppException(1, "email already used")

val authFail = new AppException(2, "id/password dont match")

However,
if they are instances,
then you would need to pass them around in the code where they might be needed.
Another alternative is to make them objects,
so you can easily import them and use them where needed:

object EmailTaken extends AppException(1, "email already used")

object AuthFail extends AppException(2, "id/password dont match")

Your approach using a trait for AppException instead of a class seems fine too, but I'm fairly new to Scala myself.
Using a class like I did above seems shorter, so I would prefer it.

As for using case classes (or case objects),
in the posted code I don't see a need:
it seems that you don't need to differentiate the different cases.
If all of these cases can be handled as an AppException and result in an InternalServerError,
then there's no need to implement more.

Finally:

  I could have used isInstanceOf[AppException] to check for custom exceptions. But are there any problems with this approach?

Don't do that. It's recommended to avoid isInstanceOf as much as possible.
The alternative is using polymorphism or pattern matching.
In your case, you don't actually need any of this.
You have simple instances of AppException:
all your cases behave the same way,
their only difference is in parameters, not in behavior.