Sums of columns and diagonals of a matrix I made a simple matrix program that prints some data..I want to know how to reduce amount of lines with some functions or whatever, because there is so much if-s,and for loops.

Tried to make functions but almost every for loop is different, so that did not work.

#include <stdio.h>
main()
{
    int i,j,m,n,sMain,sAnti,sCol,sMainUp,sMainDown,sAntiUp,sAntiDown;
    int arr[30][30];

    printf("What dimensions of matrix you want?(1 number) ");
    scanf("%d",&m);
    n = m;

    for(i = 0; i < m; i++){
        for(j = 0; j < n; j++){
            printf("Type elements: ");
            printf("Element[%d,%d]: ",i,j);
            scanf("%d",&arr[i][j]);
        }
    }
    for(i = 0; i < m; i++){
        for(j = 0; j < n; j++){
            printf("%d ",arr[i][j]);
        }
        printf("\n");
    }
    sMain = 0;
    sAnti = 0;
    sMainUp = 0;
    sMainDown = 0;
    sAntiUp = 0;
    sAntiDown = 0;

    for(i = 0; i < m; i++){
        for(j = 0; j < n; j++){
            if(i == j){
                sMain += arr[i][j];
            }
            if((i + j) == (n - 1)){
                sAnti += arr[i][j];
            }
            if(i < j){
                sMainUp += arr[i][j];
            }
            if(i > j){
                sMainDown += arr[i][j];
            }
            if((i + j) < (n - 1)){
                sAntiUp += arr[i][j];
            }
            if((i + j) > (n - 1)){
                sAntiDown += arr[i][j];
            }
        }
    }
    sCol = 0;
    printf("Sum of what column you want? ");
    scanf("%d",&j);
    for(i = 0; i < m; i++){
        sCol += arr[i][j];
    }
    printf("Sum of main diagonal: %d.\n",sMain);
    printf("Sum of anti(counter) diagonal: %d.\n",sAnti);
    printf("Sum above main diagonal: %d.\n",sMainUp);
    printf("Sum under main diagonal: %d.\n",sMainDown);
    printf("Sum above anti diagonal: %d.\n",sAntiUp);
    printf("Sum under anti diagonal: %d.\n",sAntiDown);
    printf("Sum of %d. column is: %d.",j,sCol);

}

Use Symbolic Constants Rather Than Numeric Constants
In most programming languages there is a way to define symbolic constants for numbers which makes the code more readable and easier to maintain. When raw numbers are used in code they are sometimes called Magic Numbers. Using Magic Numbers is generally considered a poor programming practice as discussed in this stackoverflow question.

While the number 30 isn't quite a magic number since it is used as the maximum dimensions for the arrays in the matrix, it would be beneficial to anyone that needs to read or maintain the code to define symbolic constants for it. This would allow anyone who needs to edit the code to change the maximum dimensions to change 1 number in 1 place.

In C this would be:

#define MAXIMUM_MATRIX_DIMENSION 30

and in C++ this would be:

const int MAXIMUM_MATRIX_DIMENSION = 30;

Then the integer array arr could be declared as:

int arr[MAXIMUM_MATRIX_DIMENSION][MAXIMUM_MATRIX_DIMENSION];

It then becomes very easy to change the maximum size of the matrix by only changing one line.

Meaningful Variable Names
The code might be easier to read if the variables m and n had more meaningful names, m could be matrixDimension. It's not really clear what n since it could also be `matrixDimension.

The code might also be more readable if the variable arr had a more meaningful name, perhaps baseMatrix.

Declare Variables as Needed
The C programming language now allows variables to be created where they are needed, for instance the variables i and j could be created within the for loops

    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            printf("Type elements: ");
            printf("Element[%d,%d]: ",i,j);
            scanf("%d",&arr[i][j]);
        }
    }

The variables used to contain the sums should also be declared where they are initialized.

Error Checking on Input
It is always better to check user input before using it to perform actions in the code. For example checking the size of the dimensions before using it as a control value in the previous loop. If the user enters a number less than 1 or greater than 29 the program will experience undefined behavior and may crash. If the number is 0 or less the loops will never execute and if the number is greater than 29 matrix values will be written to memory that hasn't been allocated to the arrays.

    m = -1;
    while (m < 1 or m >= MAXIMUM_MATRIX_DIMENSION)
    {
        printf("What dimensions of matrix you want?(1 integer number greater than 0 and less than %d) ", MAXIMUM_MATRIX_DIMENSION);
        scanf("%d",&m);
    }

Complexity
The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.

There is also a programming principle called the Single Responsibility Principe that applies here. The Single Responsibility Principle states:

  Every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

There are at least 4 possible functions in main() and possibly more. Each of the outer for loops is a good candidate for a function. The possible functions are:

Get the dimensions of the matrix
Get the individual values of the matrix
Print the matrix
Calculate and report the sums of the matrix columns, rows and diagonals (this could be 2 functions).


Initializing a multidimensional with many default values I need to create a \${n} \times {n}\$ multidimensional array filled with default values.

Right now, I'm using this code:

//--- how many columns?
var colNumber = 10;
//--- how many rows?
var rowNumber = 20;

//--- default value
var defaultValue = "default";

var defRow = [];
var defaultArray = [];

for(var x = 0; x < colNumber; x++){
    defRow.push(defaultValue);
}
for(var x = 0; x < rowNumber; x++){
    defaultArray.push(defRow);
}
console.log(defaultArray);

find fiddle here

Is there any better approach to do this?

Yes, there's a better approach. The problem you have here is that each row is the same value, so a change to one row will be seen in all rows. For example, I added the following to your code to illustrate this:

console.log(JSON.stringify(defaultArray));
defaultArray[5][5] = "Fubar";
console.log(JSON.stringify(defaultArray));

This should change the value in the middle of the 'matrix', but instead the result is:

"[["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"],
["default","default","default","default","default","Fubar","default","default","default","default"]]"

You need to have a fresh array instance for each row.

Even though it is mundane, the logical way to do it is:

var defaultArray = [];

for(var x = 0; x < rowNumber; x++){
    var defRow = [];
    for(var y = 0; y < colNumber; y++){
        defRow.push(defaultValue);
    }
    defaultArray.push(defRow);
}

Edit: Based on the benchmarks for my browser (Firefox), a decrementing while-loop is much faster than alternatives. I would use:

var defaultArray = [];

for(var row = rowNumber - 1; row >= 0; row--){
    var defRow = [];
    for(var col = colNumber - 1; col >= 0; col--){
        defRow[col] = defaultValue;
    }
    defaultArray[row] = defRow);
}

By working backwards over the array you reduce the amount of space allocations that happen as the array grows. Here's the results of that benchmark for me:


Inputs equality check using jQuery without plugins I tried creating a function to check for a match between two email fields, let's say EMAIL and CONFIRM email. I absolutely try to avoid jQuery validate. It is not worth it for a single field. For the rest I use HTML5 properties like required, pattern, etc. and it works well. This is why I want to deliver seamless experience with setCustomValidity.

Here's my working code, which of course, may be improved by someone with more experience in JS and jQuery.

HTML

<input type="email" name="addr1" id="addr1" required>
<input type="email" name="addr2" data-equal-to="addr1" data-msg-error="Emails do not match." required>

jQuery

$('[data-equal-to]').on('blur', function() {
    var to_confirm = $(this),
        to_equal = $('#' + to_confirm.data('equal-to'));
    if (to_confirm.val() != to_equal.val()) {
        this.setCustomValidity(to_confirm.data('msg-error'));
    }
    else {
        this.setCustomValidity('');
    }
    to_equal.one('blur', function() {
        to_confirm.trigger('blur');
    });
});

Here are the problems I encountered:

I was using '.bind'. It turns out its deprecated. Then I started using
'.on'
I forgot the last 3 lines. There was no event listener for the
first email input, so I was only checking the CONFIRM input. This
got fixed.
I was using 'input' instead of 'blur'. 'input' provided
real-time validation (as you type) which is good, but consumed too
much in my opinion. Also it showed errors while you are still typing
(and haven't finished), so some users may find it confusing. The only
drawback of 'blur' I find is that feedback on validity comes after
you click another element (unfocus).
Binding on every input a new listener to 'to_equal' turned out to be a bad idea. I ended up with multiple listeners, causing the browser to crash. I found out that '.one' exists, which should do the same as .off before .on (or maybe after?)

My question is - can this little script be improved in terms of speed, or using less event listeners? Is there a case I haven't thought of? I searched a lot to find a good no plugin solution, but with no luck. Also I insist on using data- attributes to provide the matching id + the error message (as the website is multi-lingual and its easier to modify HTML than JS on the fly).

I think that having the 'perfect' version of this script will help a lot of people, especially in confirm email/password (for passwords case sensitivity must be in mind!) aspect.

Switch to the native DOM methods like getElementById, which is orders of magnitude faster and you can keep input:

$('[data-equal-to]').on('input', function() {
  var target = document.getElementById(this.dataset.equalTo);
  var isEqual = !target || target.value == this.value;
  this.setCustomValidity(isEqual ? '' : this.dataset.msgError);
});

You can also debounce the verification by 200ms, for example:

;(function() {
  var timeout;

  function validateEquality(element) {
    var target = document.getElementById(element.dataset.equalTo);
    var isEqual = !target || target.value == element.value;
    element.setCustomValidity(isEqual ? '' : element.dataset.msgError);
  }

  $('[data-equal-to]').on({
    input: function() {
      clearTimeout(timeout);
      timeout = setTimeout(validateEquality, 200, this);
    }),
    blur: function() {
      clearTimeout(timeout);
      validateEquality(this);
    }),
  });
})();

You can also make this a jQuery plugin.

As for mirroring the check for the target element, the preferable approach is to explicitly declare data-equal-to attribute on both input elements that points to the other one. But you can also do it implicitly by adding equalOf expando property pointing to the linked element so you can re-triggering input event on it:

$('[data-equal-to]')
  .on('input', function() {
    var target = document.getElementById(this.dataset.equalTo);
    var isEqual = !target || target.value == this.value;
    this.setCustomValidity(isEqual ? '' : this.dataset.msgError);
  })
  .map(function() {
    var target = document.getElementById(this.dataset.equalTo);
    target.equalOf = this;
    return target;
  })
  .on('input', function() {
    $(target.equalOf).trigger('input');
  });


Scoring each letter in a word I've made code that scores each letter in a word you input according to the table below:

  1: AEILNORSTU
  2: DG
  3: BCMP
  4: FHVWY
  5: K
  8: JX
  10: QZ

I appreciate any feedback, but the main reason of this post concerns the charPoint method. Should I rewrite this using switch? Or is there an even better way to write it?

package exercicios;

import com.sun.org.apache.xalan.internal.xsltc.compiler.Pattern;

import acm.program.*;

public class Ex5 extends ConsoleProgram{

    public void run(){
        String word = readLine("Enter a word: ");
        println(wordScore(word));

    }

    private int wordScore(String word){
        int score = 0;

        for (int i = 0; i < word.length(); i++){
            score += charPoint(word.substring(i, i+1));
        }

        return score;
    }
    private int charPoint(String ch){

        if (ch.matches("[AEILNORSTU]")){
            return 1;
        } else if (ch.matches("[DG]")){
            return 2;
        } else if (ch.matches("[BCMP]")){
            return 3;
        } else if (ch.matches("[FHVWY]")){
            return 4;
        } else if (ch.matches("[K]")){
            return 5;
        } else if (ch.matches("[JX]")){
            return 8;
        } else if (ch.matches("[QZ]")){
            return 10;
        } else return 0;

    }
}

It may be simpler (and definietly faster when it comes to larger data) to create a private static final Map<Character, Integer> with LETTER -> VALUE mapping prior to any calculations. Besides repeating the put many times when constructing it, you can be even cooler although less readable IMO:

private static final Map<Character, Integer> LETTER_TO_POINT;

static {
    final Map<Character, Integer> letterToPoint = new HashMap<>();
    // letterToPoint.put('A', 1);
    // letterToPoint.put('B', 3);
    // booooooring :-(

    BiConsumer<String, Integer> rememberPointValues = (letters, points) -> {
        for (char letter : letters.toCharArray()) {
            letterToPoint.put(letter, points);
        }
    };
    rememberPointValues.accept("AEILNORSTU", 1);
    rememberPointValues.accept("DG", 2);
    rememberPointValues.accept("BCMP", 3);
    rememberPointValues.accept("FHVWY", 4);
    rememberPointValues.accept("K", 5);
    rememberPointValues.accept("JX", 8);
    rememberPointValues.accept("QZ", 10);
    LETTER_TO_POINT = Collections.unmodifiableMap(letterToPoint);
}

Once you have that, the charPoint method is much simpler:

private int charPoint(char ch) {
  return LETTER_TO_POINT.get(ch);
}

Moreover, you can iterate over the letters in the string like that:

for (char letter : word.toCharArray()) {
  score += charPoint(letter);
}


Real time metal prices and conversion fro USD to MXN using BeautifulSoup updated version from bs4 import BeautifulSoup
import requests
import re
import datetime

metal_translation = {"Aluminium": "Aluminio", "Copper": "Cobre", "Zinc": "Zinc", "Nickel": "Níquel", "Lead": "Plomo", "Tin": "Estaño",
                     "Aluminium Alloy": "Aleación de Aluminio", "Cobalt": "Cobalto", "Gold*": "Oro*", "Silver*": "Plata*",
                     "Steel Scrap**": "Chatarra de Acero", "NASAAC": "NASAAC", "Steel Rebar**": "Varilla de Acero"}

def get_metal_values():
    names = []
    prices = []
    response = requests.get('https://www.lme.com/')
    response.raise_for_status()
    metals = response.text
    soup = BeautifulSoup(metals, 'lxml')
    metal_table = soup.find("table", attrs={"class": "ring-times"})
    metal_table_names, metal_table_prices = metal_table.tbody.find_all("th"), metal_table.tbody.find_all("td")
    for name in metal_table_names:
        names.append(name.text.replace("LME ", ""))
    for price in metal_table_prices:
        prices.append(price.text.strip())
    return names, prices

def get_peso_conversion():
    response = requests.get('https://themoneyconverter.com/USD/MXN')
    response.raise_for_status()
    peso = response.text
    soup1 = BeautifulSoup(peso, 'lxml')
    conversion = soup1.find("div", class_="cc-result").text
    rate = re.search("\d{2}\.\d{4}", conversion).group()
    return rate

def get_time():
    d = datetime.datetime.now()
    date_time = d.strftime("%d/%m/%Y | %H:%M:%S")
    return date_time

def convert_values():
    names, prices = get_metal_values()
    rate = get_peso_conversion()
    for k, v in zip(names, prices):
        v = (float(v.replace(",", "")) * float(rate))
        print(f'{metal_translation[k]}: {v:.2f} $')

def program_run():
    print("Metal Prices by ETHAN HETRICK")
    print("================================================")
    print(f'{get_time()} | 1 USD = {get_peso_conversion()} MXN\n')
    print("Precios de metales de London Metal Exchange: (Por tonelada métrica, *Por onza Troy)\n")
    convert_values()
    print("================================================")

program_run()

Example Output:
input("\nEscribe 'x' para terminar.\n")

Metal Prices by ETHAN HETRICK
================================================
26/06/2020 | 21:59:00 | 1 USD = 23.0622 MXN

Precios de metales de London Metal Exchange: (Por tonelada métrica, *Por onza Troy)

Aluminio: 36484.40 $
Cobre: 138038.80 $
Zinc: 47438.95 $
Níquel: 293097.50 $
Plomo: 41004.59 $
Estaño: 391826.78 $
Aleación de Aluminio: 27997.51 $
NASAAC: 27444.02 $
Cobalto: 657272.70 $
Oro*: 40711.70 $
Plata*: 410.74 $
Chatarra de Acero: 6065.36 $
Varilla de Acero: 9720.72 $
================================================

Escribe 'x' para terminar.

This is an updated version of my code from a previous post of mine thanks to @Reinderien
My fiances father owns a metal recycling business in Mexico City, Mexico which requires him to do a lot of calculations when negotiating with clients. Since he was doing this by hand, I decided to automate this for him. I used London Metal Exchange, which is his preferred site to get the current prices, for the metal prices and also got the exchange rate for USD to MXN and applied that as well. I also needed to translate everything to spanish so I used a dictionary. This is my first time utilizing webscraping and the datetime module so any advice to make this program run more efficiently or make the code more concise is much appreciated!

I think it would be better to handle the API stuff to convert prices using a Python package like CurrencyConverter.
The site that you are using currently might be down some day or may blacklist your IP because of the many requests that your code is making to convert the prices.
Also, your code seems to be better converted to a Scrapy project if you are interested in web scraping. Scrapy Tutorial by ScrappingHub


A simple AngularJS application for counting the number of gallons of paint I created a simple Angular JS application for calculation gallons of paint needed to paint the ceiling of a room.

I assume one gallon covers 350 square feet and use it as a constant.
Also, I round up a counting of the gallons to the next whole number.
Now my code seems to me too simple).

I will be grateful for advice as it is possible to complicate this task with the use of AngularJS or next version of Angular.

angular.module('my-App', [])
 .controller('paintCalculatorController', function($scope){
  $scope.length = 0;
  $scope.width = 0;
  const squareFeetForOneGallon = 350;
  $scope.square = function(){
   return $scope.length * $scope.width;
  }
  $scope.countGallon = function(){
   return Math.ceil($scope.length * $scope.width / squareFeetForOneGallon);
  }
 });
form{
 background-color: #f1f1f1;
 border-radius: 5px;
 }
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Room ceiling area

  <form class="inline-form mt-3 py-3">
  Length:
  <input style="width:90px" type="number" ng-model="length" value="" name="" min="0" oninput="validity.valid||(value='');">
   feet
   X
  Width :
  <input style="width:90px" type="number" ng-model="width" value="" name="" min="0" oninput="validity.valid||(value='');">
   feet
    </form>

You will need to purchase {{countGallon()}} gallons of
 paint to cover {{square()}} square feet.

Feedback
The code looks pretty good, and thus I only found a few things that I could change (listed below). I like how the bootstrap text-center class can be applied once to affect all sub-elements.
Suggestions
CSS
Move the in-line styles to the stylesheet to reduce redundancy - e.g. the number inputs have a specific width, which can be put into a CSS rule-set, like this example:
input[type="number"] {
  width: 90px;
}

Or apply a class name to those elements and utilize that class name in the selector. Also, the width of the container (i.e. 500px) can be moved into a rule-set.
JavaScript
Declaring the Constant
The idiomatic way of declaring a constant in AngularJS is to use .constant() and use dependency injection to inject that constant in the controller.
.constant('SQUARE_FEET_FOR_ONE_GALLON', 350)

Then that value will be available for injection in the controller (this example uses the implicit format:
.controller('paintCalculatorController', function($scope, SQUARE_FEET_FOR_ONE_GALLON){

If nobody else is planning to work on this small amount of code with you, then using a plain JavaScript constant should be fine.
Slight redundancy
Gerrit0 is correct in the comment: "maybe using $scope.square in $scope.countGallon"
The function countGallon() can be updated to updated to utilize the count() function. The formula for the square footage likely won't change anytime soon, but if it did, then that could be updated in a single place instead of both places. This complies with the Don't Repeat Yourself principle.
return Math.ceil($scope.count() / squareFeetForOneGallon);


Web Scraping Dynamically Generated Content Python This is a small web scraping project I made in 2 hours that targets the website remote.co . I am looking forward for improvements in my code. I know about the inconsistency with the WebDriverWait and time.sleep() waits, but when I used the WebDriverWait to wait until the load_more button was clickable and ran the program selenium crashed my webdriver window and continuously spammed my terminal window with 20-30 lines of seemingly useless text.

import scrapy
from selenium import webdriver
from selenium.common.exceptions import ElementNotInteractableException
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep

class ScrapeRemote(scrapy.Spider):
    name = 'jobs'
    start_urls = [f'https://remote.co/remote-jobs/search/?search_keywords={job_title}']

    job_title = input('Enter your desired position: ').replace(' ', '+')

    def __init__(self):
        self.driver = webdriver.Chrome(r'C:\Users\leagu\chromedriver.exe')

    def parse(self, response):
        self.driver.get(response.url)

        try:
            load_more = WebDriverWait(self.driver, 10).until(
                EC.visibility_of_element_located((By.XPATH, '/html/body/main/div[2]/div/div[1]/div[3]/div/div/a'))
                )
        except TimeoutException:
            self.log("Timeout - Couldn't load the page!")

        while True:
            try:
                sleep(1.5)
                load_more = self.driver.find_element_by_css_selector('a.load_more_jobs')
                load_more.click()
            except (ElementNotInteractableException, ElementClickInterceptedException):
                try:
                    close_button = WebDriverWait(self.driver, 6).until(
                        EC.element_to_be_clickable((By.CSS_SELECTOR, '#om-oqulaezshgjig4mgnmcn-optin > div > button'))
                        )
                    close_button.click()
                except TimeoutException:
                    self.log('Reached Bottom Of The Page!')
                    break

        selector = scrapy.selector.Selector(text=self.driver.page_source)
        listings = selector.css('li.job_listing').getall()

        for listing in listings:
            selector = scrapy.selector.Selector(text=listing)
            position = selector.css('div.position h3::text').get()
            company = selector.css('div.company strong::text').get()
            more_information = selector.css('a::attr(href)').get()
            yield {
                'position': position,
                'company': company,
                'more_information': more_information
            }

        self.driver.close()

Combined imports

from selenium.common.exceptions import ElementNotInteractableException
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import TimeoutException

should be

from selenium.common.exceptions import (
    ElementNotInteractableException,
    NoSuchElementException,
    ElementClickInterceptedException,
    TimeoutException,
)

Input-in-static

This:

job_title = input('Enter your desired position: ').replace(' ', '+')

creeps me out. I don't know a lot about scrapy, but see if you can initialize job_title in the constructor instead of as a static. What if this class were to be imported once and used twice, each with a different job title?

Hard-coded paths

This:

'C:\Users\leagu\chromedriver.exe'

should be pulled out into a constant, or better yet, an environmental parameter, command-line argument or configuration file parameter. Surely a user of yours who downloads your script will not be named leagu.

XPath

/html/body/main/div[2]/div/div[1]/div[3]/div/div/a

is extremely fragile and opaque. I loaded the remote.co search results, and a better selector - mind you, this is CSS and not XPath - is

div.card > div.card-body > div.card > div.card-body > a.card

You should not start from the root element, and you should attempt to use classes and IDs where possible. This markup is kind of a mess and so meaningful paths are hard to form.

Swallowing exceptions

You do this:

    except TimeoutException:
        self.log("Timeout - Couldn't load the page!")

but then continue with the rest of the method? Would you not want to re-throw, or at least return?

Non-guaranteed close

This:

self.driver.close()

will be skipped if there is any uncaught exception. First of all, I don't think the driver should be closed in parse, or else the class effectively can only support one invocation of parse. Implement __enter__ and __exit__, and call driver.close() in __exit__. Have the instantiator of ScrapeRemote use it in a with-block.


Find the largest exponent x such that p^x evenly divides n Write a method getExponent(n, p) that returns the largest exponent
  x such that px evenly divides n. If p ≤ 1 the method should return -1.

  getExponent(162, 3) returns 4 because 162 = 21∙ 34, therefore the value of x here is 4.
  if n is 27 and p is 3, return 3 because 33 divides 27 evenly but 34 does not.
  if n is 28 and p is 3, return 0 because 30 divides 28 evenly but 31 does not.
  if n is 280 and p is 7, return 1 because 71 divides 280 evenly but 72 does not.
  if n is -250 and p is 5, return 3 because 53 divides -250 evenly but 54 does not.`
  if n is 18 and p is 1, return -1 because if p <= 1 the function returns -1.
  if n is 128 and p is 4, return 3 because 43 divides 128 evenly but 44 does not.

I wrote following code to test that result

public class Exponent {

public static void main(String args[]) {
    int n = 27;
    int p = 3;
    System.out.println("result is: " + getExponent(n, p));
}

public static int getExponent(int n, int p) {
    int count = 0;
    if (p <= 1) {
        count = -1;
    } else {
        boolean status = true;
        while (status) {
            if (n % p == 0) {
                count++;
                n = n / p;
            } else {
                status = false;
                break;
            }
        }
    }

    return count;
}
}

I checked whether n is divisible by p or not. If divisible, then increment count and return count. Is this the right way to do that?

I would do an "early exit" in the case \$ p \le 1 \$ and
save an indentation level for the "main case":

if (p <= 1) {
    return -1;
}

The status variable is not needed, the while-loop can be
simplified to

int count = 0;
while (n % p == 0) {
    count++;
    n = n / p;
}

Your program should check if the input number \$ n \$
is zero, otherwise it will run into an infinite loop in that case.


Using BufferedReader to read lines of a file into a list To help improve my proficiency with Java, I would like to know how should I close these FileReaders as I have come across multiple answers, and what could I do better with this block of code?

/**
 * Returns a Vector<String> object that that can be parsed into classes.
 * The file arugment must specify a realative or aboustle adress to the file.
 * @param file to read
 * @return
 */
public static ArrayList<String> read(File file) {

    ArrayList<String> data = new ArrayList<String>();

    String lineRead;

    try {

        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        while ( (lineRead = br.readLine()) != null ) {
                data.add(lineRead);
        }

        br.close();
        fr.close();

    } catch(IOException e) {
        e.printStackTrace();
    }

    return data;
}

Since Java 7, you can make use of try-with-resources, which would change the implementation to:

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    while ((lineRead = br.readLine()) != null) {
        data.add(lineRead);
    }
} catch (IOException e) {
    ...
}

Some other tips:

Your documentation is not telling the truth and incomplete, you have to add some return documentation. Also, for parameters, the first string represents the name, and what follows is the explanation. So it should be more like e.g. @param file the file to read all lines from.
Return the interface instead of the implementation, i.e. return List instead of ArrayList, which means you can always change the implementation.
Never just print the stack trace, wrap and throw an (unchecked) exception or log. For more information as to why, see why printStackTrace is considered bad practice. In case you want to propagate the exception nonetheless, you can wrap it in another exception, e.g.:

try {
    ...
} catch (IOException e) {
    throw new UncheckedIOException(e);
}

This example may be used when the method this code is executed in does not declare to throw a checked Exception. But it all depends on the case at hand.

BufferedReader has a lines method returning all String lines as a stream. With this, you could also implement it as follows:

return br.lines().collect(toList());

I statically imported Collectors#toList. Notice how this results in a List and not an ArrayList.


Exception handling across functions I have three functions for building, applying, and plotting filters:

Build a filter:

def filter_build(frequency, sample_rate, filter_type, filter_order):
    nyq = 0.5 * sample_rate

    if filter_type == 'bandpass':
        try:
            normal_cutoff = (frequency[0] / nyq, frequency[1] / nyq)
        except Exception as e:
            print("Must provide tuple of frequency ranges for a bandpass filter")
            raise
    else:
        try:
            normal_cutoff = frequency / nyq
        except Exception as e:
            print("Must provide a single frequency value for this filter type")
            raise

    b, a = butter(filter_order, normal_cutoff, btype=filter_type, analog=False)

    return b, a

Apply filter:

def filter(signal, frequency, sample_rate, filter_type, filter_order=2):
    try:
        b, a = filter_build(frequency, sample_rate, filter_type, filter_order)
    except:
        print("Error when creating filter")
        return None

    filtered = filtfilt(b, a, signal)
    return filtered

Plotting the filter response:

def plot_filter_response(frequency, sample_rate, filter_type, filter_order=2):

    try:
        b, a = filter_build(frequency, sample_rate, filter_type, filter_order)
    except:
        print("Error when creating filter")
        return None

    w, h = freqz(b, a, worN=8000)
    plt.subplot(2, 1, 1)
    plt.plot(0.5*sample_rate*w/np.pi, np.abs(h), 'b')
    plt.xlim(0, 0.5*sample_rate)
    plt.title("Filter Frequency Response")
    plt.xlabel('Frequency (Hz)')
    plt.grid()

    if filter_type == 'bandpass':
        for i in range(len(frequency)):
            plt.axvline(frequency[i], color='k')
            plt.plot(frequency[i], 0.5*np.sqrt(2), 'ko')
    else:
        plt.axvline(frequency, color='k')
        plt.plot(frequency, 0.5*np.sqrt(2), 'ko')

    plt.show()

Everything appears to be working, but I dont think I'm handling exceptions correctly/efficiently.

For example, in filter() and plot_filter_response() I have the exact same try block, which feels redundant

The purpose of the try blocks (in all 3 functions) is to provide an easily understood error message if building a filter fails. The primary reason for this happening (that I can foresee) is if someone specifies a bandpass filter and only provides a single frequency cutoff, or if someone wants a lowpass filter but accidentally provides a tuple of 2 frequencies

Is there a way to remove the redundant try blocks, so that if a filter is mis-specified, then filter_build() will raise the error and stop any other lines of code from running?

A related issue is my inclusion of Return None in the latter 2 functions. Is there a way to remove those? If I remove them, then currently if filter_build() fails, the rest of the plotting code (or filtfilt) still gets executed, which runs into more problems. Ideally I want the functions to just exit if filter_build() doesn't return correctly

Your code is buggy due to you guarding against Exception, rather than a more specific exception.
This can lead to you saying a division by zero error is actually due to the user not passing in a number.

From this you have the following choices:

Change the errors to your own errors, whilst reducing the amount of errors you guard against in your try-excepts.

This would make filter_build look more like:

def filter_build(frequency, sample_rate, filter_type, filter_order):
    nyq = 0.5 * sample_rate

    if filter_type == 'bandpass':
        try:
            normal_cutoff = (frequency[0] / nyq, frequency[1] / nyq)
        except TypeError:
            raise ValueError("Must provide tuple of frequency ranges for a bandpass filter")
    else:
        try:
            normal_cutoff = frequency / nyq
        except TypeError:
            raise ValueError("Must provide a single frequency value for this filter type")

    return butter(filter_order, normal_cutoff, btype=filter_type, analog=False)

This keeps the entire error stack, and makes debugging the code much easier, whilst keeping your error messages.
But, you may want to change your approach, as you say you expect a tuple, rather than any indexable type.
And so you could use the LBYL approach of:

def filter_build(frequency, sample_rate, filter_type, filter_order):
    nyq = 0.5 * sample_rate

    if filter_type == 'bandpass':
        if not isinstance(frequency, tuple):
            raise ValueError("Must provide tuple of frequency ranges for a bandpass filter")
        normal_cutoff = (frequency[0] / nyq, frequency[1] / nyq)
    else:
        if not isinstance(frequency, (float, int)):
            raise ValueError("Must provide a single frequency value for this filter type")
        normal_cutoff = frequency / nyq

    return butter(filter_order, normal_cutoff, btype=filter_type, analog=False)

However, you could always remove all the try-excepts, and just leave the default Python error messages.
This can look like:

def filter_build(frequency, sample_rate, filter_type, filter_order):
    nyq = 0.5 * sample_rate
    if filter_type == 'bandpass':
        normal_cutoff = (frequency[0] / nyq, frequency[1] / nyq)
    else:
        normal_cutoff = frequency / nyq
    return butter(filter_order, normal_cutoff, btype=filter_type, analog=False)

I personally don't raise custom errors in most of my code, and so use the last option mostly.
I think Python's errors are pretty good, and I'm kinda lazy.
But all three options above are good.
You need to decide how you'll handle your errors.
You want to either do no handling, and your program just exits with the error.
Or you want to handle the error and display the actual error.
To do the latter should instead look like:

import traceback

def filter(signal, frequency, sample_rate, filter_type, filter_order=2):
    try:
        b, a = filter_build(frequency, sample_rate, filter_type, filter_order)
    except Exception:
        traceback.print_exc()
        return None
    return filtfilt(b, a, signal)

I'd highly recommend that you don't do the above.
Maybe you have a usecase where it's good.
But in almost all cases, it's better to remove the try-except, and for your program to exit.

If I were writing the above two functions I'd use the following:

def filter_build(frequency, sample_rate, filter_type, filter_order):
    nyq = 0.5 * sample_rate
    if filter_type == 'bandpass':
        normal_cutoff = (frequency[0] / nyq, frequency[1] / nyq)
    else:
        normal_cutoff = frequency / nyq
    return butter(filter_order, normal_cutoff, btype=filter_type, analog=False)

def filter(signal, frequency, sample_rate, filter_type, filter_order=2):
    b, a = filter_build(frequency, sample_rate, filter_type, filter_order)
    return filtfilt(b, a, signal)


Free time calculator I started learning Python 2 about a week ago, using Codecademy and Stack Overflow answers to help me learn. I wrote a code to calculate the user's free time based on user sleep and work time. It also lets the user decide whether to see percentage of free time. It's not fancy; I never intend to actually use it. It works the way I want it to.

I'm looking for feedback on how I wrote this code. What should I have done differently?

print "The program is operating."

def sleep(time):
  sleep_hours = float(raw_input("How many hours do you sleep a night?: "))
  return time - sleep_hours

def work(time):
 work_hours = float(raw_input("How many hours do you work each weekday?: "))
 time -= work_hours
 return time

def see_percent():
  reply = raw_input("Would you like to know the percent of your waking time is free time? (Y/N): ").lower()
  if reply == "y":
    print percent_round + "%."
  elif reply == "n":
    print "Okay"
  else:
    print "Y/N means enter a 'Y' for yes or a 'N' for no."

time = 24.
time_minus_sleep = sleep(time)
time_minus_work = work(time_minus_sleep)
waking_time = time_minus_sleep
percent_free = str(time_minus_work / waking_time * 100)
percent_round = percent_free[:5]

print""
print "You have %.2f hours of freetime." % time_minus_work
waking_time = time_minus_sleep
print "Of the %.0f hours in a day, you are awake for %.2f of them." % (time, waking_time)

There is no need for sleep and work to take the time as an argument. Just return what the user enters and calculate in the main function. The main part of the code should be guarded by a if __name__ == "__main__": guard, which ensures that that code is only executed when running the script but not when importing from it.

Python 2 will soon be no longer supported. If you are starting to learn Python now, learn Python 3 straight away. In the code below the main differences are that raw_input is now input (and the Python 2 input no longer exists), print is no longer a statement, but a function (so surround it with (), instead of ), division is now float division by default (use // for integer division) and finally string formatting has become a lot easier in Python 3.6 with f-strings.

def ask_time(message):
    while True:
        try:
            hours = float(input(message))
            if 0 <= hours <= 24:
                return hours
        except ValueError:
            pass
        print("Please enter a number between 0 and 24")

def see_percent():
    reply = input("Would you like to know the percent of your waking time is free time? (Y/N): ").lower()
    return reply == "y"

if __name__ == "__main__":
    total_time = 24.  # hours
    sleep_time = ask_time("How many hours do you sleep a night?: ")
    work_time = ask_time("How many hours do you work each weekday?: ")

    waking_time = total_time - sleep_time
    free_time = waking_time - work_time
    print(f"You have {free_time:.2f} hours of free time.")
    print(f"Of the 24 hours in a day, you are awake for {waking_time:.2f} of them.")

    if see_percent():
        percent_free = free_time / total_time
        print(f"{percent_free:.2%}.")

I also made a more general ask_time function which ensures that the user enters a valid number between 0 and 24 and keeps on asking if they didn't and used four spaces throughout, as recommended by Python's official style-guide, PEP8.


Simple fuzzy text search algorithm Basically, this code takes a keyword and an array of strings, then sorts them based on two things: the number of characters shared with the key, and the distance between them.(As a side note, would this properly be called a sort, not a search?)

def search(key, list)
  # Format for everything pushed to out:
  # Should this be a class?
  # {
  #   val: the string in question,
  #   shared_chars: [{char: shared char of key list elem,
  #                   index: index of shared char,
  #                   kindex: index of shared char in key
  #                   distance: how close the shared chars are}]
  # }
  out = []
  key = key.downcase

  list.each { |l|
    l.downcase!
    shared_chars = []

    keyi = 0
    key.each_char { |c|
      index = /#{c}/ =~ l

      if index != nil
        shared_chars.push char: c, index: index, kindex: keyi
      end

      # Inelegant?
      keyi += 1
    }

    # Calulate total distance between shared_chars
    distance = 0
    odistance = 0

    shared_chars.each_index { |i|
      unless i == shared_chars.length-1
        distance += (shared_chars[i+1][:index] - shared_chars[i][:index]).abs
        odistance += (shared_chars[i+1][:kindex] - shared_chars[i][:kindex]).abs
      end
    }

    distance -= odistance
    distance = distance.abs

    out.push val: l, shared_chars: shared_chars, distance: distance
  }

  out.sort_by! { |e|
    # 100 is arbitrary
    100 + e[:distance] - e[:shared_chars].length*3
  }

  out
end

Specifically I would like to know if any part of it could be made more efficient and/or elegant, but general critique is of course welcome.

Blocks longer than one line are conventionally written using do…end rather than braces.
Code of the form

out = []
list.each { |l| ... out.push(something) }

… would be better expressed as

out = list.collect { |l| something }

Besides being slightly more compact, there is a subtle difference in thinking: the former feels like "do this, then this, then this to build a result"; the latter says "transform each element like this", and it's easier to see that there is a one-to-one correspondence between input elements and output elements.
Within that block,

out = list.collect do |l|
  # Calling l.downcase! would have the side-effect of modifying
  # strings in the original list, which is impolite.
  l = l.downcase

  shared_chars = []
  key.split.each_with_index do |c, keyi|
    index = l.index(c)
    # Actually, char:c is never used and could be eliminated
    shared_chars.push(char: c, index: index, kindex: keyi) if index
  end

  distance, kdistance = 0, 0
  shared_chars.each_cons(2) do |a, b|
    distance += (b[:index] - a[:index]).abs
    kdistance += (b[:kindex] - a[:kindex]).abs
  end

  { val: l, shared_chars: shared_chars, distance: (distance - odistance).abs }
end

Furthermore,

out.sort_by! { |e| ... }
out

could just be

out.sort_by { |e| ... }

(.sort_by is defined because an Array is an Enumerable.)
I think that the whole function would be better as one chained expression:

def search(key, list)
  key = key.downcase

  list.collect do |l|
    ...
  end.sort_by do |e|
    # There's no point in adding 100 to each element
    e[:distance] - 3 * e[:shared_chars].length
  end
end


Showing form on btn click - preventDefault of submit btn, then remove listener I've built out a section on a page that contains multiple instances (why I'm using querySelectorAll()) of this Request Brochure form. They are using Campaign Monitor so much of the form code has been removed for this post.

Operation

On page load an event handler that calls preventDefault on click  events is added to elements with class download to prevent the submit action.
A class of .is-open is added to the .download container.
This triggers a keyframe animation that transitions the height, then the opacity of the forms
The event listener is removed to allow the button to perform it's submit action

I did try using the method of setting the button to disabled initially, then removing this attribute onclick but found this meant the hover states would not work.

I'm looking to see if this is the most efficient way of adding, then removing preventDefault once it is no longer required.

const packageCMCont = document.querySelectorAll('.download');

packageCMCont.forEach(function(item) {

  function handleClick(e) {
    e.preventDefault()
    var btn = item.querySelector('.btn');

    item.classList.add('is-open');

    btn.classList.remove('is-style-outline');
    btn.classList.add('is-style-default');

    item.removeEventListener('click', handleClick);
  }

  item.addEventListener('click', handleClick);

})
.download {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
 }
.download.is-open .inputs {
    display: flex;
    height: 100px;
    animation: showForms 3s forwards;
}
.inputs {
  opacity: 0;
  display: none;
  flex-direction: column;
  height: 0;
  overflow: hidden;
}
input {
  height: 50px;
}
button {
  height: 50px;
  width: 100%;
  background-color: green;
  color: white;
}
button:hover {
  background-color: white;
  color: green;
}

@keyframes showForms {
  0% {
    height: 0;
  }
  50% {
    height: 100px;
    opacity: 0;
  }
  100% {
    height: 100px;
    opacity: 1;
  }
}

  <form>

      <input aria-label="Name" id="fieldName" maxlength="200" name="cm-name" placeholder="Name">
      <input autocomplete="Email" aria-label="Email" id="fieldEmail" maxlength="200" required="" type="email" placeholder="Email">

      <button class="btn" type="submit">Request Brochure</button>

  </form>

Event delegation can be used to improve efficiency. Instead of adding a click handler to every single element with the class download, an event handler could be added to the entire document or a sub-element that contains all elements with class download.

document.addEventListener('click', e => {
  let node = e.target;
  do {
    if (node.classList.contains('download') && !node.classList.contains('is-open')) {
      e.preventDefault();
      const btn = node.querySelector('.btn');

      btn.classList.remove('is-style-outline');
      btn.classList.add('is-style-default');

      node.classList.add('is-open');
      break;
    }
    node = node.parentNode;
  } while (node && node.classList !== undefined);
});

In the example above, the click handler inspects the target element to see if it or a parent node has the class download and if such an element doesn't have class is-open before modifying class names for the elements.

I noticed that I wasn't able to click on the div element with class download without clicking the button, despite the container element having space on the sides of the button, and in the original code the click event is bubbled up from the button to the div. Instead of needing to use the do while loop to go up the DOM chain, the click handler could check to see if the target element has class name btn and in that case if it has an ancestor up three levels that matches the specified class names then modify the class names.

document.addEventListener('click', e => {
  const node = e.target;
  if (node.classList.contains('btn')) {
    if (node.parentNode && node.parentNode.parentNode && node.parentNode.parentNode.parentNode) {
      const ancestorDiv = node.parentNode.parentNode.parentNode;
      if (ancestorDiv.classList && ancestorDiv.classList.contains('download') && !ancestorDiv.classList.contains('is-open')) {
        e.preventDefault();

        node.classList.remove('is-style-outline');
        node.classList.add('is-style-default');

        ancestorDiv.classList.add('is-open');
      }
    }
  }
});

Because the code above contains multiple 'if' statements that lead to multiple indentation levels, the logic could be switched to return early instead:

document.addEventListener('click', e => {
  const node = e.target;
  if (!node.classList.contains('btn')) {
    return;
  }
  if (!(node.parentNode && node.parentNode.parentNode && node.parentNode.parentNode.parentNode)) {
    return;
  }
  const ancestorDiv = node.parentNode.parentNode.parentNode;
  if (ancestorDiv.classList && ancestorDiv.classList.contains('download') && !ancestorDiv.classList.contains('is-open')) {
    e.preventDefault();

    node.classList.remove('is-style-outline');
    node.classList.add('is-style-default');

    ancestorDiv.classList.add('is-open');
  }
});

I presume the classes is-style-outline and is-style-default are styled by a library (e.g. wordpress) but the styles could be incorporated based on whether the container div (i.e. with class download) contains class is-open, in the same way the inputs are displayed depending on those class names.

Indentation in this code is fairly uniform, though one CSS ruleset (i.e. .download.is-open .inputs) contains rules indented by four spaces instead of two


Calculate employee wage This is for a class assignment. The objective is to write a program that will take in user input for employee information and print the wage based on hours worked.

Please review my code.

#include <ctime>
#include <iostream>

using namespace std;

int GetSalary(int,int,int,int);
int GetYearsOfService(int);

int main()
{
    int employeeId, hoursWorked, yearJoined, fullTime;

    cout << "Employee ID: ";
    cin >> employeeId;

    cout << "Hours Worked: ";
    cin >> hoursWorked;

    cout << "Year Joined: ";
    cin >> yearJoined;

    cout << "FullTime Status (0 for no, 1 for yes): ";
    cin >> fullTime;

    double salary = GetSalary(employeeId, hoursWorked, yearJoined, fullTime);
    double taxes = salary * 0.15;

    cout << endl << "Empolyee ID: " << employeeId << endl << "\tFull time?: ";

    if (fullTime == 0)
        cout << "No";
    else
        cout << "Yes";

    cout << endl << "\tHours worked: " << hoursWorked << endl << "\tWages (after tax) for the month: $"
         << salary - taxes << endl << "\tAmount withheld for tax: $" << taxes;

    return 0;
}

int GetSalary(int employeeId, int hoursWorked, int yearJoined, int fullTime) {
    double hourlyWage = 14;

    //Get the hourly wage
    int wage = 14;

    if( wage>=50 && wage < 100){
        wage += 1.25;
    }else if( wage < 160){
        wage += 2.0;
    }else{
        wage += 3.0;
    }

    double baseSalary = hourlyWage * hoursWorked;
    int yearsOfService = GetYearsOfService(yearJoined);

    //Check if any additional benefits/bonusses are to be paid
    if (fullTime == 1)
    {
        baseSalary += (35 *yearsOfService);
        baseSalary += 300;
    }
    else {
        if (yearsOfService > 5)
            baseSalary += (35 * yearsOfService);
    }
    return baseSalary;
}

int GetYearsOfService(int yearJoined) {
    time_t curTime = time(NULL);

    int elapsed = curTime / (365 * 24 * 60 * 60);

    return 1970 + elapsed - yearJoined;
}

My first review in awhile, this is short, sorry. I'm sure others will add more.

Please stop doing using namespace std. Read
this.
Using double for representing currency is
bad.
But since this is an assignment, it probably won't matter much.
Use constant variables to represent magic numbers like .15 and
3.0. Create a const variable named TAX_RATE for instance.
You are returning an int yet salary is of type double?
time_t curTime = time(NULL);

Use
nullptr
(C++11).


Passing some redundant parameters to an interface vs creating a new request object every time for the interface I am writing a proxy class, that will fetch a certain property (say propertyA) by calling an underlying service.

Currently we use Service A to get propertyA, but there is a chance that in the near future, we might migrate to service B to get propertyA instead.

Approach 1:
I wanted to make ServiceAProxy and ServiceBProxy both extend a common interface say PropertyAProxy that looks something like this

public interface PropertyAProxy{
    PropertyA getPropertyA(param1,param2, param3);
}

with the child classes as

public class ServiceAProxy implements PropertyAProxy{
    PropertyA getPropertyA(param1,param2,param3){
        return serviceA.getPropertyA(param1,param2); //param 3 is not needed for service A
    }
}

and

public class ServiceBProxy implements PropertyAProxy{
    PropertyA getPropertyA(param1,param2,param3){
        return serviceB.getPropertyA(param1,param2,param3);
    }
}

Approach 2:
or should I go for a really generic Provider interface

public interface Provider<I,O>{
    O get(I input);
}

with child classes being
public class ServiceAProxy implements

 Provider<PropertyARequestForServiceA,PropertyA>{
            PropertyA getPropertyA(PropertARequestForServiceA input){
                return serviceA.getPropertyA(input.getParam1, input.getParam2);
            }
        }

and

public class ServiceBProxy implements Provider<PropertyARequest2,PropertyA>{
    get(param1,param2,param3){
        return serviceB.getPropertyA(input.getParam1, input.getParam2,input.getParam3);
    }
}

My concerns with approach 1 are:

I am passing param3 to ServiceAProxy even though its not needed.
With the visibility I CURRENTLY have, we wont need anything else besides param1, param2 and param3. But in the future there might be a ServiceC which needs param4 and not param 1.

My concerns with approach 2:

For every input object i will have to define a new pojo to act as a request object, and that seems a bit excessive to have so many request classes (especially since the code base im working on is already getting quite large)

Additional Context:
I will be using serviceA to get paramA for now, but there is a VERY high chance that some point in the future we will migrate to serviceB to get paramA.
To avoid pains in the future, I wanted to make the callers of the proxy to call an interface instead, so that I could switch the underlying proxy implementation without having to rewrite the calling logic.

Approach 1, is simpler to implement, but i may end up passing parameters that are never used.
Approach 2, is more generic, but involves me making request objects for each implementation, which I personally feel is overkill.

I have no STRONG inclination over either approach, and hence reaching out to the wider community.

Since what you want is a total transparency on how you access the propertyA then solution 1 seems better. Because with solution 2 you have to change the request object.

You should clearly identify your parameters. Some may be changing the output that is needed, other may be more related to the underlying service and can be "defaulted" into the dedicated proxy. At the end if you still have some unused parameters, this is acceptbale until the response is still correct.

It is not because the serviceB has a functionnality (param3) that you are obliged to use it. Your services should have a common behavior if you want to exchange them without any impacts.


Word frequencies from large body of scraped text I have a file with word frequency logs from a very messy corpus of scraped Polish text that I am trying to clean to get accurate word frequencies. Since this is a big text file, I divided it into batches.

Here is a snippet from the original file:

 1 środka(byłe
 1 środka.było
 1 środkacccxli.
 1 (środkach)
 1 „środkach”
 1 środkach
 1 środkach...
 1 środkach.",
 1 środkach"
 1 środkach".
 1 środkachwzorem
 1 środkach.życie
 1 środkajak
 1 "środkami"
 1 (środkami)
 1 „środkami”)
 1 środkami!"
 1 środkami”
 1 środkami)?
 1 środkami˝.

My goal is to clean true word labels and remove noisy word labels (e.g. collocations of words concatenated through punctuation). This is what is achieved by the first part of the script. As you can see in the data sample above, several noisy entries belong to the same true label. Once cleaned, their frequencies should be added. This is what I try to achieve in the second part of my script.

Here is the code in one piece with fixed indentation, in case you are able to reproduce my issues on your end:

# -*- coding: utf-8 -*-

import io
import pandas as pd
import numpy as np

num_batches = 54

for i in range(1 ,num_batches +1):

    infile_path = r'input_batch_' + str(i) + r'.txt'
    outfile_path = r'output_batch_' + str(i) + r'.txt'

    with io.open(infile_path, 'r', encoding = 'utf8') as infile, \
         io.open(outfile_path, 'w', encoding='utf8') as outfile:

        entries_raw = infile.readlines()
        entries_single = [x.strip() for x in entries_raw]
        entries = [x.split('\t') for x in entries_single]

        data = pd.DataFrame({"word": [], "freq": []})

        for j in range(len(entries)):
            data.loc[j] = entries[j][1], entries[j][0]

            freq_dict = dict()
            keys = np.unique(data['word'])

            for key in keys:
                for x in range(len(data)):
                    if data['word'][x] == key:
                        if key in freq_dict:
                            prior_freq = freq_dict.get(key)
                            freq_dict[key] = prior_freq + data['freq'][x]
                        else:
                            freq_dict[key] = data['freq'][x]

        for key in freq_dict.keys():
        outfile.write("%s,%s\n" % (key, freq_dict[key]))

The problem with this code is that it is either buggy, running into an infinite loop or sth, or is very slow, even for processing a single batch, to the point of being impractical. Are there ways to streamline this code to make it computationally tractable? In particular, can I achieve the same goal without using for loops? Or by using a different data structure for word-frequency lookup than a dictionary?

for i in range(1 ,num_batches +1):

Your inter-token spacing here is a little wonky. I suggest running this code through a linter to get it to be PEP8-compliant.

This string:

r'input_batch_' + str(i) + r'.txt'

can be:

f'input_batch_{i}.txt'

This code:

entries_raw = infile.readlines()
entries_single = [x.strip() for x in entries_raw]
entries = [x.split('\t') for x in entries_single]

can also be simplified, to:

entries = [line.rstrip().split('\t') for line in infile]

Note a few things. You don't need to call readlines(); you can treat the file object itself as an iterator. Also, avoid calling a variable x even if it's an intermediate variable; you need meaningful names.

This is an antipattern inherited from C:

for j in range(len(entries)):
    data.loc[j] = entries[j][1], entries[j][0]

You should instead do:

for j, entry in enumerate(entries):
    data.loc[j] = entry[1], entry[0]

That also applies to your for x in range(len(data)):.

This:

freq_dict = dict()

should be:

freq_dict = {}

This:

if key in freq_dict:
    prior_freq = freq_dict.get(key)
    freq_dict[key] = prior_freq + data['freq'][x]
else:
    freq_dict[key] = data['freq'][x]

can be simplified to:

prior_freq = freq_dict.get(key)
freq_dict[key] = data['freq'][x]
if prior_freq is not None:
    freq_dict[key] += prior_freq

or even (courtesy @AlexHall):

freq_dict[key] = data['freq'][x] + freq_dict.get(key, 0)

Note a few things. First of all, you were inappropriately using get - either check for key presence and then use [], or use get and then check the return value (which is preferred, as it requires fewer key lookups).

This loop:

for key in freq_dict.keys():
outfile.write("%s,%s\n" % (key, freq_dict[key]))

needs adjustment in a few ways. Firstly, it won't run at all because its indentation is wrong. Also, rather that only iterating over keys, you should be iterating over items:

for key, freq in freq_dict.items():
    outfile.write(f'{key},{freq}\n')


Producing triangles of asterisks based on height I have created a simple terminal program: it allows the user to enter a height and it will produce triangles of asterisks (*'s) based on the height.

I have just started learning C# as practice for my internship. I would appreciate any feedback.

using System;

public class Triangle
{
    public int height;
    private string pyramid = "";

    public Triangle(int height)
    {
        this.height = height;
    }

    public String makeTriangle()
    {
        //4
        //   *    = 1         ***+***  = Even on both sides  7/2
        //  ***   = 3 - (+2)  **+++**  =
        // *****  = 5 - (+2)  *+++++*
        //******* = 7 - (+2)  +++++++
        int cutEnds = biggestOddNumber() / 2;

        for (int i = 0; i < height; i++)
        {
            for (int j = 1; j <= biggestOddNumber(); j++)
            {
                String singleElement = "*";

                if (j <= cutEnds || j > (biggestOddNumber()-cutEnds))
                {
                    pyramid = pyramid + " ";
                }
                else
                {
                    pyramid = pyramid + singleElement;
                }

                if (j == biggestOddNumber())
                {
                    pyramid = pyramid + "\r\n";
                }
            }
            cutEnds--;

        }
        return pyramid;
    }

    public int biggestOddNumber()
    {
        // 1 2 3 4 5 6 7 8 9 10
        // ?   ?   ?   ?
        //
        //Formula for Odd Numbers = 2n + 1
        //2*0 + 1 = 1
        //2*1 + 1 = 3
        //2*2 + 1 = 5
        //...
        // we do height -1 since if you look at formula we start from 0 not 1
        // if we do 2*4 + 1 = (9)
        //4
        //   *    = 1
        //  ***   = 3 - (+2)
        // *****  = 5 - (+2)
        //******* = 7 - (+2) However it should be (7)

        return (2 * (height-1) + 1);

    }
}

Main method

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Enter height of pyramid");
            int height = int.Parse(Console.ReadLine());
            Triangle triangle = new Triangle(height);
            Console.WriteLine(triangle.makeTriangle());
        }
    }
}

You should read Naming guidelines and apply them to your code.
pyramid should be a local variable. Otherwise calling makeTriangle more than once will produce incorrect results.
There is no need for biggestOddNumber to be public.
singleElement should be a constant field.
You can use String.PadRight and String.PadLeft methods to pad the string with spaces (or any other character) from both sides. Instead of manually doing it in hard-to-understand loop.


Formatting inventory of parts I have one file with indexes.  For example, they are:

1    Fruit
2    Meat
3    Fish
4    Salmon
5    Pork
6    Apple

And a dictionary, because I want to match entries that I choose:

similar = {'1' : '6', '2' : '5'}

Since they are on the same file, my program scans for the '1' on the file, and then re-scans from the beginning looking for the '6'. Same with all the numbers, always re-scanning.

It's a very large file with a lot of numbers.

similar = { '4719' : '4720c01' }

for aline in invFormatted:
    lines = aline.split("\t") #Splits the CSV file on every tab.
    lotID = lines[0]
    partNO = lines[1] #Splits and gets the part that would be the "index"
    if similar.has_key(partNO):
        for alines in invFormatted:
            liness = alines.split("\t")
            lotIDmatch = liness[0]
            partNOmatch = liness[1]
            if liness[1] == similar[partNO]:

Would there be a way to make it so it only scans it once?  Or any other ideas to put better this program?

There is a text file formatted this way:

51689299  4719    Medium Azure    Riding Cycle
51689345  4720c01 Trans-Clear Wheel & Tire Assembly

In real life, it would have thousands of entries.

Then, my Python file 'knows' that the part number 4719 matches the part number 4720c01 via the similar dictionary:

similar = { '4719' : '4720c01' }

Now, what I think does:

invFormatted = open('export.txt', 'r') #Opens the file with the part numbers

with open ('upload.txt', 'a') as upload:

    upload.write("<INVENTORY>") #Something that would be on the export

    for aline in invFormatted:
        lines = aline.split("\t") #Splits the text file on every tab
        lotID = lines[0] #The lot ID is the first word
        partNO = lines[1] #Part number the second one
        if partNO in similar: #Sees if the part number in question has a match, if YES
            for alines in invFormatted: #Searchs my inventory file again to see if the match is in my inventory
                liness = alines.split("\t")
                lotIDmatch = liness[0]
                partNOmatch = liness[1]
                if liness[1] == similar[partNO]: #if YES, prints out what I want it to print, and goes back to the first step
                    upload.write("blabla")

    invFormatted.close()

    upload.write("\n</INVENTORY>")

Can you store the content in the CSV file in the memory?It will be more effective to read from the memory than the disk.

Maybe the CSV file will also be store in the memory cache by OS, but you can do it your self to make it more reliable.

Of course it's only when there is enough memory you can do this.

OK, from your code, I think maybe you just need to read all line[1] in and then scan it.

partNOs=[line.split("\t")[1] for line in upload]
for partNO in partNOs:
    if partNO in similar and similar[partNO] in partNOs:
        upload.write("blabla")

This assume that: what you write to file 'upload' will not match similar keys and values. Because it read the file and use the 'cache' before write into it.


Script for concatenating delimited text files I need to concatenate a bunch of delimited text files. In the process, I need to add a new column to the data based on part of the name of one of the directories containing each file. The script works, but I have a feeling that it is inelegant in the extreme.

In particular, I'm wondering whether I should be reading the source files into a data structure that can later be written to file as a delimited text file. It seems like such an approach would be more general and easily extended.

In its current structure, I have doubts about the efficiency of how I'm skipping the header lines in source files with the is_header variable. It seems like this approach requires more condition-checking than should be strictly necessary. Can't I just iterate over some object? I tried for row in reader[1:]: but apparently objects of type csv.reader don't allow subscripting.

#! /usr/bin/env Python3

import glob
import csv

file_names = glob.glob('*/unknown/*.dat')

with open(file_names[0], 'r') as csv_input:
  reader = csv.reader(csv_input, delimiter = '\t')
  header = ['seed'] + next(reader)

with open('output.dat', 'a') as csv_output:
  writer = csv.writer(csv_output, delimiter = '\t')
  writer.writerow(header)

  for file_name in file_names:
    param_dir = file_name.split('/')[0]
    seed = param_dir.split('-')[0]

    with open(file_name, 'r') as csv_input:
      reader = csv.reader(csv_input, delimiter = '\t')
      is_header = True
      for row in reader:
        if not is_header:
          out_row = [seed] + row
          writer.writerow(out_row)
        is_header = False

There is some repetition between your header-reading routine and the rest of the code.  You could incorporate it into the main loop to remove that duplication and avoid opening the first file twice.  You already use next(reader) nicely to read the header; use the same technique to skip the header row.

To determine the seed from a file path, you look for a - in the file path.  Your glob should have a - to ensure that that succeeds.

import csv
from glob import glob

paths = glob('*-*/unknown/*.dat')

with open('output.dat', 'a') as csv_output:
    writer = csv.writer(csv_output, delimiter='\t')
    header_written = False

    for path in paths:
        param_dir = path.split('/')[0]
        seed = param_dir.split('-')[0]

        with open(path, 'r') as csv_input:
            reader = csv.reader(csv_input, delimiter='\t')

            header = next(reader)
            if not header_written:
                writer.writerow(['seed'] + header)
                header_written = True

            for row in reader:
                writer.writerow([seed] + row)


Method arguments set object attributes The code creates a meta class and its implementation to set the values passed in as arguments to methods on a class automatically on the object avoiding a lot of self.a=a code at the start of methods.

>>> from functools import wraps
>>> import inspect
>>>
>>> def setMethodAttrs(func):
...    @wraps(func)
...    def wrapper(*args, **kwargs):
...        formalArgs=inspect.getargspec(func)[0]
...        if len(args)>1:
...           for x in range(1, len(args)):
...              setattr(args[0], formalArgs[x], args[x])
...        for k, v in kwargs.iteritems():
...           setattr(vars()['args'][0], k, v)
...        return func(*args, **kwargs)
...    return wrapper
...
>>> def classAttrs(cls):
...     for key, val in vars(cls).items():
...         if callable(val):
...             setattr(cls,key, setMethodAttrs(val))
...     return cls
...
...
>>>
>>> @classAttrs
... class trythis:
...    def __init__(self):
...       self.firstvar=1
...       self.secondvar=2
...       self.thirdvar=3
...       self.fourthvar=4
...    def method1(self,firstvar=None,secondvar=None,thirdvar=None):
...       print("firstvar {}".format(self.firstvar))
...       print("secondvar {}".format(self.secondvar))
...       print("thirdvar {}".format(self.thirdvar))
...       print("fourthvar {}".format(self.fourthvar))
...    def method2(self, secondvar=None, fourthvar=None):
...       print("firstvar {}".format(self.firstvar))
...       print("secondvar {}".format(self.secondvar))
...       print("thirdvar {}".format(self.thirdvar))
...       print("fourthvar {}".format(self.fourthvar))
...
...
...
>>> a=trythis()
>>> a.method1()
firstvar 1
secondvar 2
thirdvar 3
fourthvar 4
>>> a.method1(firstvar=9)
firstvar 9
secondvar 2
thirdvar 3
fourthvar 4
>>> a.method2(11)
firstvar 9
secondvar 11
thirdvar 3
fourthvar 4
>>> a.method1(19, thirdvar=21)
firstvar 19
secondvar 11
thirdvar 21
fourthvar 4
>>> a.method2(fourthvar=40)
firstvar 19
secondvar 11
thirdvar 21
fourthvar 40
>>>

...        if len(args)>1:
...           for x in range(1, len(args)):
...              setattr(args[0], formalArgs[x], args[x])

You’re pretty much re-inventing zip here, use that instead. To extract out the first (self) parameter, you can use next (in Python 3) or slicing (in Python 2). To get a consistent behaviour accross Python versions, you can use itertools.izip in Python 2.

Something along the lines of:

arguments = zip(formalArgs, args)
_, self = next(arguments)
for name, value in arguments:
    setattr(self, name, value)

You can also define your wrapper as def wrapper(self, *args, **kwargs) to remove the need for next and already extract the value of self out of the args tuple. This will mean you’ll have to slice formalArgs though:

def wrapper(self, *args, **kwargs):
    formal_args = inspect.getargspec(func)[0][1:]
    for name, value in zip(formal_args, args):
        setattr(self, name, value)

You also don't need to inspect func at each call as, since you're using a decorator, you’re pretty much guaranteed that this object will never change during the lifetime of the program. Besides, it may be more readable to use the name, rather than the index, of the attribute you’re trying to extract out of the nametuple (since Python 2.6).

Lastly, getargspec has been deprecated since Python 3.0, so you'd better off using getfullargspec. But this function doesn't exist in Python 2, so you can try a conditional import:

from itertools import chain
from functools import wraps
try:
    # Python 3
    from inspect import getfullargspec as getargspec
except ImportError:
    # Python 2
    from inspect import getargspec
    from itertools import izip as zip

def store_attributes(method):
   arguments_names = getargspec(method).args[1:]

   @wraps(method)
   def wrapper(self, *args, **kwargs):
       for name, value in chain(zip(arguments_names, args), kwargs.items()):
           setattr(self, name, value)
       return method(self, *args, **kwargs)

   return wrapper

def class_store_attributes(cls):
    for name, value in vars(cls).items():
        if callable(value):
            setattr(cls, name, store_attributes(value))
    return cls

Usage being the same, even though I still don't get why you would use @class_store_attributes on the whole class rather than @store_attributes on a per-method basis.


Beginnings of Go web server with mongoDb I am just learning how to use go and I'm a bit confused on how my code is supposed to be organised package wise.

Am I right to have the user package? I'm planning to redirect my /user/ routes to a handler in this package but I'm unsure if this is the go way to do things

My directory structure is

/go_rest_api
  /user
    -user.go
    -user_provider.go
  -app.go
  -main.go

main.go

package main

func main() {
  a := App{}
  a.Initialize()
  a.Run()
}

app.go

package main

import (
  "fmt"
  "log"
  "github.com/gorilla/mux"
  "gopkg.in/mgo.v2"
  "go_rest_api/user"
)

type App struct {
  Router *mux.Router
  Mongo *MongoConnection
}

type MongoConnection struct {
  Session *mgo.Session
}

func(a* App) GetMongoSession() *mgo.Session {
  return a.Mongo.Session.Copy()
}

func(a *App) Initialize() {
  session, err := mgo.Dial("127.0.0.1:27017")
  if err != nil {
    panic(err)
  }

  session.SetMode(mgo.Monotonic, true)

  a.Mongo = &MongoConnection{session}
  a.Router = mux.NewRouter()
}

func(a *App) Run() {
  defer a.Mongo.Session.Close()
  testMongo(a.GetMongoSession())
}

func testMongo(session *mgo.Session) {
  userProvider := user.Provider(session)
  err := userProvider.InsertUser(user.User{"test"})
  if err != nil {
    log.Fatal(err)
  }

  user := user.User{}
  err, user = userProvider.GetUser("test")
  if err != nil {
    log.Fatal(err)
  }

  fmt.Println("username:", user.Username)
}

user/user.go

package user

type User struct {
  Username string
}

user/user_provider.go

package user

import (
  "gopkg.in/mgo.v2/bson"
  "gopkg.in/mgo.v2"
)

type provider struct {
  Collection *mgo.Collection
}

func Provider(mongoSession *mgo.Session) provider {
  p := provider{}
  p.Collection = mongoSession.DB("test").C("user")
  return p
}

func(p *provider) InsertUser(user User) error {
  return p.Collection.Insert(&user)
}

func (p *provider) GetUser(username string) (error, User) {
  result := User{}
  err := p.Collection.Find(bson.M{"username": username}).One(&result)
  return err, result
}

You might wanted to start writing some comments on your code.

For example I've read all your code but there are some method that I don't understand like :

func(a* App) GetMongoSession() *mgo.Session {
  return a.Mongo.Session.Copy()
}

Okay we know It is getting the mongo session. but for what purpose?

// We get the mongo session for .... you can start explain why
func(a* App) GetMongoSession() *mgo.Session {
  return a.Mongo.Session.Copy()
}

I think it is a good think to keep comment the code, so others can understand it quickly. especially when someone who new to mongoDB. :D


Accessing value from either os.environ or argparse I have the following code:

#!/usr/bin/env python3
import os, argparse

if __name__ == '__main__':
    # Parse arguments.
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose",  action="store_true", dest="verbose")
    args = parser.parse_args()

    try:
        verbose = bool(os.environ['VERBOSE'])
    except KeyError:
        verbose = args.verbose

    print("Verbose:", verbose)

And I would like to find the simpler way of returning value from two different sources (either system variable or parsed argument).

Ideally I would expect to find some one-liner such as:

verbose = bool(os.environ['VERBOSE']) or args.verbose

however instead I have KeyError exception, therefore I had to implement exception handler.

I'm expecting the following tests to print True (if verbose is set):

VERBOSE=1 ./test.py
./test.py -v

otherwise False.

Using get on the os.getenv dictionary and specifying args.verbose as the default value (2nd param of the .get call) will have your desired outcome:

import os
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose",  action="store_true", dest="verbose")
    args = parser.parse_args()

    verbose = bool(os.environ.get('VERBOSE', args.verbose))

    print("Verbose:", verbose)

Test runs:

$ ./test.py -v; VERBOSE=1 ./test.py ; ./test.py
Verbose: True
Verbose: True
Verbose: False

Same output as your original.

Other notes:

The comment # Parse arguments. was pointless
Imports should appear on separate lines as per PEP8


Find abstraction for classes which represent tables with differnt amount of colums (based on DataTables) I have a lot of classes which are principal equal, but they consist small differences so that I can´t abstract then very well.

The classes represent different kinds of DataTables. Every Class has two important methods which every "table-class" has. Here a abstracted example:

internal class FooTable
{
    internal static DataTable CreateTable()
    {
        using (DataTable fooTable = new DataTable("fooTable"))
        {
            // number and content of rows are different from table to table.
            fooTable.Columns.Add("ColFoo");
            fooTable.Columns.Add("ColBar");
            fooTable.Columns.Add("ColSomethingElse");

            AddRow(fooTable, "ValueA", "ValueB", "ValueC");
            AddRow(fooTable, "ValueD", "ValueE", "ValueF");
            // ... more rows ...

            return fooTable;
        }
    }

    private static void AddRow(
        DataTable table,
        string ColFoo,
        string ColBar,
        string ColSomethingElse)
    {
        DataRow dataRow = table.NewRow();

        dataRow["ColFoo"] = ColFoo;
        dataRow["ColBar"] = ColBar;
        dataRow["ColSomethingElse"] = ColSomethingElse;

        table.Rows.Add(dataRow);
    }
}

The differences between the tables are the number of columns and the datatyp of column content. With this implementation I can´t use abstract classes, because of the different amount of columns. The names of the columns are also redundant in code.

Finally I think about the use of params to solve the problem with different amount of columns, but I’m not sure how to make a good implementation other AddRow-methode.

private static void AddRow(DataTable table, params object[] values)
{
    ...
}

So did anyone know a better way to implement this? I'm sure there is a better way.

I can think of trying something like this.

interface ICount
{
  int count();
}

class CountOne : ICount { int count() { return 1; }}
class CountTwo : ICount { int count() { return 2; }}

abstract class IFooTable<T> where T : ICount, new()
{
  int count() { return (new T()).count(); }
}

class FooTable<T> : IFooTable<T>
{
  void AddRow(params object[] values) {
    assert(values.length = this.count());
    ...
  }
}

class OneTable : FooTable<CountOne> { }
class TwoTable : FooTable<CountTwo> { }

But honestly I would just expect the add function to take a row. This is not something where I'd use generics, instead I'd just use mutable data structures that have constraint checks. I'm way more concerned with column names matching especially when a params statement doesn't make sure they're in the right order.

class FooTable
{
  List<string> columns;
  List<DataRow> rows;

  void AddRow(DataRow row)
  {
    assert(column names for the row match the expected values);
    rows.add(row);
  }
}

Alternatively, you could mix both approaches. Using the generics to ensure the number of columns and then adding a DataRow at a time to enforce column names match up.


Program to let any user run a command I have a script which can only be run by one specific user on a system. I need to let all users on the system have access to run that script and see the output. But there must never be more than one instance of the script running simultaneously.

I came up with this program to be run as the specific user who can run the script. This program will be left running listening on a TCP port. Any user who want to run the script then connects to the TCP port and the script will run.

#include <arpa/inet.h>
#include <errno.h>
#include <error.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int setup_socket()
{
  const int one = 1;
  struct sockaddr_in6 bind_addr = {
    .sin6_addr = IN6ADDR_LOOPBACK_INIT,
    .sin6_family = AF_INET6,
    .sin6_port = htons(65454),
    .sin6_flowinfo = 0,
    .sin6_scope_id = 0,
  };
  int fd = socket(PF_INET6, SOCK_STREAM, 0);

  setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));

  if (bind(fd, (struct sockaddr*)&bind_addr, sizeof(bind_addr)))
    error(EXIT_FAILURE, errno, "bind() failed");

  if (listen(fd, 5))
    error(EXIT_FAILURE, errno, "listen() failed");

  return fd;
}

int main(int argc, char ** argv)
{
  int fd;

  if (argc < 2) {
    fprintf(stderr, "Usage: %s <command>\n", argv[0]);
    return EXIT_FAILURE;
  }

  fd = setup_socket();

  while (1) {
    int child_fd = accept(fd, NULL, NULL);
    pid_t child = fork();

    switch (child) {
    case -1:
      error(0, errno, "fork() failed");
      close(child_fd);
      break;
    case 0:
      if ((dup2(child_fd, 1) != 1) ||
          (dup2(child_fd, 2) != 2))
        error(EXIT_FAILURE, errno, "dup2() failed");
      execvp(argv[1], argv + 1);
      error(EXIT_FAILURE, errno, "excvp(%s) failed", argv[1]);
    default:
      close(child_fd);
      waitpid(child, NULL, 0);
    }
  }
}

Do you see any flaws in this program? I am mostly concerned with security problems, but also interested in hearing of any other problems you may see in the program.

This looks a bit unclear:

const int one = 1;

It's primarily used as the option_value argument of setsockopt().  Consider renaming this to something more clear so that it doesn't leave readers confused.
In addition to your other error-checking, you can also check the return value of socket() and print its error in case it fails.
A little nit-picky, but you can just initialize fd after the command line check instead of declaring it first and then assigning to it:

int fd = setup_socket();


Summation calculator of integers, squares, and cubes Code works exactly how I want it to, but any simplification to the code that could be made would be much appreciated (granted this program uses almost everything within the scope of my C++ knowledge).

 // sum calculator
#include<iostream>
#include<string>

//integer sum: 0 + 1 + 2 + ... + n
int integer_sum(int a, int b){
    int int_sum(0);
    while(a <= b){
    int_sum += a;
    a++;
   }
   return int_sum;
}

//squares sum: 0^2 + 1^2 + 2^2 + ... + n^2
int square_sum(int a, int b){
    int squ_sum(0);
    while(a <= b){
    squ_sum += a*a;
    a++;
  }
  return squ_sum;
}

//cubes sum: 0^3 + 1^3 + 2^3 + ... + n^3
int cube_sum(int a, int b){
    int cub_sum(0);
    while(a <= b){
    cub_sum += a*a*a;
    a++;
   }
  return cub_sum;
}

int main(){

    while(std::cin){

        char choice;
        // user menu
        std::cout << "select an operation: \n"
                  << "(a) sum of integers\n"
                  << "(b) sum of squares\n"
                  << "(c) sum of cubes\n"
                  << "(d) calculator OFF\n";
        std::cin >> choice;

        std::string restraint("First value must be less than the second");
        std::string request_range_1("First Range value: ");
        std::string request_range_2("Second Range value: ");
        int range_1;
        int range_2;

        switch(choice){
        case 'd':
            break;
        case 'a':
            std::cout << restraint << std::endl;
            std::cout << request_range_1;
            std::cin >> range_1;

            std::cout << request_range_2;
            std::cin >> range_2;

            std::cout << std::endl << "The sum of the integers in the range: " << "[" << range_1 << "," << range_2 << "]\nis: ";
            std::cout << integer_sum(range_1, range_2) << std::endl << std::endl;
            break;
        case 'b':
            std::cout << restraint << std::endl;
            std::cout << request_range_1;
            std::cin >> range_1;

            std::cout << request_range_2;
            std::cin >> range_2;

            std::cout << std::endl << "The sum of the squares in the range: " << "[" << range_1 << "," << range_2 << "]\nis: ";
            std::cout << square_sum(range_1, range_2) << std::endl << std::endl;
            break;
        case 'c':
            std::cout << restraint << std::endl;
            std::cout << request_range_1;
            std::cin >> range_1;

            std::cout << request_range_2;
            std::cin >> range_2;

            std::cout << std::endl << "The sum of the cubes in the range: " << "[" << range_1 << "," << range_2 << "]\nis: ";
            std::cout << cube_sum(range_1, range_2) << std::endl << std::endl;
            break;
        default:
            std::cout << "Incorrect operation \n\n";
            break;
        }
        if(choice == 'd')
            break;
    }
    std::cout << "Calculator OFF" << std::endl;
}

Refactor IO

In each case of your switch statement, you have this at the very beginning:

std::cout << restraint << std::endl;
std::cout << request_range_1;
std::cin >> range_1;

std::cout << request_range_2;
std::cin >> range_2;

Rather than re-writing this out for each case, you should refactor this to its own function that returns the two inputs. That way, you can just call that function to get the inputs.

Also, speaking of inputs...

Never trust the user!

When you are grabbing the two input numbers for an operation, you show the user a restraint message that says that the first number must be smaller than the second. While your function technically do "handle" this by returning 0, it would be good practice to not call those functions at all and to instead print out to the user if they accidentally (or purposely) entered a bigger number first.

You could include this in the extracted input-getting function described above. You can even create a loop inside this that repeatedly asks the user for proper input before actually returning the input.

early exit -- early exit -- early exit -- early exit....

    if(choice == 'd')
        break;
}
std::cout << "Calculator OFF" << std::endl;

This is a bit of code I grabbed from the end of the switch statement. Note that the only time that this bit of code is going to be reached is if the user hit d as their input.

Therefore, you can do some simplifying here. Rather than exiting from the switch statement only to do another conditional on whether or not to break the loop, just return from the entire program as soon as it is discovered that the user entered 'd':

case 'd':
    std::cout << "Calculator OFF" << std::endl;
    return 0;

This is much simpler and removes the redundancy from your code.

More refactoring and simplification

Your three _sum functions are all very similar except for a single line. These lines:

int_sum += a;

and

squ_sum += a*a;

and

cub_sum += a*a*a;

The rest of the code in the function is identical (of course, except for the variable names). This means that we can do some refactoring.

To simplify the code, let's write a blank function that follows the same format as the others:

int sum_exponent_series(int a, int b, int exp);

Notice the last parameter: this will allow the function to know whether to put a, a*a, or a*a*a... Which, in fact, can be simplified using <cmath>'s pow.

Now, the body of the function looks like this:

int sum(0);
for(; a <= b; a++) {
    sum += pow(a, exp);
}
return sum;

Note, I made two other changes:

I fixed your indentation (watch that in the future)
I turned your while loop into a for loop. An incrementation at the end of a while loop like you is a pretty good indication you need a for loop.

Now, instead of having three functions, you can just have this one function and call it with different exp values.

BUT WAIT!! You can make your program even more flexible now! Rather than having the user enter the "type" of exponent series thing they want, have them input these three things:

A number
The amount of times to add that number
The exponent to raise the number to when adding

That way, you won't even need a switch statement at all! The user could enter numbers like 3, or 8, or anything else without having to be restricted by what options you already set in place!