texts: Dynamically loading and naming controllers in nodejs and express

texts:
I'm trying to write a module to dynamically load all the files from my "controllers" folder, and then add them to the main express instance as routers.

The files inside the controllers export an Express router. So the code basically does the next things:

Read the "controllers" dir.
Store what each router exported by the file to a var.
"Merge" the router with the main app instance(that is exported by the index.js file).

I had some issue generating the controllers name, because they need to be dynamic variables, so I created an object and then I passed the name using the brackets syntax, and I think that they may be stored twice, once in that Object I created and the second it the Express instance (if that makes any sense...).

And overall I think it can be created better.

The code:

./index.js

// Expressjs
const express = require('express');

// Setting and exporting app so this instance could be used in other files.
const app = module.exports = express();

// Load and initialize the controllers, and passing them the main express instance.
require('./lib/controllersLoader');

/*
 * Initializing the listener according to the settings in the config.
 */
app.listen(config.server.port, err => {
    // Throwing an exception since the whole app depends on this.
    if (err) throw err;
    console.log(`SERVER: Listening on port ${config.server.port}`);
});

./lib/controllersLoader.js

// Get the main express app instance
const app = require('../index');
const fs = require('fs');

// Getting an Array of the files in the 'controllers' folder.
let files = fs.readdirSync( __dirname + '/../controllers');

files.forEach( fileName => {
    // Stripping the filename from the extension and storing it for later use
    // as the Controller name.
    let contName = /.+(?=\.\w?)/.exec(fileName)[0];

    // Create a new object to hold the controllers,
    // I use an Object because that helps me with dynamic variables.
    let controllers = {};

    // Store the required module in a variable.
    controllers[contName] = require( __dirname + '/../controllers/' + fileName );

    // Setting the route string.
    let route;

    // If file is the index file, the route should be '/'
    if (fileName === 'index.js') {

        route = '/';

    } else {

        // Get filename without extension using regex
        route = '/' + contName;

    }

    app.use(route, controllers[contName]);
});

./controllers/example.js(in this case its the index)

const router = require('express').Router();
const debug = require('../config').debug;

router.get('/', (req, res) => {
    res.send('Hello, World!');
});

module.exports = router;


texts: Plague Inc. in Python - Extremely Early Stage

texts:
I've been working to create a game in Python similar to Plague Inc. and instead of just writing one big clump of code and then getting it reviewed, I wanted to do it stage-by-stage and make it a little easier. Also, reviews might possibly help me later on in the development process.

import datetime
import random

countries = [
   dict(Name = "China", Population = "1,363,560,000"),
   dict(Name = "India", Population = "1,242,070,000"),
   dict(Name = "United States", Population = "317,768,000"),
   dict(Name = "Indonesia", Population = "249,866,000"),
   dict(Name = "Brazil", Population = "201,032,714"),
   dict(Name = "Pakistan", Population = "186,015,000"),
   dict(Name = "Nigeria", Population = "173,615,000"),
   dict(Name = "Bangladesh", Population = "152,518,015"),
   dict(Name = "Russia", Population = "143,700,000"),
   dict(Name = "Japan", Population = "127,120,000"),
   dict(Name = "Mexico", Population = "119,713,203"),
   dict(Name = "Philippines", Population = "99,329,000"),
   dict(Name = "Vietnam", Population = "89,708,900"),
   dict(Name = "Egypt", Population = "86,188,600"),
   dict(Name = "Germany", Population = "80,716,000"),
   dict(Name = "Iran", Population = "77,315,000"),
   dict(Name = "Turkey", Population = "76,667,864"),
   dict(Name = "Thailand", Population = "65,926,261"),
   dict(Name = "France", Population = "65,844,000"),
   dict(Name = "United Kingdom", Population = "63,705,000"),
   dict(Name = "Italy", Population = "59,996,777"),
   dict(Name = "South Africa", Population = "52,981,991"),
   dict(Name = "South Korea", Population = "50,219,669"),
   dict(Name = "Colombia", Population = "47,522,000"),
   dict(Name = "Spain", Population = "46,609,700"),
   dict(Name = "Ukraine", Population = "45,410,071"),
   dict(Name = "Kenya", Population = "44,354,000"),
   dict(Name = "Argentina", Population = "40,117,096"),
   dict(Name = "Poland", Population = "38,502,396"),
   dict(Name = "Sudan", Population = "37,964,000"),
   dict(Name = "Uganda", Population = "35,357,000"),
   dict(Name = "Canada", Population = "35,344,962"),
   dict(Name = "Iraq", Population = "34,035,000"),
   ]

current_date = datetime.datetime.strftime(datetime.date.today(), "%m-%d-%Y")

print "Welcome to a Python version of Plague Inc."
user = raw_input('\nWhat is your name? ').title() # for later on in the game
print '\nCountries to choose from are\n'
print "Country".ljust(15),"Population\n"
for country in countries:
    print country["Name"].ljust(15), country["Population"]
startcountry = raw_input('\nWhat country would you like to start in? ').title()

if startcountry == 'Random': # random.sample can be used for more than one country later on
    startcountry = random.choice(countries)

diseasename = raw_input('\nWhat would you like to name your disease? ').title()

print '\nNews Bulletin'.ljust(45), current_date
print '-' * 55
print 'An unknown disease named', diseasename, 'has struck', startcountry, 'by storm.'
print 'Doctors and scientists will need to collaborate to find out more information about this disease.'


texts: Using a dictionary template for consistent response structure from an API

texts:
I am making a simple API for news items using Python and the Bottle framework.

I return a Python dictionary from my endpoints as Bottle converts this to JSON automatically in the response to the client.

I wanted to ensure a consistent structure to the responses, so I have declared a template dictionary. The code for each endpoint makes a deep copy of this then modifies the relevant data before returning it.

import bottle
from bottle import route
from copy import deepcopy as deepcopy

# Dictionary for response template
response_dict = {
"status" : "ok",
"code" : 0,
"error" : False,
"message" : "",
"result" : {}
}

# Example route
@route('/example')
def example():
    return_dict = deepcopy(response_dict)
    return_dict["message"] = "Success"
    return_dict["result"] = {
        "title" : "Test Title",
        "body" : "
Lorem ipsum dolor sit amet...
"
    }
    return return_dict

I would like to know if there is a better way to use a template for a JSON response and whether the structure of my dictionary is appropriate.


texts:
Requesting code review, best practices, optimizations for this solution to the Tower of Hanoi problem.

final class PlatePair {

    private final String source;
    private final String destination;

    public PlatePair (String source, String destination) {
        this.source = source;
        this.destination = destination;
    }

    public String getSource() {
        return source;
    }

    public String getDestination() {
        return destination;
    }
}

public final class ToweOfHanoi {

    private ToweOfHanoi () { }

    /**
     * Solves the problem of tower of hanoi
     *
     * @param n     The number of plates
     * @return      The Set of sequential steps to take to solve the hanoi problem.
     */
    public static Set<PlatePair> solve(int n) {
        if (n <= 0) throw new IllegalArgumentException("The number of plates " + n  + " should be greater than zero.");

        final Set<PlatePair> platePair = new LinkedHashSet<PlatePair>();
        moveTowers(n, "A", "B", "C", platePair);
        return platePair;
    }

    public static void moveTowers(int n, String from, String using, String to, Set<PlatePair> platePair) {
        assert platePair != null;

        if (n == 0) return;

        moveTowers(n - 1, from, to, using, platePair);
        platePair.add(new PlatePair(from, to));
        moveTowers(n - 1, using, from, to, platePair);
    }

    public static void main(String[] args) {
        for (PlatePair getHanoi :  solve(3)) {
            System.out.println(getHanoi.getSource() + " : " + getHanoi.getDestination());
        }
    }
}


texts:
# Stack Overflow

'''
Goal: pull back all tables in a database where column name 'Audit Report' == 'complete'
Why is this a script: There are over 1000 tables in the database with the same structure
                        this script will automate checking which reports have a 'complete'
                         under the column name 'Audit Report'
This script will:
    1) pull down all of the tables in a database
    2) pull down all of the column names per table
    3) create a dataframe
    4) filter to all tables that contain a column name
    5) run a dynamic sql query based on filtered df
    6) print out tablenames
'''

# import modules
import pandas as pd
import pyodbc
import time

# connect to database
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=111.11.111.11;'    # servername
                      'Database=databasename;'    # database name
                      'Trusted_Connection=yes;')

# Initialize the list to populate
listoftables = []
columnnames = []

# Step 1
# using the connection string
# appending each table name to 'listoftables'
# this step will give us all of the database tables
cursor = conn.cursor()
for row in cursor.tables():
    listoftables.append(row.table_name)

# Step 2
# using all of the tables, we now want all of the column names
for x in listoftables:
    tempcolnames = []
    # for each table, get all of the column names
    for row in cursor.columns(table = x):
        tempcolnames.append(row.column_name)
    columnnames.append(tempcolnames)

# Step 3
# make a dataframe of the two lists
df = pd.DataFrame(
    {'TableName': listoftables,
     'col_names'  : columnnames
    })

# Step 4
# filter to tables that are have 'Audit_Report' as a column name
df['status'] = df.apply(lambda x: 1 if 'Audit_Report' in x['col_names'] else 0, axis =1 )
# auditreports will return a dataframe with all tables that have 'Audit_Report' as a column name
auditreports = df[df['status'] == 1]

# start time to get an idea for how long the query runs
start_time = time.time()
# this is the 'shell' of the save location
merged=pd.DataFrame()

# Step 5
# this is the iterative sql loop we are going to run
for table in auditreports['TableName']:
    df = pd.read_sql_query('''
        select
            *
        from
            [dbo].[{}]
        where
            Audit_Report = 'Complete'

        '''.format(table, username), conn)

    # checking if the query pulled down any data
    if len(df) > 0:
        df['TableName'] = table
        merged=pd.concat([merged,df], sort=False)
        # if it does have data we store it in 'merged' if it does not, the 'else' is implied as 'do nothing'
        # we dont need to say, else if all was want to do is 'do nothing'

    # waiting a tenth of a second to keep from overloading server or computer
    time.sleep(.1)

# how long the query took to run
minutes = (time.time() - start_time)/60
print('query took: ' + str(minutes) + ' minutes')

# Step 6
# print all reports that have been audited
merged

Concerns: Are my comments understandable?

Potential #TODO: this is considered a Script, how can I take this script and make it more flexible and create a method or Class that I can throw some kwargs and make it more program-like. What part of the script would be the easiest to turn into a method?


texts: CakePHP view with interleaved PHP and HTML

texts:
It's CakePHP, though I'm more interested in what people think about the layout of the indentation, the mark-up, position of logic etc.

Any feedback that relates to the subject of writing CakePHP views / front end code should take precedence over CakePHP feedback or logic feedback, though the latters are welcome too

<?php foreach ($list as $l): ?>

    <?php $english=$l['translation']['english']; ?>

    <?php $translate_to=$l['translation']['translate_to']; ?>

    <?php $content=$l['Content']; ?>

    <?php if($l['flag_count']>0): ?>

                        <?=$l['flag_count'] ?>

    <?php else: ?>

                        <?=$l['flag_count'] ?>

    <?php endif; ?>

                        <?=$this->Html->link("Edit",$l['edit_route']) ?>

                            <?=$english[$content['content_type']."_name"] ?>

    <?php if ($english_id!=$current_language_id): ?>

                            <?=$translate_to[$content['content_type']."_name"] ?>

    <?php endif; ?>

    <?php if ('range'==$content['content_type']): ?>

        <?php $slider_class=(1==$content['slider']) ? "in_slider" : ""; ?>

        <?php $slider_text=(1==$content['slider']) ? "on home" : ""; ?>

                        <div class='js_slider_toggle' data-content-id='<?=$content['id'] ?>'>

                                display on home?

                            <span class='js_icon slider_toggle <?=$slider_class ?>'>

    <?php endif; ?>

<?php endforeach; ?>


texts: Max Heap Data Structure Implemented with Python List

texts:
Created a max heap using a Python list as the base storage. The heap starts at index 1.

Here is the heap:

class Heap:
  def __init__(self):
    # storage starts with an unused 0 to make
    # integer division simpler later on
    self.storage = [0]
    self.size = 0

  def insert(self, value):
    self.storage.append(value)
    self.size += 1
    self._bubble_up(self.size)

  def delete(self):
    self.storage[1], self.storage[-1] = self.storage[-1], self.storage[1]
    deleted_value = self.storage.pop(-1)
    self.size -= 1
    self._sift_down_(1)
    return deleted_value

  def get_max(self):
    return self.storage[1]

  def get_size(self):
    return self.size

  def _bubble_up(self, index):
      # my two part base case for recursion:
      # if parent is greater than child or if index less than or equal to one
      if self.storage[index] < self.storage[index//2] or index <= 1:
          return
      else:
          # swap the parent/child values
          self.storage[index], self.storage[index//2] = self.storage[index//2], self.storage[index]
          # recursive call
          return self._bubble_up(index//2)

  def _sift_down_(self, index):
    left_child = index * 2
    right_child = (index * 2) + 1
    if left_child > self.size:
      return
    if right_child <= self.size:
        if self.storage[index] < self.storage[left_child] or self.storage[index] < self.storage[right_child]:
            largest_child = right_child if (self.storage[right_child] > self.storage[left_child]) else left_child
            self.storage[index], self.storage[largest_child] = self.storage[largest_child], self.storage[index]
            return self._sift_down_(largest_child)
        else:
          return
    else:
      if self.storage[index] < self.storage[left_child]:
        self.storage[index], self.storage[left_child] = self.storage[left_child], self.storage[index]
        return self._sift_down_(left_child)
      else:
        return

Produces the correct output when used:

heap = Heap()

heap.insert(40)
heap.insert(18)
heap.insert(20)
heap.insert(15)
heap.insert(13)
heap.insert(9)
heap.insert(19)
heap.insert(1)
heap.insert(3)
heap.insert(8)

print(heap.storage)

heap.delete()
print("heap after delete(): ", heap.storage)
print(heap.get_size())

Outputs:

[0, 40, 18, 20, 15, 13, 9, 19, 1, 3, 8]
heap after delete():  [0, 20, 18, 19, 15, 13, 9, 8, 1, 3]
9

Seeking any and all feedback; missing edge cases, logical flaws, and general improvement tips.


texts: Trying to avoid a double full scan with aggregates in query

texts:
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?


texts:
Although this sort works on Int lists < length million, when the stack overflows, the last clause of the merge function definition looks odd to me, recursing in 2 places. Is there clearer way to define that definition and how can the stack limitation be avoided?

msort :: Ord a => [a] -> [a]
msort [] = []
msort xs = concat . merge . split $ xs

merge :: Ord a => [[a]] -> [[a]]
merge [] = []
merge [x] = [x]
merge (l1:l2:ls) = merge $ mpair l1 l2 : merge ls

mpair :: Ord a => [a] -> [a] -> [a]
mpair [] l2 = l2
mpair l1 [] = l1
mpair l1@(x:xs) l2@(y:ys) | x >= y     = x : mpair xs l2
                          | otherwise  = y : mpair l1 ys

split :: [a] -> [[a]]
split xs = [[x]| x<-xs]


texts: How can I find out why this Rust program to echo lines from stdin is slow?

texts:
Given the following Rust program:

fn main() {
    let mut reader = io::stdin();
    for line in reader.lock().lines() {
        match line {
            Ok(l) => print!("{}", l),
            Err(_) => continue,
        }
    }
}

yes | program achieves 1.04MiB/s throughput, according to pv. The trivial C program below, which I fully realize does less, gives me a throughput of 141MiB/s.

int main() {
    int c;
    while((c=getchar()) != EOF)
        putchar(c);
}

How do I go about finding out what's keeping the Rust version from being faster? While I would appreciate if you just told me what to change to make it faster, I'm far more interested in how to find out what needs to be changed.

Edit: I tried changing lines() to chars() in the Rust version, to approximate the C version better, but it didn't seem to make any difference.


texts:
Just created an overlay on hover following a Youtube tutorial - but I adjusted some css to make it responsive.
I'd like to hear hear some reviews or suggestions where I can improve.

#Projects .card {
  position: relative;
  overflow: hidden;
}

#Projects .card:before {
  position: absolute;
  content: '';
  width: 80%;
  height: 220%;
  background:rgba(199, 0, 57, .9);
  top: -50%;
  left: -100%;
  z-index: 1;
  transform: rotate(20deg);
  transform-origin: center top 0;
  transition: .5s;
}

#Projects .card:hover:before {
  left: 10%;
}

#Projects .card .card-text {
  width: 100%;
  padding: 0 20px;
  position: absolute;
  top: -150%;
  color: #fff;
  left: 0;
  z-index: 2;
  transition: .5s;
}

#Projects .card:hover .card-text {
   top: 20%;
}

@media (max-width: 992px) {
  #Projects .card:hover .card-text {
    top: 15%;
 }

  #Projects  .card-text a {
    font-size: 11px;
  }

  #Projects .btn {
    padding: 5px 15px;
  }

  #Projects  .card-text h3 {
    font-size: 18px;
  }

  #Projects  .card-text h5 {
    font-size: 18px;
  }

}

@media (max-width: 575px) {

  #Projects .btn {
    padding: 5px 24px;
    font-size: 1.1rem;
  }

  #Projects  .card-text h3 {
    font-size: 1.5rem;
  }

  #Projects  .card-text h5 {
    font-size: 1.5rem;
  }

}
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
    integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

Project 1

Some text...

            View

Project 2

Some text...

            View


texts: Updating items in a list from a blocking source asynchronously

texts:
This is a Windows forms application.
this.Server.GetLogMessages() will block if there are no messages to get, so I want this in a separate thread. I'm putting the messages into a ConcurrentStack and then pulling them out on the main thread to output them.
Here is the respective code:
private async Task UpdateLogs()
{
    var logMessages = new ConcurrentStack<string>();

    // assign to `_` to avoid warning
    var _ = Task.Run(async () =>
    {
        await foreach (var message in this.Server.GetLogMessages())
        {
            logMessages.Push(message);
        }
    }, this.CancellationTokenSource.Token);

    await foreach (var message in GetMessages())
    {
        // don't update the UI if task is canceled
        if (this.CancellationTokenSource.Token.IsCancellationRequested)
        {
            break;
        }

        this.textLogs.AppendText($"{message}{Environment.NewLine}");
    }

    async IAsyncEnumerable<string> GetMessages()
    {
        var message = String.Empty;

        while (!this.CancellationTokenSource.IsCancellationRequested)
        {
            while (!logMessages.TryPop(out message))
            {
                await Task.Delay(100);
            }

            yield return message;
        }
    }
}

It works fine, but seems as if it could be better/cleaner somehow.


texts: Fetching the definition of a word using a REST API

texts:
This is the code I'm using to GET the definition of a word from Wordnik's REST API. I don't want to ignore any error but this is causing the code to be ridiculously long. I'm new to Swift so I'd appreciate it if someone could explain how best to trim it down.

class func define(params: DefinitionParameters!, delegate: WordnikDictionaryDelegate!){

        if let url = url(definitionParams: params){

            NSLog("URL: \(url)")

            let session = NSURLSession.sharedSession()
            let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in

                var error : NSError?
                if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? NSMutableArray{

                    NSLog("Response: \(json)")

                    if json.count == 0 {

                        delegate.dictionaryDidLoad(
                            nil,
                            forWord: params.word,
                            error: self.buildError(404, message: "No definitions found")
                        )

                    }else if let definitionJSON = json[0] as? NSMutableDictionary{

                        delegate.dictionaryDidLoad(
                            definitionJSON.valueForKeyPath("text") as? String,
                            forWord: params.word,
                            error: nil
                        )

                    }else{

                        delegate.dictionaryDidLoad(
                            nil,
                            forWord: params.word,
                            error: self.buildError(401, message: "Unexpected Result Format")
                        )

                    }

                }else{

                    delegate.dictionaryDidLoad(
                        nil,
                        forWord: params.word,
                        error: self.buildError(401, message: "Unexpected results format")
                    )

                }

            })

            task.resume()

        }else{

            delegate.dictionaryDidLoad(
                nil,
                forWord: params.word,
                error: self.buildError(400, message: "Invalid URL")
            )

        }

    }


texts: An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++

texts:
This is a follow-up question for A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++ and A Summation Function For Boost.MultiArray in C++. I am trying to implement an arithmetic_mean template function for calculating the arithmetic mean value of various type arbitrary nested iterable things. The recursive_reduce function (thanks to G. Sliepen's answer) and the recursive_size function are used here. Because both recursive_reduce function and recursive_size function are needed in the arithmetic_mean function here, there are two new concepts is_recursive_reduceable and is_recursive_sizeable created as follows.
template<typename T>
concept is_recursive_reduceable = requires(T x)
{
    recursive_reduce(x, 0.0);
};

template<typename T>
concept is_recursive_sizeable = requires(T x)
{
    recursive_size(x);
};

Next, the main part of arithmetic_mean template function:
template<class T> requires (is_recursive_reduceable<T> && is_recursive_sizeable<T>)
auto arithmetic_mean(const T& input)
{
    return (recursive_reduce(input, 0.0)) / (recursive_size(input));
}

Some test cases of this arithmetic_mean template function.
//  std::vector<int> case
std::vector<int> test_vector = {
    1, 2, 3
};
auto arithmetic_mean_result1 = arithmetic_mean(test_vector);
std::cout << arithmetic_mean_result1 << std::endl;

//  std::vector<std::vector<int>> case
std::vector<decltype(test_vector)> test_vector2 = {
    test_vector, test_vector, test_vector
};
auto arithmetic_mean_result2 = arithmetic_mean(test_vector2);
std::cout << arithmetic_mean_result2 << std::endl;

// std::deque<int> case
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto arithmetic_mean_result3 = arithmetic_mean(test_deque);
std::cout << arithmetic_mean_result3 << std::endl;

// std::deque<std::deque<int>> case
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto arithmetic_mean_result4 = arithmetic_mean(test_deque2);
std::cout << arithmetic_mean_result4 << std::endl;

A Godbolt link is here.
All suggestions are welcome.
The summary information:

Which question it is a follow-up to?
A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++ and
A Summation Function For Boost.MultiArray in C++

What changes has been made in the code since last question?
The arithmetic_mean template function is the main part here.

Why a new review is being asked for?
I am not sure if it is a good idea to add is_recursive_sizeable and is_recursive_reduceable concepts here. Moreover, I am wondering that the name of used concept is understandable.


texts: C++ lock free, single producer, single consumer queue

texts:
Assumptions for use:

push() will only ever be called by a single thread.
pop() will only ever be called by a single thread.

Requirements:

push() needs to be as fast as possible. Requirements are stringent enough that I've determined that I can't use std::mutex (at least not in any way I've attempted to) as it is far too slow. (some initial stress tests took 6-8 ms without and 26-60 ms with std::mutex)

Code:

template<typename T>
class PCQueue {
    const size_t size;
    std::unique_ptr<T[]> contents;
    std::atomic<size_t> head;
    std::atomic<size_t> tail;
public:
    explicit PCQueue(size_t s) : size(s), contents(new T[s]), head(0), tail(0) {}

    //num of elements in ringbuffer (size - room())
    size_t count() {
        return (tail + size - head) % size;
    }

    //num of free spaces in ringbuffer (size - count())
    size_t room() {
        return (head + size - tail) % size;
    }

    void push(T t) {
        size_t newTail = (tail + 1) % size;
        if (newTail == head) {
            throw std::runtime_error("Pushing Full PCQueue");
        }
        contents[tail] = t;
        tail = newTail;//std::atomic implicitly memfences, so this op must occur after the "contents[tail] = t;"
    }

    T pop() {
        if (tail == head) {
            throw std::runtime_error("Popping Empty PCQueue");
        }
        T ret = contents[head];
        size_t newHead = (head + 1) % size;
        head = newHead;
        return ret;
    }
};

My testing has implied that this performs correctly (but I'd like to squeeze more speed out of it if possible), but I'm not entirely certain my assumption about the push method is correct (the comment regarding memory barriers), as I'm still getting a handle on those, and I'm not sure I understand how loads and stores can be reordered regarding atomic and non-atomic variables, with the various memory orders.  sequential consistency (the default) should enforce the desired behavior I think?

I'm worried that it's just working by coincidence (as concurrent code has a tendency to do), so a verification that my code is valid would be appreciated, as well as any general tips to improve it both in readability and performance.


texts: Algorithm for Run Length Encoding - String Compression

texts:
I attempted a problem from the Cracking the Coding Interview book. The following input: aabcccaaa should give the following output: a2b1c3a3. Any advice is much appreciated!

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

char* compress(char*);

int main(int argc, char** argv)
{
    if(argc==2)
    {
        printf("The compression of %s is %s \n", argv[1],
            compress(argv[1]));
    }
    else
        printf("Not correct number of inputs.");
}

char* compress(char* str)
{
    const size_t len = strlen(str);
    char result[len];

    //initialized to 0, so length check can be done later
    memset(result, 0, len);

    int counter;
    int j = 0;

    if(str==NULL || len == 0)
        return 0;

    result[0] = str[0];
    for(size_t i = 0; i < len; i++)
    {
        counter = 1;//reset counter

        //to make sure no array out of bounds exception occurs
        if(result[j+1]==0)
            result[++j] = counter + '0';
        else
            return str;

        while(str[i] == str[i+1])
        {
            //to store number in char array, add the asci value
            // of 0.
            result[j] = (++counter + '0');
            i++;
        }
        if(result[j+1]==0)
            result[++j] = str[i+1];
        else
            return str;
    }

    result[++j] = '0';

    //to avoid "function returns address of local variable" error
    //to also avoid altering original argument
    char* str1 = (char*)malloc(sizeof(result));
    strcpy(str1, result);
    return str1;
}


texts:
I have written a working implementation of a Poker card that I want to be comparable. I feel that my solution is somewhat bloated in C++, and want to ask if I should have done something different to make it more concise.

#ifndef POKER_CARD_H
#define POKER_CARD_H

enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace};
enum Color {Hearts, Spades, Dimonds, Clubs};

namespace {
    int as_int(Value value){
        switch(value){
            case Value::Two     : return 2;
            case Value::Three   : return 3;
            case Value::Four    : return 4;
            case Value::Five    : return 5;
            case Value::Six     : return 6;
            case Value::Seven   : return 7;
            case Value::Eight   : return 8;
            case Value::Nine    : return 9;
            case Value::Ten     : return 10;
            case Value::Jack    : return 11;
            case Value::Queen   : return 12;
            case Value::King    : return 13;
            case Value::Ace     : return 14;
        }
    }
    int as_int(Color color){
        switch(color){
            case Color::Dimonds : return 1;
            case Color::Clubs   : return 2;
            case Color::Hearts  : return 3;
            case Color::Spades  : return 4;
        }
    }
}

class Card {

public:
    Card(Value value, Color color);

    Color getColor() const;

    Value getValue() const;

private:
    Value value;
    Color color;
};

inline bool operator==(const Card& lhs, const Card& rhs) {
    return ((rhs.getValue() == lhs.getValue()) && (rhs.getColor() == lhs.getColor()));
}
inline bool operator!=(const Card& lhs, const Card& rhs) {return !operator==(lhs,rhs);}
inline bool operator< (const Card& lhs, const Card& rhs) {
    if (as_int(lhs.getValue()) < as_int(rhs.getValue())){
        return true;
    }
    else if (as_int(rhs.getValue()) == as_int(lhs.getValue())){
        return as_int(lhs.getColor()) < as_int(rhs.getColor()) ? true : false;
    }
    else {
        return false;
    }
}
inline bool operator> (const Card& lhs, const Card& rhs) {return  operator< (rhs,lhs);}
inline bool operator<=(const Card& lhs, const Card& rhs) {return !operator> (lhs,rhs);}
inline bool operator>=(const Card& lhs, const Card& rhs) {return !operator< (lhs,rhs);}

#endif //POKER_CARD_H


texts: Return the number of unique ways you can climb the staircase

texts:
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.

For example, if N is 4, then there are 5 unique ways:

1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2

What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.

public class DailyCodingProblem12 {
    public static void main(String args[]) {
        int[] X = { 1, 2 };
        int N = 4;
        int result = solution(N, X);
        System.out.println(result);

        int[] X1 = { 1, 2, 3 };
        N = 4;
        result = solution(N, X1);
        System.out.println(result);

        int[] X2 = { 1, 2, 3 };
        N = 3;
        result = solution(N, X2);
        System.out.println(result);
    }

    static int solution(int N, int[] X) {
        int[] memory = new int[N + 1];
        memory[0] = 1;
        memory[1] = 1;
        return noOfWays(N, X, memory);
    }

    static int noOfWays(int N, int[] X, int[] memory) {
        if (memory[N] != 0) {
            return memory[N];
        }
        int noOfWays = 0;
        for (int i = 0; i < X.length && (N - X[i] >= 0); i++) {
            memory[N - X[i]] = noOfWays(N - X[i], X, memory);
            noOfWays += memory[N - X[i]];
        }
        return noOfWays;

    }

}

How do I improve my solution? There is a way to save more space?


texts: Handler for default values in a CLI flag utility library in C

texts:
I am developing a very basic CLI flag utility library in C. The following code is a part of the main translation unit containing all the relevant functions, and is located in the global scope.

struct pair {
    char name[100];
    char defaultValue[100];
};

static struct pair *defaults = NULL;

void setDefault(const char *flagName, const char *defaultValue) {
    if (defaults == NULL) {
        defaults = malloc(10 * sizeof(struct pair));
    }

    static short pos = 0;
    if(pos % 10 == 0) {
        defaults = realloc(defaults, (pos + 10) * sizeof(struct pair));
    }

    strncpy((defaults + pos)->name, flagName, 100);
    strncpy((defaults + pos)->defaultValue, defaultValue, 100);

    pos++;
}

static void clearDefaults(void) {
    free(defaults);
}

To clue you in, the idea is that the user calls setDefault with 2 strings, the first of which represents a flag name, and the second which represents the default value of that (should it not have been passed to the program). The pair is stored in memory and is later used by other library functions.

My question is centered around the storage of flagName:defaultValue pairs, which are represented using the pair struct. Right now I'm using a global static variable defaults which stores a pointer to a dynamically allocated array of said structs. It's static, therefore I had to initially set it to NULL, and "initialize" it only after the first call of setDefaults. I feel that this creates unnecessary clutter as other library functions have to test defaults for NULL before trying to search it for a specific pair.

That is my first concern, is there a better way to initialize a global static variable?

The second is my implementation of dynamic reallocation in setDefault. It initially allocates space for 10 pairs, and once the limit is reached it allocated space for 10 more and so on. I've tested the implementation with Valgrind and a bunch of calls to setDefault and there were no memory leaks or other errors.

Is this a good way to do it? Can anything be improved? I'm very much a beginner at C so any feedback is welcome.


texts: Taking change - convergent iteration through iterate

texts:
For the Code Review community challenge "Implement StackSTV", the algorithm requires a "convergent iterative scheme" to calculate the keep ratios of candidates that have been elected.

To simplify the calculation of those keep ratios I have written following function to truncate an infinite list that calculates the keep ratio scheme's next step.

I wonder whether I missed some basic library function and whether the function is idiomatic haskell:

{-
    Take items from a list, as long as the last item taken is not the same as the next item in the list.
    Passing an empty list returns an empty list.
-}
takeModified :: Eq a => [a] -> [a]
takeModified (x:xs) = [x] ++ go x xs
    where
    go :: Eq a => a -> [a] -> [a]
    go elem (x':xs')
       | elem == x' = []
       | otherwise  = [x'] ++ go x' xs'
    go elem [] = []
takeModified [] = []


texts:
A Translator in the Terminal using Golang. It uses Google's API. Currently, it only translates en (English) to es (Spanish).

package main

import (
    "bufio"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "os"
)

func (item *Result) UnmarshalJSON(data []byte) error {
    var v []interface{}
    if err := json.Unmarshal(data, &v); err != nil {
        fmt.Println(err)
        return err
    }
    item.Data = v[0].(interface{}).([]interface{})[0].([]interface{})[0].(string)
    return nil
}

type Result struct {
    Data interface{}
}

func main() {
    fmt.Printf("\nEnter text\t: ")
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    query := scanner.Text()
    response, err := http.Get("https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=es&dt=t&q=" + url.QueryEscape(query))
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    } else {
        defer response.Body.Close()
        bytes, err := ioutil.ReadAll(response.Body)
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
        var result Result
        if err := json.Unmarshal(bytes, &result); err != nil {
            fmt.Println(err)
        }
        value := result.Data
        fmt.Printf("Translation\t: %s\n", value)
    }
}


texts: All possible combinations of colors for Mastermind

texts:
Just started out with CIS 194 on Haskell and wonder what the more idiomatic way to solve this problem would have been.

This code is supposed to generate all possible combinations of 6 given colors up to a given length. It works, but I think my solution is not that elegant. The suggested solution included this hint:

  Hint: This exercise is a bit tricky. Try using a helper function that
  takes in all the codes of length n − 1 and uses it to produce all
  codes of length n. You may find the concatMap function helpful.

But I could not figure a way so I did it like this:

-- Mastermind -----------------------------------------

-- A peg can be one of six colors
data Peg = Red | Green | Blue | Yellow | Orange | Purple
         deriving (Show, Eq, Ord)

-- A code is defined to simply be a list of Pegs
type Code = [Peg]

-- List containing all of the different Pegs
colors :: [Peg]
colors = [Red, Green, Blue, Yellow, Orange, Purple]

---- Exercise 6 ----

-- Extends a given Code by prepending a Peg: extendCode [Red, Green] Blue -> [Blue, Red, Green]
extendCode :: Code -> Peg -> Code
extendCode code peg = peg : code

-- Extends a given Code by all possible Pegs, turning the Code into a list of Codes
fullyExtendCode :: Code -> [Code]
fullyExtendCode code = map (\color -> extendCode code color) colors

-- Extends a given number of Codes by all possible Pegs
fullyExtendCodes :: [Code] -> [Code]
fullyExtendCodes [] = map (:[]) colors
fullyExtendCodes codes = concatMap fullyExtendCode codes

-- Helper function for allCodes which includes the Codes list from previous recursions
aCodes :: [Code] -> Int -> [Code]
aCodes codes 0 = codes
aCodes codes l = aCodes (fullyExtendCodes codes) (l - 1)

allCodes :: Int -> [[Peg]]
allCodes l = aCodes [] l

Any suggestions from more experiened Haskell programmers?


texts:
A little while ago I wrote this implementation of Conway's Game of Life in Ruby. It's based on this Game of Life in APL video, which I think is rather elegant, though a bit dense. Feel free to give feedback on any aspect of the program, but the parts I most care about are readability and the way I work with matrices.

Unlike most implementations, the neighbor count used to determine who's alive in the next generation includes self (the cell who's neighbors we are counting). This technique is used in the APL version as well and allows us to express the rules of the game in a more concise manner than normal: i.e. a cell in the next generation is alive if its neighbor count including self is three or if it was alive in the last generation and its neighbor count including self is four.

The program currently monkey-patches Matrix, which I'm not thrilled about. I'm pretty sure Matrix#translate can be removed in favor of some sort of matrix math that would do the equivalent, but I'm not familiar enough with the subject to know how to do this well.

It would also probably be nice to blank the screen without shelling out.

The program requires Ruby 1.9 or later.

#!/usr/bin/env ruby
# encoding: utf-8

require 'matrix'

class Matrix
  def translate(row_count, col_count)
    Matrix[
      *row_vectors.map do |row|
        row.to_a.rotate(row_count)
      end.rotate(col_count)
    ]
  end
end

class Board
  attr_reader :width, :height

  def self.random(size)
    board = Matrix.build(size) { rand(10) == 0 ? 1 : 0 }
    new(board)
  end

  def self.parse(board_string)
    new(Matrix[board_string.split("\n").map { |row| row.split.map(&:to_i) }])
  end

  def initialize(board)
    @width = board.column_size
    @height = board.row_size
    @board = board
  end

  def next
    board_state = neighbor_counts.map.with_index do |count, idx|
      count == 3 || count == 4 && @board[idx / width, idx % width] == 1 ? 1 : 0
    end

    Board.new(board_state)
  end

  def to_s
    @board.row_vectors.map do |row|
      row.map do |n|
        n == 1 ? "B" : "·"
      end.to_a.join(" ")
    end.join("\n")
  end

  def neighbor_counts
    [-1,0,1].product([-1,0,1]).map do |row, col|
      @board.translate(row, col)
    end.reduce(:+)
  end
end

if __FILE__ == $0
  b = Board.random(40)
  system("clear")

  loop do
    puts b
    sleep 0.2
    system("clear")
    b = b.next
  end
end


texts:
Problem statement

  In simple words it say, count total Strongly connected components in the graph.

All edges are undirected.
I have the following code that uses kosaraju 2DFS approach.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class AirlineProblem {
    private static boolean[] visited = null;
    private static boolean[] reverseVisited = null;
    private static ArrayList<ArrayList<Integer>> adj = null;
    private static ArrayList<ArrayList<Integer>> adjr = null;
    private static boolean[] indegree0 = null;

    public static void main(String[] args) {
        String[] airports = { "BGI", "CDG", "DEL", "DOH", "DSM", "EWR", "EYW", "HND", "ICN", "JFK", "LGA", "LHR", "ORD",
                "SAN", "SFO", "SIN", "TLV", "BUD" };
        String[][] routes = { { "DSM", "ORD" }, { "ORD", "BGI" }, { "BGI", "LGA" }, { "SIN", "CDG" }, { "CDG", "SIN" },
                { "CDG", "BUD" }, { "DEL", "DOH" }, { "DEL", "CDG" }, { "TLV", "DEL" }, { "EWR", "HND" },
                { "HND", "ICN" }, { "HND", "JFK" }, { "ICN", "JFK" }, { "JFK", "LGA" }, { "EYW", "LHR" },
                { "LHR", "SFO" }, { "SFO", "SAN" }, { "SFO", "DSM" }, { "SAN", "EYW" } };
        String startingAirport = "LGA";
        System.out.println(solution(airports, routes, startingAirport));
    }

    public static int solution(String[] airports, String[][] routes, String startingAirport) {
        int n = airports.length;

        HashMap<String, Integer> airportsMap = new HashMap<>();
        for (int i = 0; i < n; ++i)
            airportsMap.put(airports[i], i);

        adj = new ArrayList<>(n);
        adjr = new ArrayList<>(n);
        for (int i = 0; i < n; i++) {
            adj.add(new ArrayList<Integer>());
            adjr.add(new ArrayList<Integer>());
        }
        for (String[] route : routes) {
            adj.get(airportsMap.get(route[0])).add(airportsMap.get(route[1]));
            adjr.get(airportsMap.get(route[1])).add(airportsMap.get(route[0]));
        }

        visited = new boolean[n];
        reverseVisited = new boolean[n];
        indegree0 = new boolean[n];
        for (int i = 0; i < n; i++)
            if (visited[i] == false)
                dfs1(i);

        int counter = 0;
        for (int i = 0; i < n; ++i)
            if (indegree0[i] == true && airportsMap.get(startingAirport) != i)
                counter++;
        return counter;
    }

    private static void dfs1(int node) {
        visited[node] = true;
        boolean hasParent = false;
        for (int i : adjr.get(node))
            if (visited[i] == false) {
                hasParent = true;
                Arrays.fill(reverseVisited, false);
                dfs1(i);
            }

        if (hasParent == false) {
            indegree0[node] = true;
            reverseVisited[node] = true;
            for (int i : adj.get(node))
                if (reverseVisited[i] == false)
                    dfs2(i);
        }
    }

    private static void dfs2(int node) {
        visited[node] = true;
        reverseVisited[node] = true;
        indegree0[node] = false;
        for (int i : adj.get(node))
            if (reverseVisited[i] == false)
                dfs2(i);
    }
}

I would like review about the efficiency, performance and programming paradigm I used. I would also be interested if some tasks can be automated by using a library.


texts: Possible security issues in email validation

texts:
I need feedback on this code regarding security issues.

<?php
if(!isset($_POST['submit']))
{
    //This page should not be accessed directly. Need to submit the form.
    echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];

//Validate first
if(empty($name)||empty($visitor_email))
{
    echo "Name and email are mandatory!";
    exit;
}

if(IsInjected($visitor_email))
{
    echo "Bad email value!";
    exit;
}

$email_from = 'someemail@some.com';//<== update the email address
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n".
    "Here is the message:\n $message".

$to = "someemail@some.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank-you.html');

I'm using this IsInjected($str) function to validate email addresses:

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}

?>


texts:
I have written very simple Python code to solve the simple harmonic oscillator using Euler method, but I am not sure if the program is correct or not. I would be very grateful if anyone can look at my code and suggest further improvements since I am very new to this programming thing.

import matplotlib.pyplot as plt
v=0.0   #initial velocity
h=0.01  #time step
x=5.0   #initial position

t=0.0
ta,xa=[],[]

while t<1.0:
    ta.append(t)
    xa.append(x)

    v=v-(10.0/1.0)*x*h    #k=10.0, m=1.0
    x=x+v*h
    t=t+h
plt.figure()
plt.plot(ta,xa,'--')
plt.xlabel('$t(s)$')
plt.ylabel('$x(m)$')
plt.show()


texts: List class/controller to prevent memory exhaustion

texts:
In my Outlook spam add-on when I receive a new email I create a new task to process the email.

That way I don't block Outlook itself.

To prevent the List collection from growing exponentially, (traditionally Outlook is not closed for a long, long time), I have created a simple TasksController class that will help me keeping the list to a manageable size.

Then I can simply call:

TasksController.Add( ProcessNewEmail() )
...
private async Task<bool> ProcessNewEmail()
{
   /// ... do stuff
}

This is the class itself

internal class TasksController : IDisposable
{
  private static TasksController _controller;

  private static TasksController Controller => _controller ?? (_controller = new TasksController());

  private readonly object _lock = new object();
  private readonly List<Task> _tasks;

  private TasksController()
  {
    _tasks = new List<Task>();
  }

  public void Dispose()
  {
    WaitAll();
  }

  private void _Add( Task run )
  {
    //  remove all the completed tasks
    RemoveAllCompleted();

    // and add the new task
    lock (_lock)
    {
      _tasks.Add(run);
    }
  }

  private void _WaitAll()
  {
    lock (_lock)
    {
      Task.WaitAll(_tasks.ToArray());
    }
    RemoveAllCompleted();
  }

  private void RemoveAllCompleted()
  {
    lock(_lock)
    {
      _tasks.RemoveAll(t => t.IsCompleted);
    }
  }

  public static void WaitAll()
  {
    Controller._WaitAll();
  }

  public static void Add(Task run)
  {
    Controller._Add( run );
  }
}

Is deriving from IDisposable necessary?
Is the class itself thread safe?


texts: Russian Peasant Multiplication Algorithm

texts:
For university, we have just started to learn C++ as a language, and one of our challenges to do in our spare time is to write an algorithm for 'Peasant multiplication'. In the challenge, we have been told that we cannot use the multiplication operator *.

My code for it is as follows.

#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <limits>
using namespace std;

vector<int> half(float numberToHalf) {
    vector<int> steps;
    while (numberToHalf != 1) {
        steps.push_back(numberToHalf);
        numberToHalf = floorf(numberToHalf / 2);
    }
    steps.push_back(1);
    return steps;
}

vector<int> repeatedDouble(int number, int limit) {
    vector<int> doubleList;
    for (int i = 0; i < limit; i++)
    {
        doubleList.push_back(number);
        number += number;
    }
    return doubleList;
}

int adding(vector<int> halfList, vector<int> doubleList) {
    int total = 0;
    for (int i = 0; i < halfList.size(); i++) {
        if (halfList[i] % 2 != 0) {
            total += doubleList[i];
        }
    }
    return total;
}

int verify(string timeRound) {
    bool roundAgain = true;
    int number;
    do {
        cout << "Enter the " << timeRound << " number: " << endl;
        cin >> number;
        if(cin.good() && 0 < number) { //if number entered is positive and an integer
            roundAgain = false;
        }else {
            //Make cin ready to take another input
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(),'\n'); //Snippet taken from https://stackoverflow.com/questions/16934183/integer-validation-for-input
            cout << "A valid input is a POSITIVE, whole, number. No letters, words, or negatives" << endl;
        }
    } while (roundAgain);
    return number;
}

int main() {
    int num1 = verify("First");
    int num2 = verify("Second");

    vector<int> halved = half(num1);
    vector<int> doubled = repeatedDouble(num2, halved.size());
    cout << "The result is: " << adding(halved, doubled);
}

Any help in optimising the code to make it look and run even better would be appreciated! Also, if any of you could give some tips for robustness or similar that would be great too!

I am completely new to C++ so any tricks and tips from experienced coders would be amazing!


texts: Writing data of a certain integer type to a buffer

texts:
I have function which writes data of a specified type to a buffer. Here is the part of this which writes Uint8, Uint16, Uint32 and Uint64, in big and little endian. As you can see that the same code is repeated several times, so I want to make this code more elegant.

...
            case BW_DATA_TYPE_UINT8:
            {
                Uint8_T val = *(static_cast(Uint8_T*, src));
                Uint8ToLittleEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] );
                bw->curPos += length;
                break;
            }

            case BW_DATA_TYPE_UINT16_LE:
            {
                Uint16_T val = *(static_cast(Uint16_T*, src));
                Uint16ToLittleEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 1 );
                bw->curPos += length;
                break;
            }

            case BW_DATA_TYPE_UINT32_LE:
            {
                Uint32_T val = *(static_cast(Uint32_T*, src));
                Uint32ToLittleEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 3 );
                bw->curPos += length;
                break;
            }

            case BW_DATA_TYPE_UINT64_LE:
            {
                Uint64_T val = *(static_cast(Uint64_T*, src));
                Uint64ToLittleEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 7 );
                bw->curPos += length;
                break;
            }

            case BW_DATA_TYPE_UINT16_BE:
            {
                Uint16_T val = *(static_cast(Uint16_T*, src));
                Uint16ToBigEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 1 );
                bw->curPos += length;
                break;
            }

            case BW_DATA_TYPE_UINT32_BE:
            {
                Uint32_T val = *(static_cast(Uint32_T*, src));
                Uint32ToBigEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 3 );
                bw->curPos += length;
                break;
            }

            case BW_DATA_TYPE_UINT64_BE:
            {
                Uint64_T val = *(static_cast(Uint64_T*, src));
                Uint64ToBigEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 7 );
                bw->curPos += length;
                break;
            }
    ...


texts: Function to split strings on multiple delimiters

texts:
I have this implementation of the split algorithm that different from .split() method you can use with multiple delimiters. Is this a good way of implementing it (more performance)?

def split(str, delim=" "):
    index = 0
    string = ""
    array = []
    while index < len(str):
        if str[index] not in delim:
            string += str[index]
        else:
            if string:
                array.append(string)
                string = ""
        index += 1
    if string: array.append(string)
    return array

Using the standard .split() method:

>>> print "hello = 20".split()
['hello', '=', '20']

>>> print "one;two; abc; b ".split(";")
['one', 'two', ' abc', ' b ']

Using my implementation:

>>> print split("hello = 20")
['hello', '=', '20']

>>> print split("one;two; abc; b ", ";")
['one', 'two', ' abc', ' b ']

Multiple delimiters:

>>> print split("one;two; abc; b.e. b eeeeee.e.e;;e ;.", " .;")
['one', 'two', 'abc', 'b', 'e', 'b', 'eeeeee', 'e', 'e', 'e']

>>> print split("foo barfoo;bar;foo bar.foo", " .;")
['foo', 'barfoo', 'bar', 'foo', 'bar', 'foo']

>>> print split("foo*bar*foo.foo bar;", "*.")
['foo', 'bar', 'foo', 'foo bar;']

Obs: We can do something like using re.split().


texts:
I've started working on a small Flask project for no real reason other than fun, and pulled myself back on form validation. I realize that there are existing libraries like WTForms, but wanted to try and write something myself.

I tried to make the high-level interaction similar to that of SQLAlchemy, where you define models with column (in this case field) attributes and they get done 'automatically', but this is the first time I've tried writing something like this so I'm looking for criticisms primarily in the FormDeserializer.__init__ (I've never had a practical purpose for dir and __dict__ so I'm unsure if my usage is acceptable)

import typing
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug import ImmutableMultiDict

class Field():
    class FieldLengthExceeded(Exception):
        pass

    class MissingFieldData(Exception):
        pass

    def __init__(self, name: str, *, strict: bool=False, max_length: int=1024):
        self.name: str = name
        self._value: typing.Optional[str] = None
        self._strict: bool = strict
        self._max_length: int = max_length

    @property
    def value(self) -> typing.Optional[str]:
        return self._value

    @value.setter
    def value(self, value):
        if value is not None and len(value) > self._max_length:
            raise self.FieldLengthExceeded
        else:
            self._value = value

    def validate(self):
        if self._value is None and self._strict:
            raise self.MissingFieldData
        elif self._value is not None:
            self._type_specific_validation()

    def _type_specific_validation(self):
        pass

class IntegerField(Field):
    class InvalidInteger(Exception):
        pass

    def _type_specific_validation(self):
        if not all([x in '0123456789' for x in self._value]):
            raise self.InvalidInteger

    @Field.value.getter
    def value(self) -> typing.Optional[int]:
        return self._value if self._value is None else int(self._value)

class PasswordField(Field):
    class Password(str):
        def __eq__(self, comparator):
            return check_password_hash(self, comparator)

    @Field.value.getter
    def value(self) -> typing.Optional[Password]:
        return self._value if self._value is None else self.Password(generate_password_hash(self._value))

class EmailField(Field):
    class InvalidEmail(Exception):
        pass

    def _type_specific_validation(self):
        if '@' not in self._value:
            raise self.InvalidEmail

class FormDeserializer():
    def __init__(self, data: ImmutableMultiDict):
        for attrib in dir(self):
            d = getattr(self, attrib)
            if isinstance(d, Field):
                # Get the attribute from the form data
                v: typing.Optional[str] = data.get(d.name, None)

                d.value = v

                # Check the value is valid
                d.validate()

                # Finally, rebind to the value of the field
                self.__dict__[attrib] = d.value

### Example ###
class TestForm(FormDeserializer):
    username = Field('username', strict=False, max_length=24)
    password = PasswordField('password', strict=True)

    email = EmailField('email')

data = {'username': 'jellywx', 'password': 'hello world', 'email': 't@tm.tm'}
f = TestForm(data)


texts: Solving the Mining algorithm from HackerRank

texts:
I was working on this problem for a few hours last night and finally came up with a brute-force solution. The task is to report the minimum work necessary (sum of weight × distance) to relocate gold produced at n mines to k of those mines. The first line of input contains n and k; subsequent lines give the location and amount of gold of each mine.

My solution is passing all the unit tests that don't time out, so I'm fairly confident that is correct except that it needs to use fewer operations in order to be a successful submission.

Any ideas on how I can make this not timeout?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

static class Extensions
{
     // ripped from http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n
    public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
    {
      return k == 0 ? new[] { new T[0] } :
        elements.SelectMany((e, i) =>
          elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] {e}).Concat(c)));
    }
}

class Mine
{
    public int Distance { get; set; } // from river
    public int Gold { get; set; } // in tons
}

class Solution
{
    static void Main(String[] args)
    {
        // helper function for reading lines
        Func<string, int[]> LineToIntArray = (line) => Array.ConvertAll(line.Split(' '), Int32.Parse);

        int[] line1 = LineToIntArray(Console.ReadLine());
        int N = line1[0], // # of mines
            K = line1[1]; // # of pickup locations

        // Populate mine info
        List<Mine> mines = new List<Mine>();
        for(int i = 0; i < N; ++i)
        {
            int[] line = LineToIntArray(Console.ReadLine());
            mines.Add(new Mine() { Distance = line[0], Gold = line[1] });
        }

        // helper function for checking whether a move combination ends up
        // forming K groups
        Func<IEnumerable<Tuple<Mine,Mine>>, bool> FormsKGroups = combo =>  {
            var groups = mines.Select(mine => new List<Mine>() { mine })
                              .ToList();
            foreach(var move in combo)
            {
                int start = mines.IndexOf(move.Item1),
                      end = mines.IndexOf(move.Item2);
                groups[end].Add(mines[start]);
                groups[start].Remove(mines[start]);
            }
            return groups.Count(g => g.Count > 0) == K;
        };

        // Get all move combinations that form K groups
        var moveCombos = mines.SelectMany(m => mines, (m1, m2) => Tuple.Create(m1, m2))
                              .Where(tuple => !tuple.Item1.Equals(tuple.Item2)) // we have all 2^N ordered pairs of mines
                              .Combinations(N - K) // all combinations of length (N - K) of those pairs
                              .Where(x => true); // that form K groups

        // helper function for calculating the cost of a sequence of moves
        Func<IEnumerable<Tuple<Mine,Mine>>, int> MovesCost = (moves) =>
            moves.Aggregate(0, (sum, move) =>
                sum + Math.Abs(move.Item1.Distance - move.Item2.Distance) * move.Item1.Gold);

        // calculate min cost and print result
        int mincost = moveCombos.Min(MovesCost);
        Console.WriteLine(mincost);
    }
}


texts: Checking if a string is a number with STL

texts:
Recently me and colleague had a discussion about the following piece of code (simple bool function that checks if string is a number, +1000 not allowed, -1000, 1234 ... allowed).

He felt that it was hackish, while I thought it was nice, clean and elegant (since it uses STL, not hand made loops).
So is this a judgement call or one of us is wrong? Is this code elegant or hack?

 bool validate(const std::string& m)
 {
   if (m.empty())
     return false;
   return m.end() == find_if(*m.begin() == '-'? ++m.begin() : m.begin(),
                                    m.end(), not1(ptr_fun(isdigit)));
 }


texts: Class that pickles, unpickles and extends pickled documents

texts:
I've been pickling ngram models and I wrote this class to be able to easily extend models when training.

I wanted to know if it could possibly be done in a better way?

class PickleDoc:

    def pickle(self, obj, writefile=None):

        if writefile:
            with open(writefile, 'w') as ad:
                pckled = pickle.dump(obj, ad)
                logger.debug('pickled object at {0}'.format(writefile))
                # return pckled
        else:
            with open('default.plk', 'w') as df:
                pckled = pickle.dump(obj, df)
                logger.debug('pickled object at default file')
                # return pckled

    def unpickle(self, readfile):
        logger.debug('unpickling {0}'.format(readfile))

        try:
            with open(readfile, 'r') as rf:
                p = pickle.load(rf)
                logger.debug('unpickled {0}'.format(readfile))
                return p
        except IOError:
            logger.debug('issue unpickling {0}'.format(readfile))

    def _extend_pickled_list(self, obj, extendfile):
        """extends a pickled list object from a given file"""

        with open(extendfile, 'r') as ef:
            p1 = pickle.load(ef)
            logger.debug('1. unpickled {0}'.format(ef))
            p2 = p1 + obj
            logger.debug('1.5 appended {0}'.format(type(p2)))

        with open(extendfile, 'w') as ew:
            logger.debug('2. about to pickle object at {0}'.format(ew))
            pickle.dump(p2, ew)
            logger.debug('3. pickled object {0}'.format(ew))

        with open(extendfile, 'r') as e:
            logger.debug('4. reading object {0}'.format(e))
            r = pickle.load(e)
            logger.debug('5. read object {0}'.format(e))

        return r

    def _extend_pickled_dict(self, obj, extendfile):
        """extends a pickled dict object from a given file"""

        with open(extendfile, 'r') as efr:
            p1 = pickle.load(efr)

            for k, v in obj.items():
                if k not in p1.keys():
                    p1[k] = v
                elif type(p1[k]) == list:
                    p1[k] = p1[k].append(v)
                else:
                    pass

        with open(extendfile, 'w') as efw:
            pickle.dump(p1, efw)

        with open(extendfile, 'r') as er:
            r = pickle.load(er)

        return r

    def extend_file(self, obj, extendfile):

        if os.path.exists(extendfile):
            if type(obj) == dict:
                ex_file = self._extend_pickled_dict(obj, extendfile)
            elif type(obj) == list:
                ex_file = self._extend_pickled_list(obj, extendfile)
            else:
                logger.debug('Object type is not extensable')

        else:
            logger.debug('file does not exists')

p.s intense logging was from when it didn't want to play ball initially.


texts:
Problem description:

Given a 32-bit signed integer, reverse digits of an integer.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: \$[−2^{31},  2^{31} − 1]\$. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

My solution:

var reverse = function(x) {
    temp = (x < 0) ? -1 : 1;
    x = x * temp;
    let res = x % 10;
    while(x > 9) {
        x = (x - x % 10) / 10;
        res = 10 * res + x % 10;
    };
    res = ((res < 2147483648) && (res >= -2147483648)) ? res : 0;
    return res * temp;
};

console.log(reverse(-321));
console.log(reverse(1534236469));

Test:
Input #1: -321
Expected #1: -123

Input #2: 1534236469
Expected #2: 0

Test summmary:
Solution accepted
Runtime: 88ms

Question: Is there a way to make this function less complex, maybe also improving its runtime?


texts: Find the locally biggest or equal values including corners in an array

texts:
I am looking for a function, that will find in array of n integers highest or equal locally values including corners.

My code is probably wrong, and I somehow think solution is in some library like NumPy or SciPy, but I do not know how to find it:

def look_for_maximas(vals):
    '''
    actually look for hills, 1, 0, 1, 1, 0, 1, 1, 2, 1, 0, 0 should return indexes 0, 2, 3, 7
    :param vals:
    :return:
    '''
    if len(vals) == 0:
        return []
    res = []
    buff = [0]
    is_candidate = True
    i = 1
    while i < len(vals):
        if vals[i] > vals[i-1]:
            is_candidate = True
            buff = [i]
        elif vals[i] == vals[i-1] and is_candidate:
            buff.append(i)
        else:
            if is_candidate:
                res += buff
            is_candidate = False
            buff = []
        i += 1
    if is_candidate:
        res += buff

    return res

I have some tests to test it:

assert look_for_maximas([1, 0, 1, 1, 0, 1, 1, 2, 1, 0, 0]) == [0, 2, 3, 7]
assert look_for_maximas([0]) == [0]
assert look_for_maximas([0, 1, 0]) == [1]
assert look_for_maximas([]) == []
assert look_for_maximas([0, 0, 0, 0]) == [0, 1, 2, 3]
assert look_for_maximas([i for i in repeat(0, 1000)]) == range(0, 1000)
assert look_for_maximas(
    [100, 0, 0, 100, 10, 0, 10, 10, 0, 5, 3, 0, 0, 10, 10, 10, 10, 100, 0, 1]) == [0, 3, 6, 7, 9, 17, 19]

And it passes it, but it is probably not the best code and I am probably inventing wheel one more time.


texts:
I am currently learning JavaScript and the project I have been working on is creating a basic Blackjack game. Some code was provided for me, with the additional instructions:

"How would you edit the above code to PRINT what you and the Dealer have? How would you edit the code to let you know if you beat the dealer or not? How would you edit the code to let you know who busted? Hit 21? Also, would you hit once? Twice? What code would you put in if you hit either way? Test and run your code in an IDE of your choice."

The code I completed does work, but I believe there is probably a smarter way to write it. My code is as follows:

/* Created by Michael on 5/18/2016. */
// ——- —— —
// INPUTS: Two Integers
// OUTPUT: an Integer
// EFFECT: Returns a random integer between two inputs
function randint( min, max) {
    return Math.floor( Math.random() * (max - min + 1) + min);
}

// INPUTS: none
// OUTPUT: none
// EFFECT: "Player gets a Card"
 function hitMe() {
    console.log(" Hit me." );
handValue += randint( 1,11);
console.log(" New Hand: " + handValue)
}

// These are the cards you have
// your HandValue is an Integer
var handValue = 0;

// These are the cards the Dealer has
// the DealerValue is an Integer
var dealerValue = 0;

// here are your first two cards
handValue += randint( 1,11);
handValue += randint( 1,11);

// here are the Dealers cards
dealerValue += randint( 1,11);
dealerValue += randint( 1,11);

// the Dealer always hits once
dealerValue += randint( 1,11);
console.log("Dealer hits, do you hit or call?");

console.log("hit or call?");

if (handValue < 18)
{
    hitMe()
}
    if (handValue < 18) {
        hitMe()
    }
        if (handValue > 21) {
        console.log("Player Busts! Dealer has " + dealerValue + ".")
    } else if (handValue == 21) {
        console.log("Player hit 21! Dealer has " + dealerValue + ".")
    } else if (dealerValue == 21) {
        console.log("Dealer hit 21! Player has " + handValue + ".")
    } else if (handValue > dealerValue && handValue < 22) {
        console.log("Player wins with " + handValue + "! Dealer had " +              dealerValue + ".")
} else if (dealerValue > 21) {
    console.log("Dealer Busts with " + dealerValue + "! Player has " + handValue + ".")
} else if (dealerValue > handValue && dealerValue < 22) {
    console.log("Dealer wins with " + dealerValue + "! Player had " +   handValue + ".")
}

// Do you hit once? Twice? Or not? Insert your line of code below

// ————————-

Any recommendations for a more efficient way to write this game?


texts:
This is a simple demonstration of a singly linked list, from my class work:

#include <stdio.h>
#include <stdlib.h>
#include <wctype.h>
#include <errno.h>
#include <assert.h>
#include <ctype.h>
#include <stddef.h>
#include <wchar.h>
#include <locale.h>
#include <setjmp.h>
struct node
{
    int          info;
    struct node *link;
};

typedef struct node* NODE;

NODE main()
{
    NODE first = NULL;
    int  item, choice;

    for(;;)
    {
        printf("1.INSERT AT FRONT\n2.DISPLAY\n3.QUIT\n\nPLEASE ENTER YOUR CHOICE:");
        scanf("%d",&choice);

        switch (choice)
        {
            case 1:
            printf("\nEnter the item to be inserted:");
            scanf("%d", &item);

            first = insert_front(item,first);
            break;

            case 2:
            display(first);
            break;

            case 3:
            exit(0);
        }
    }
}

NODE getnode()
{
    NODE x;

    x = (NODE) malloc(sizeof(struct node));
    if(x == NULL)
    {
        printf("Out of memory");
        exit(0);
    }
    return x;
}

int insert_front(int item, NODE first)
{
    NODE temp;
    temp = getnode();
    temp->info = item;
    temp->link = first;
    return temp;
}

void display(NODE first)
{
    NODE temp;

    if(first == NULL)
    {
        printf("Empty");
        return;
    }

    printf("\nThe contents are: ");

    temp = first;
    while(temp != NULL)
    {
        printf("%d ", temp->info);
        temp = temp->link;
    }
    printf("\n");
}

As you can see, this code demonstrates the working of a linked list. How can this program more smaller, better, more professional and much more good? If you were given a chance to modify this program, how would you do it? I wanna know how to think and how to train myself to modify programs like these. And as you see, I have learned most of C. I referred to and learned C from K.N Kings The C programming language: A modern approach and Computer science: A structured approach using C and data structures from Data structures using C by Tenenbaum.

Now I have stretched my legs in learning C what can I do to create application that might be useful to me or to others. Say I want to create a small game like "snake" or create a small application that my father might use to do his business.


texts:
I've made a simple console application using JavaScript, NodeJS and yargs.

index.js

This is the startup file.

#!/usr/bin/env node
'use strict';

const yargs = require('yargs');
const argv = yargs
.option('celsius', {alias: 'c', default: false})
.option('fahrenheit', {alias: 'f', default: false})
.option('kelvin', {alias: 'k', default: false})
.help('h')
.argv;

let value = argv._[0];

if (!value) {
  console.log('You need to pass a value to be converted.');
} else {
  const convert = require('./convert')

  if (argv.celsius) {
    console.log(convert.fromCelsius(value));
  } else if (argv.fahrenheit) {
    console.log(convert.fromFahrenheit(value));
  } else if (argv.kelvin) {
    console.log(convert.fromKelvin(value));
  } else {
    console.log("You need to pass a valid flag.")
  }
}

convert.js

This is required by index.js in order to transform values. Each scale has it own file.

'use strict';

let fixFloat = (value) => parseFloat(value).toFixed(2);

let fromCelsius = (value) => {
  const conversion = require('./celsius');
  let kelvin = fixFloat(conversion.toKelvin(value));
  let fahrenheit = fixFloat(conversion.toFahrenheit(value));
  return `${value}°C = ${fahrenheit}°F = ${kelvin}K`;
};

let fromFahrenheit = (value) => {
  const conversion = require('./fahrenheit');
  let celsius = fixFloat(conversion.toCelsius(value));
  let kelvin = fixFloat(conversion.toKelvin(value));
  return `${value}°F = ${celsius}°C = ${kelvin}K`;
};

let fromKelvin = (value) => {
  const conversion = require('./kelvin');
  let celsius = fixFloat(conversion.toCelsius(value));
  let fahrenheit = fixFloat(conversion.toFahrenheit(value));
  return `${value}K = ${celsius}°C = ${fahrenheit}°F`;
};

module.exports = {
  fromCelsius,
  fromFahrenheit,
  fromKelvin,
};

celsius.js

'use strict';

let toKelvin = (value) => value + 273.15;
let toFahrenheit = (value) => (value * (9 / 5)) + 32;

module.exports = {
  toKelvin,
  toFahrenheit,
};

fahrenheit.js

'use strict';

let toCelsius = (value) => (value - 32) * (5 / 9);
let toKelvin = (value) => (value + 459.67) * (5 / 9);

module.exports = {
  toCelsius,
  toKelvin,
};

kelvin.js

'use strict';

let toCelsius = (value) => value - 273.15;
let toFahrenheit = (value) => 1.8 * toCelsius(value) + 32;

module.exports = {
  toCelsius,
  toFahrenheit,
};

You can see it running by installing it via npm

npm i -g thermo.js
thermo 10 -celsius
=> 10°C = 50.00°F = 283.15K

Is my implementation good? This is my first non-web JavaScript program. I want to make the code more idiomatic. I think I messed up some of ES6 variables declaration.


texts: Javascript Minesweeper (with Stack Snippets!)

texts:
As Stack Snippets are live on Code Review now, I wanted to do something quick in it as part of rolfl's challenge on meta. And when you make things quick, they probably get dirty. And when things get dirty, you refactor. And when you don't know how to refactor, you post it up for review.

So, as many of my previous questions has been about Minesweeper probabilities, what better thing to make than a Minesweeper game?

This minesweeper game does not have any probability-calculations or other cool stuff though, that will have to wait until version 2.0 :) It's not the multiplayer variant Minesweeper Flags either. Just plain old Minesweeper. I decided to go with the 'Intermediate' setting, i.e. 16 x 16 with 40 mines.

It has been a while since I did any real JS coding, but I don't consider myself a beginner in it.

By the way, don't be afraid if it says 'Kaboom' on your first click. It's a bug feature, not a feature bug.

Stack-Snippet with JS + HTML: (a slightly modified version can be found on github)

var elements = [];
var fields = [];
var allFields = [];

function showField(thisButton) {
  var thisX = Number(thisButton.attr('data-x'));
  var thisY = Number(thisButton.attr('data-y'));
  var button = fields[thisY][thisX];
  var number = Number(button.attr('data-value'));
  thisButton.attr('data-visible', true);
  if (button.attr('data-mine') === 'true') {
    button.text('X');
    alert('KABOOM!');
    allFields.forEach(function(entry) {
      entry.attr('disabled', true);
    });
  }
  else if (number === 0) {
    button.text(number);
    for (var xx = thisX - 1; xx <= thisX + 1; xx++) {
      for (var yy = thisY - 1; yy <= thisY + 1; yy++) {
        if (fields[yy] !== undefined && fields[yy][xx] !== undefined) {
          var innerButton = fields[yy][xx];
          if (innerButton.attr('data-visible') === 'false') {
            showField(innerButton);
          }
        }
      }
    }
  }
  else {
    button.text(number);
  }
}

var table = $('#board').find('tbody');
for (var y = 0; y < 16; y++) {
  var tr = $('
');
  var row = [];
  for (var x = 0; x < 16; x++) {
    var td = $('');
    var button = $('<button>').text('_').attr('data-value', 0)
     .attr('data-x', x).attr('data-y', y).attr('data-visible', false)
     .attr('data-mine', false)
     .on('click', function() {
       showField($(this));
    });
    td.append(button);
    tr.append(td);
    row.push(button);
    elements.push(button);
    allFields.push(button);
  }
  fields.push(row);
  table.append(tr);
}

// Generate mines
for (var mines = 0; mines < 40; mines++) {
  var random = Math.floor(Math.random() * elements.length);
  var field = elements[random];
  var thisX = Number(field.attr('data-x'));
  var thisY = Number(field.attr('data-y'));
  field.attr('data-mine', true);
  for (var xx = thisX - 1; xx <= thisX + 1; xx++) {
    for (var yy = thisY - 1; yy <= thisY + 1; yy++) {
      if (fields[yy] !== undefined && fields[yy][xx] !== undefined) {
        var innerButton = fields[yy][xx];
        var previous = Number(innerButton.attr('data-value'));
        innerButton.attr('data-value', previous + 1);
      }
    }
  }
  elements.splice(random, 1);
}

Primary concerns:

Is it a good idea to use data-* attributes to store the data? It kinda makes it quite easy to cheat...
Am I using the features of JQuery in a good way?
Any other comments welcome! Don't be afraid to hurt my feelings, I'm more of a Java guy anyway...


texts: Finding median of sub arrays taking too much time

texts:
I'm trying to solve a programming challenge where I have to find the median of given subarrays of an array. I have used std::vector's n_th element for this. But the evaluator fails some test cases as "time limit exceeded".

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

/*
In
6
2 4 5 3 1 6
3
1 6
2 4
3 3

Out
3
4
5

*/

int get_ceil(int length)
{
    if (length % 2 == 0)
    {
        return length/2;
    }
    else
    {
        return (length+1)/2;
    }

}

int get_median_of_subarray(std::vector<int> & full_array, int lo, int hi)
{

    std::vector<int>::const_iterator begin = full_array.begin() + lo;
    std::vector<int>::const_iterator end = full_array.begin() + hi + 1;
    std::vector<int> sub_array(begin, end);

    int median_pos = get_ceil(hi - lo + 1);
    std::nth_element (sub_array.begin(), sub_array.begin() + median_pos -1, sub_array.end());
    return sub_array[median_pos - 1];
}

int main()
{
    ios_base::sync_with_stdio(false);

    int array_size = 0;
    std::vector<int> input_array;

    cin >> array_size;

    for(int i = 0; i < array_size; i++)
    {
        int x;
        cin >> x;
        input_array.push_back(x);
    }

    int query_size = 0;
    cin >> query_size;

    int lo = 0;
    int hi = 0;

    for(int i = 0; i < query_size; i++)
    {
        cin >> lo >> hi;
        std::cout << get_median_of_subarray(input_array, --lo, --hi) << std::endl;
    }

    return 0;
}


texts:
I am constructing a binary tree. Let me know if this is a right way to do it. If not please tell me how to?? I could not find a proper link where constructing a general binary tree has been coded. Everywhere BST is coded.

  3
 / \
1   4
   / \
  2   5

This is the binary tree which i want to make.I should be able to do all the tree traversals.Simple stuff.

public class Binarytreenode
{
    public Binarytreenode left;
    public Binarytreenode right;
    public int data;

    public Binarytreenode(int data)
    {
        this.data=data;
    }

    public void printNode()
    {
        System.out.println(data);
    }

    public static void main(String ar[])
    {
        Binarytreenode root = new Binarytreenode(3);
        Binarytreenode n1 = new Binarytreenode(1);
        Binarytreenode n2 = new Binarytreenode(4);
        Binarytreenode n3 = new Binarytreenode(2);
        Binarytreenode n4 = new Binarytreenode(5);

        root.left = n1;
        root.right = n2;
        root.right.left = n3;
        root.right.right = n4;
    }
}


texts:
I wrote a short Haskell script to compress and decompress via the use of run length encoding.

The concept is simple enough, n equal items x in a row will be replaced by (n, x), decompressing is just the reverse.

For example:

> runLengthCompress "foooo barrr"
[(1,'f'),(4,'o'),(1,' '),(1,'b'),(1,'a'),(3,'r')]

As you can see the four consecutive o have been substituted by (4,'o')

About the code itself I fear I have written too little points (arguments) to my functions, hindering readability but I am not sure, maybe the lack of points makes it more readable, not less.

Also I feel like my areInverses function is already built-in into Haskell and that I am rebuilding the wheel with it.

Without further ado, here is the code:

import Data.List
import Control.Monad
import Control.Arrow

runLengthExpand :: [(Int, a)] -> [a]
runLengthExpand = concat . map (uncurry replicate)

runLengthCompress :: Eq a => [a] -> [(Int, a)]
runLengthCompress = (map (length &&& head)) . group

areInverses :: Eq b => (a -> b) -> (b -> a) -> [b] -> Bool
areInverses f g = all ((==) =<< f . g)

examples :: [[Int]]
examples = [ [3, 3, 3, 5, 5, 7, 1], [1,1,1,0,0,0,5] ]

main :: IO()
main = do
  print $ runLengthCompress "foooo barrr"
  print $ areInverses runLengthExpand runLengthCompress examples


texts:
I've made a very simple slideshow that works by appending and prepending images (on click and every 3 seconds). This is my first time trying to use classes or objects so any help would be great. I feel this could be a little verbose so I'd love any sort of feedback.

The user can click through the slideshow, but it also works on a timer of every 3 seconds.

 // Scroll through images on the homepage

 function IndexSlideshow() {

    // declare index page html elements

    var contentSlideshow = $('.content-slideshow'),
       slide = $('.slide'),
       body = $('body'),
       self = this;

    // append the first slide, fade in the newly bumped slide

    this.work = function() {
       $('.slide:first').fadeOut(200, function() {
          $(this).appendTo(contentSlideshow);
          $('.slide:first').hide().fadeIn(200);
       });
    }

    // show previous slide on click

    this.showPrev = function() {
       slide.click(function() {
          $(this).prependTo(contentSlideshow);
       });
    }

    // show next slide on click

    this.showNext = function() {
       slide.click(function() {
          self.work();
       });
    }

    // create an auto slide (slides every 3 seconds)

    this.auto = function() {
       var run;

       if (body.hasClass('home')) {
          run = setInterval(function() {
             self.work();
          }, 3000);

          // reset interval if they clicked an image

          slide.click(function() {
             clearInterval(run);
             run = setInterval(function() {
                self.work();
             }, 3000);
          });

       };

    }

 }

 var i = new IndexSlideshow();

 i.showNext();
 i.auto();


texts: Find index of '/s' before and after text in a char array

texts:
For the Arduino programming environment, let's say I have a string literal:

  char strlit[17] = "_ _ _  Sup  _ _  team?  _ _ _"

I would like to put brackets around the nth word and clear any brackets that may be around current words.

meaning that foo(strlit, 0) would return "_ _[Sup]_team?_ _ _"

and foo(strlit, 1) would return "_ _ _Sup _ [team?] _ _"

Right now the only way I know how to do this would be incrementing through the array, checking to see if the current char isspace() and the previous or next char isgraph()

Something like:

[code]...
char strlit[17] = "   Sup  team?   ";
Find_word_trim(&strlit,1);
...[code]

Where Find_word_trim looks like

     void Menu_Opt(char *line[17], int set)
     {
       int setno;
       bool on_set=false;
       int i = 0;
       while(line[i]!=NULL)
       if(line[i]=='[' || line[i]==']')
       {
         if (line[i]='[')
         {
           setno++;
         }
         line[i]=' ';
       }
       else if(isspace(line[i]) && isgraph(line[i+1])&&!on_set)
       {
         if(setno==set)
         {
           line[i]='[';
           on_set=true;
         }
         else
         {
           setno++;
         }
       }
       else if(isspace(line[i]) && isgraph(line[i-1])&&on_set)
       {
         line[i]=']';
       }
       i++;
     }

Does it. However, I feel like there's a faster way to solve the problem. Any input on how I should optimize or rewrite would be greatly appreciated. I'm ok with the assumption that my strlit will not have a [ or ] char naturally, however, bonus points if you can avoid that assumption


texts: What would you have done differently? How to approach this?

texts:
so as a beginner in Python, I've been utilizing CodeWars to practice everyday alongside my courses, been happy by the results so far, however, what I really am focusing on is the logical thinking side of things and "Thinking like a programmer". I got a question today on codewars that brought me here to ask. Although the end result of the code I wrote was a "PASS" and it worked out, I know for a fact there is a way to write shorter code using ITERATION for the same result.
The Question was to write a function that takes in a string and returns the string with numbers associated with the alphabetical position. My code is below. Again, it worked, but what would you have done differently? And how do I get into the habit of thinking differently to achieve cleaner code?
def alphabet_position(text):

    alphabet = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'}
    text = text.lower()
    mylist = []

for letter in text:
    if letter in alphabet:
        mylist.append(alphabet[letter])
    else:
        pass

return ' '.join(mylist)


texts:
I just started to learn React.js and decided to build on of the simpler projects from freeCodeCamp with it. I'm really interested in ways in which this code can be improved.

I can see at least two problems - two components with the exact same logic and different states and not working feature with scrolling to different sections based on href of a link pressed. While I will be able to fix the second one eventually, the first one is more about logic of the code.

So, my main concerns are the logic of the code and style of it. What should be fixed and how?

Here is a link to working code:

Codepen

class Contact extends React.Component {
  constructor() {
    super();
    this.state = {
      links: [
        "https://www.vk.com",
        "https://www.github.io",
        "https://codepen.io"
      ],

      icons: [
        "http://www.iconninja.com/files/16/107/688/vk-com-icon.png",
        "http://www.freeiconspng.com/uploads/git-github-hub-icon-25.png",
        "http://www.iconninja.com/files/695/496/986/black-codepen-icon.png"
      ]
    };
  }
  render() {
    const { links, icons } = this.state;
    let social = links.map((href, i) => {
      return (

      );
    });
    return
{social}
;
  }
}
class Portfolio extends React.Component {
  constructor() {
    super();
    this.state = {
      links: [
        "http://kiraburova.github.io/ModernLook/",
        "http://kiraburova.github.io/passion/",
        "http://kiraburova.github.io/singolo/",
        "https://kiraburova.github.io/Kafeinate/"
      ],

      images: [
        "https://image.ibb.co/chE8xv/1.png",
        "https://image.ibb.co/kR9K4a/2.png",
        "https://image.ibb.co/n9niVF/3.png",
        "https://image.ibb.co/i3PVAF/4.png"
      ]
    };
  }
  render() {
    const { links, images } = this.state;
    let gallery = links.map((href, i) => {
      return (

      );
    });
    return
{gallery}
;
  }
}
class About extends React.Component {
  constructor() {
    super();
    this.state = {
      name: "Name",
      text: "Hello! This is just a sample text"
    };
  }
  render() {
    return (

{this.state.name}

{this.state.text}

    );
  }
}
class Navigation extends React.Component {
  constructor() {
    super();
    this.state = {
      nav: ["About", "Portfolio", "Contact"]
    };
  }
  render() {
    let navigation = this.state.nav.map(item => {
      return {item};
    });
    return
{navigation}
;
  }
}
class App extends React.Component {
  render() {
    return (

        <Navigation />
        <About />
        <Portfolio />
        <Contact />

    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));


texts: Summation and product functions using functional paradigm

texts:
Below is the problem:

  Show that both summation and product are instances of a more general function, called accumulate, with the following signature:

def accumulate(combiner, start, n, term):
    """Return the result of combining the first n terms in a sequence."""
    "*** YOUR CODE HERE ***"

  Accumulate takes as arguments the same arguments term and n as summation and product, together with a combiner function (of two arguments) that specifies how the current term is to be combined with the accumulation of the preceding terms and a start value that specifies what base value to use to start the accumulation. Implement accumulate and show how summation and product can both be defined as simple calls to accumulate:

def summation_using_accumulate(n, term):
    """An implementation of summation using accumulate.

    >>> summation_using_accumulate(4, square)
    30
    """
    "*** YOUR CODE HERE ***"

def product_using_accumulate(n, term):
    """An implementation of product using accumulate.

    >>> product_using_accumulate(4, square)
    576
    """
    "*** YOUR CODE HERE ***"

For which, solution is mentioned below:

from operator import add
from operator import mul

def square(x):
    """ Retrun x squared"""
    return x * x

def accumulate(combiner, start, n, term):
    """Return the result of combining the first n terms in a sequence."""
    if n == 0:
        return start
    else:
        start = combiner(term(n), start)
        return accumulate(combiner, start, n-1, term)

def summation_using_accumulate(n, term):
    """An implementation of summation using accumulate.

    >>> summation_using_accumulate(4, square)
    30
    """
    assert n >= 0
    return accumulate(add, 0, n, term)

def product_using_accumulate(n, term):
    """An implementation of product using accumulate.

    >>> product_using_accumulate(4, square)
    576
    """
    assert n > 0
    return  accumulate(mul, 1, n, term)

result =  summation_using_accumulate(4, square)
print(result)
result = product_using_accumulate(3, square)
print(result)

Please let me know if this program can be improved further using functional paradigm and the DRY principle.


texts: Find contiguous integers with a given sum

texts:
Introduction

This question was asked in a technical interview, I am looking for some feedback on my solution.

Given a list of integers and a number K, return which contiguous
elements of the list sum to K.  For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it
should return [2, 3, 4].

The Ask

My solution works with my test cases, but I would like feedback on how others would approach the problem and where my code could be altered to improve efficiency and runtime.  Currently, I have a nested for loop and I believe my solution is O(n2).

Solution

def contigSum(nums, k):

    for i, num in enumerate(nums):
        accum = 0
        result = []
        # print(f'Current index = {i}')
        # print(f'Starting value = {num}')

        for val in nums[i:len(nums)]:
            # print(f'accum = {accum}')
            result.append(val)
            # print(f'accum = {accum} + {val}')
            accum += val

            if accum == k:
                print(f'{result} = {k}')
                return 0
            # else:
                # print(f'accum = {accum}')

    print('No match found')
    return 1

Test Cases

nums0 = []
k0 = None
contigSum(nums0, k0)

nums6 = [1, 2, 3]
k6 = 99
contigSum(nums6, k6)

nums1 = [1, 2, 3, 4, 5]
k1 = 9
contigSum(nums1, k1)

nums2 = [-1, -2, -3]
k2 = -6
contigSum(nums2, k2)

nums4 = [5, 2, 6, 11, 284, -25, -2, 11]
k4 = 9
contigSum(nums4, k4)

nums5 = [10, 9, 7, 6, 5, 4, 3, 2 ,1]
k5 = 20
contigSum(nums5, k5)