texts: Median-of-medians/quickselect filter in C

texts:
I wrote a quick-select filter in C on Wednesday. (The code is below.)

It is a filter in the UNIX tradition:

It reads from standard input k, the rank of the integer to select, n, the number of elements, and then n integers.
It outputs the kth highest integer.

(A perhaps better design would take k as an argument—but a bigger gripe of mine is having to give n! Bonus points if an answer can show me how to avoid reading n from stdin or as an argument. I would read until EOF, but then I would have to deal with a growing array, I think.)

For the unfamiliar, quickselect can find the kth highest integer in O(n) time. The naïve selection algorithm sorts in place and then accesses element k, for O(n lg n) runtime. Quickselect does not sort large lists and achieves linear performance.

kth_largest.c

/*d. ben knoble 2019.10.02*/

/*
 * PROGRAM
 *
 * k_largest
 *
 * Finds the kth largest element of an array in O(n) time.
 *
 * Reads from standard input
 *
 * - k: which element to find
 * - n: number of elements
 * - n elements
 *
 * Outputs kth largest element to standard out.
 *
 * IMPLEMENTATION
 *
 * see kth_largest function
 */

#include <assert.h>
#include <err.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

int compare_longs(const void *a, const void *b) {
    long x = *(long *)a;
    long y = *(long *)b;
    if (x < y)
        return -1;
    else if (x > y)
        return 1;
    return 0;
}

void sort(long *a, size_t n) {
    qsort(a, n, sizeof(long), compare_longs);
}

size_t med_index(size_t i) {
    return (size_t)(floor(i/2));
}

void swap(long *a, long *b) {
    long t = *a;
    *a = *b;
    *b = t;
}

size_t partition(long pivot, long *array, size_t n_elts) {
    // find the pivot
    size_t pos = -1;
    for (size_t i = 0; i < n_elts; ++i) {
        if (array[i] == pivot) {
            pos = i;
            break;
        }
    }
    assert(pos >= 0);
    swap(&array[pos], &array[n_elts-1]);
    // now pivot is at the end of the array

    size_t i = 0;
    for (size_t j = 0; j < n_elts; ++j) {
        if (array[j] < pivot) {
            swap(&array[j], &array[i]);
            ++i;
        }
    }
    swap(&array[i], &array[n_elts-1]);

    return i;
}

long kth_largest(size_t k, long *array, size_t n_elts) {
    size_t n_sublists = n_elts/5;
    long *medians = malloc(n_sublists * sizeof(long));
    if (medians == NULL) { err(1, NULL); }

    // sort sublists of 5 elements
    for (size_t i = 0; i < n_sublists; ++i) {
        size_t start = i*5;
        size_t left = n_elts - start < 5 ? n_elts - start : 5;
        sort(&array[start], left);
        if (left == 5)
            medians[i] = array[start + 3];
        else
            medians[i] = array[start + med_index(left)];
    }

    // determine pivot (possibly recursively)
    long pivot;
    if (n_sublists < 5)
        pivot = medians[med_index(n_sublists)];
    else
        pivot = kth_largest(med_index(n_sublists), medians, n_sublists);

    // partition
    size_t rank = partition(pivot, array, n_elts);
    if (k < rank)
        return kth_largest(k, array, rank-1);
    else if (k > rank)
        return kth_largest(rank - k, &array[rank+1], n_elts-(rank+1));
    // else k == rank
    return pivot;
}

int main(int argc, char **argv) {
    size_t k;
    size_t n_elts;
    scanf("%zd", &k);
    scanf("%zd", &n_elts);
    long *array = malloc(n_elts * sizeof(long));
    if (array == NULL) { err(1, NULL); }
    for (size_t i = 0; i < n_elts; ++i)
        scanf("%ld", &array[i]);

    printf("%ld\n", kth_largest(k, array, n_elts));
}


texts:
Diffie-Hellman is a key exchange that allows 2 people to share a symmetric key without interaction beforehand. First, a person shares an equation; in this case, we use:

$$3^x \mod{17}$$

Next, each person generates a random, usually prime, number. Then, they plug it in the equation. Let's use 5 and 7:

Alice: \$3^5 \mod{17} \equiv 9 \$
Bob: \$3^7 \mod{17} \equiv 6 \$

Finally, they share their generated numbers and calculate a "Shared Secret", this is done by (\$U\$ represents your private number):

\$\text{Public}^U \mod{17}\$

In this case:

Alice: \$6^5 \mod{17} \equiv 2\$
Bob: \$9^7 \mod{17} \equiv 2\$

Resulting in both parties having the same number. Confused? See this video.

I've implemented a function to generate that key. Thoughts?

function KeyGen(p1, p2, n){
  // Get a binary string, reverse it
  var bin = String((n).toString(2)).split("").reverse().join("");
  // Base for growth
  var grow = n;
  // Holds values for totals
  var tota = [];
  var total = 1;
  // The main loop
  for(var i = 0; i < bin.length; i++){
    tota[i] = 1;
    if(bin.substring(i, i + 1) === "1"){
      for (var l = grow; l > 0;l--){
        tota[i] *= p1;
        tota[i] %= p2;
      }
    }
    total *= tota[i];
    total %= p2;
    grow *= n;
  }
  return total;
}

// Example of gen
var gen = KeyGen(3, 17, 5);


texts: Simple React component to view cached data and test result from API

texts:
This is only the front end side of things which I have at the moment, as the back end is still being worked on. But as this is my first attempt at a react component, I'd like to know if there is anything I can improve on it.

The component has a text area for viewing the current data stored in the cache within our application, another text area for viewing the result when we send that data off to our API and get a transformed version of the data back, as well as two buttons: one for loading the cached data into one of the text areas and one for calling the API with the cached data. This component is used in development/UAT environment for testing purposes.

class DataRevealer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {input: '', result: ''};

        this.getCachedDataHandler = this.getCachedDataHandler.bind(this);
        this.transformDataHandler = this.transformDataHandler.bind(this);
        this.inputDataChanged = this.inputDataChanged.bind(this);
    }

    getCachedDataHandler() {
      let cachedData = DataRevealActions.getCachedData();
      this.setState({input: cachedData});
    }

    transformDataHandler() {
      if (this.state.input) {
        let transformedData = DataRevealActions.transformData(this.state.input);
        this.setState({result: transformedData});
      } else {
        alert('No data to transform');
      }
    }

    inputDataChanged(event) {
      this.setState({input: event.target.value});
    }

    get getCachedDataButtonText() {
      //TODO: localise string
      return 'Get Cached Data';
    }

    get transformDataButtonText() {
        //TODO: localise string
        return 'Transform Data';
    }

    render() {
        return (

                <textarea value={ this.state.input }
                          className='data-revealer-textarea centred-control'
                          onChange={ this.inputDataChanged }
                />

                  <Button onClick={ this.getCachedDataHandler }
                          className='data-revealer-button centred-control'>
                      { this.getCachedDataButtonText }
                  </Button>
                  <Button onClick={ this.transformDataHandler }
                          className='data-revealer-button centred-control' >
                      { this.transformDataButtonText }
                  </Button>

              <textarea value={ this.state.result }
                        className='data-revealer-textarea centred-control'
              />

        );
    }
}

export default DataRevealer;

Couple of things to note:

The Button is one of our custom controls, it acts as a normal button but with pre-implemented styling tweaks.
The TODO may not actually be needed, as the strings may not need to be localised.
DataRevealActions are where the back-end code will go, once that work is done.


texts: Setting Property Values Programmatically in a JSON Object

texts:
Through the lens of the SOLID principles, which one of the following makes the most sense?  I want to ensure the approach I select keeps everything simple and maintainable as we add properties, modify or replace functions, and scale.  These objects may contain up to thirty properties or more and each one may require a value which changes.

Let's say I have a JSON object and I want to dynamically add values to it.

The scenarios below all technically work but I'm not sure of what the "best practice" would be when dynamically adding items in a JSON object, especially as it grows in the number of properties.

Scenario A) - Operations in a variable.

var added = 3 + 4;
var subtracted = 1 + 2;

var testObj = {
    key1: added,
    key2: subtracted
}

Scenario B) - Operations in a function.

var b = 1, c = 2, e = 3, f = 4;

function Added(x, y) ( return x + y }
function Subtracted(a, z) ( return a - z }

var testObj = {
    key1: Added(b, c)
    key2: Subtracted(e, f)
}

Scenario C) - Operations in the JSON properties.

var a = 1, b = 2, c = 3, d = 4;
var testObj = {
    key1: a + b
    key2: c - d
}

Is there another approach which I haven't yet considered?


texts: If non-array property exists convert it to one and push new value

texts:
Is there a simpler/shorter/better way to do this?

let obj={a:1,b:[1,2]}

function add(key,value){
  if(!obj[key].push){
    obj[key]=[obj[key]]
  }
  obj[key].push(value)
}


texts:
I have a table in my database with 35000 unique URLs. I use them to create my XML sitemaps for the site. I have setup crontab jobs to create automatically new URLs, delete non existing URLs and determine if a URL is valid.

For the last part I use the following function:

function get_url_status($url)
{
    $httpCode = 0;
    $headers = get_headers($url);
    $http_header_info = $headers[0];
    $httpCode = substr($http_header_info, 9, 3);

    if ($httpCode=='200')
    {
        // check in page for noindex and dissable that url
        $metas = get_meta_tags($url);
        if ( isset($metas['robots']) && strpos( strtolower($metas['robots']),  'noindex')!==false  )
        {
            $httpCode = 410;
        }
    }

return $httpCode;
}

This will return to me the HTTP status code - 200 for legal URLs that will be included in sitemap, 400 for not found, 410 for URLs with noindex in them, 301 for redirections, etc.

In my XML sitemaps I include only URLs with status code 200.

My problem is that this function takes around 40 minutes to check the URLs in database. Is there a way to speed things up?


texts: Project Euler 378: Count ordered triplets whose triangular numbers have decreasing number of factors

texts:
Project Euler problem 378 says:

  Let \$T(n)\$ be the \$n\$th triangle number, so \$T(n) = {n (n+1) \over 2}\$.

  Let \$\mathit{dT}(n)\$ be the number of divisors of \$T(n)\$.
  E.g.: \$T(7) = 28\$ and \$\mathit{dT}(7) = 6\$.

  Let \$\mathit{Tr}(n)\$ be the number of triples \$(i, j, k)\$ such that \$1 ≤ i < j < k ≤ n\$ and \$\mathit{dT}(i) > \mathit{dT}(j) > \mathit{dT}(k)\$.
  \$\mathit{Tr}(20) = 14\$, \$\mathit{Tr}(100) = 5772\$ and \$\mathit{Tr}(1000) = 11174776\$.

  Find \$\mathit{Tr}(60\,000\,000)\$.
  Give the last 18 digits of your answer.

This is my attempt at solving it:

def t(n):
    tri_num = (n * (n+1))//2
    return tri_num

#finding nth triangle numbers

def dt(n):
    count = 0
    for i in range(1,t(n)+1):
        if t(n)%i == 0:
            count += 1
    return count

#finding nth triangle numbers' total number of dividers

def factors(n):
    factors = []
    for i in range(1,t(n)+1):
        if t(n)%i == 0:
            factors.append(i)
    return factors
#finding nth triangle number's dividers

def tr(n):
    triplesnum = 0
    triples = [(i, j, k) for i in range(n) for j in range(n) for k in range(n) if 1 <= i < j < k <= n and dt(i) > dt(j) > dt(k)]
    for i in triples:
        triplesnum += 1
    return triplesnum
while True:
    n = int(input("N =???"))
    print("triples number",tr(n))

#solution

I am new to python; I only know at most the loops,list comprehension, functions, and some class.  I am sure this problem can be solved more simply.

Although I see this code as a success considering my knowledge, it works too slowly for me after 3-digit values of n.

Is there an improvement I can make with my current knowledge?  If not, what should I be learning about next?

Note: I know some of the code is not necessary, but I used them as a testing material in the further functions.


texts: Constructing NewsArticle objects from a database table

texts:
This class seems to be able to represent the data stored in any possible database table:

public class DbTable {
    private Set<Map<String, Object>> tblData = new HashSet<Map<String, Object>>();

    public DbTable(Connection dbConn, String tblName) throws Exception {
        PreparedStatement prpStmt = dbConn.prepareStatement("SELECT * FROM " + tblName);
        ResultSet queryResults = prpStmt.executeQuery();
        ResultSetMetaData metaData = queryResults.getMetaData();

        while (queryResults.next()) {
            Map<String, Object> row = new HashMap<String, Object>();

            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String colName = metaData.getColumnName(i);
                String colClassName = metaData.getColumnClassName(i);
                Class colClass = Class.forName(colClassName);
                Object colValue = colClass.cast(queryResults.getObject(i));

                row.put(colName, colValue);
            }
            tblData.add(row);
        }
    }

    // ...
  }

Then, I'd like to construct objects to represent news articles based on the Map<String, Object> retrieved via DbTable, like this:

public class NewsArticle {
    private final String Id, Title, Story;
    private final Timestamp Pubdate;

    public NewsArticle(Map<String, Object> row) {
        String id = null; String title = null; String story = null;
        Timestamp pubdate = null;

        for (Map.Entry<String, Object> col : row.entrySet()) {
            if (col.getKey().equals("id")) {
                id = (String) col.getValue();
                continue;
            }
            if (col.getKey().equals("pubdate")) {
                pubdate = (Timestamp) col.getValue();
                continue;
            }
            if (col.getKey().equals("title")) {
                title = (String) col.getValue();
                continue;
            }
            if (col.getKey().equals("story")) {
                story = (String) col.getValue();
            }
        }

        Id = id;
        Pubdate = pubdate;
        Title = title;
        Story = story;
    }

    // ...
}

So, a Map represents a database table entry as the column name, mapEntry.getKey(), and the data in the column, mapEntry.getValue().

Because I lose type safety, I'm thinking this is rubbish. But, (1) users of DbTable most certainly should know the type of each column. (2) if they do not know the type, then they can use reflection as a backup way to make DbTable usable.

This solution seems to work fine. Any opinions about losing that type safety? How could I improve this?


texts:
I have a number of custom events that a class might or might not subscribe to.

Action<Game1, MoveEventArgs> MoveEvent;
Action<Game1, InitializeEventArgs> InitializeEvent;
Action<Game1, DrawEventArgs> DrawEvent;
Action<Game1, LoadContentEventArgs> LoadContentEvent;

Each event is currently very similar just containing a number of properties such as:

public class MoveEventArgs : EventArgs
{
    public Vector2 Direction { get; set; }
}

public class LoadContentEventArgs : EventArgs
{
    public ContentManager Content { get; set; }
}

Some have more some have less. These are likely to be either expanded on or changed in the future if I need to pass more information.

A method subscribing to these events will generally access these arguments using them in someway that is specific to that event. For example a move event may look like this.

public void Move(object o, MoveEventArgs e)
{
    spriteInfo.Position = new Vector2(
        spriteInfo.Position.X + e.Direction.X, spriteInfo.Position.Y + e.Direction.Y
    );
}

And a content event may look like this.

public virtual void LoadContent(object o, LoadContentEventArgs e)
{
    spriteInfo.Texture = e.Content.Load<Texture2D>(spriteInfo.TextureName);
}

I would like to bundle these in someway so I can easily pass them into other functions. Such as in a list or dictionary.

I have come up with two solutions.
The first is to change my event declarations from:

Action<Game1, InitializeEventArgs> InitializeEvent;
public virtual void Initialize(object o, InitializeEventArgs e) { }

to:

Action<Game1, EventArgs> InitializeEvent;
public virtual void Initialize(object o, EventArgs e)
{
    InitializeEventArgs initializeEventArgs = (InitializeEventArgs)e;
}

This will allow me to create data stuctures using the type Action<Game1, EventArgs> but will mean I lose the typing on my event subscriber methods possibly resulting in cast exceptions.

The second is creating a struct with my Events in which I can pass to classes/methods.

public struct Events
{
    public Action<Game1, MoveEventArgs> MoveEvent { get; set; }
    public Action<Game1, InitializeEventArgs> InitializeEvent { get; set; }
    public Action<Game1, DrawEventArgs> DrawEvent { get; set; }
    public Action<Game1, LoadContentEventArgs> LoadContentEvent { get; set; }
}

Which I can then use to subscribe to the event in the appropriate class/method using:

Events.InitializeEvent += Initialize;

This seems good but it could potentially become a very large struct especially if I were to have a large number of events.

So I guess my main question is does anyone have improvements for these ideas or something different?


texts: Determining what functions should be implemented in this user-authentication class

texts:
Long story short, I would like to use OOP for my new PHP project. It has a "login" requirement (i.e. user will first need to enter the username and password (login.php), if it's correct, it will be redirected to index.php and then fetch some products information). Also there will be a settings page that allows user to change the password, and email if necessary.

In summary:

When user attempts to login, the program will check if the username, password entered is correct or not. If it's correct, username (or maybe the whole User object) will be saved in the $_SESSION.
When the user settings page is loaded, it will display all user related fields on screen (i.e. by using $_SESSION).
The user can make changes in the user settings pages and data should be saved to the database.

I have this User class:

class User {
     private $username;
     private $email;
     private $hashed_password;
     private $dob;
...

     public __construct($user) {
          $this->username = $user;
     }

     public function isPasswordCorrect($userenteredpassword) {
           $this->loadFromDatabase();
           //hashed userenteredpassword, compare it against $this->hashed_password
           //if it matches, return true, otherwise return false.
     }

     public function saveToDatabase() {
          //save info to database
     }

     public function loadFromDatabase() {
         $row = select fields from user table where username = $this->username limit 1
         if ($row is found) {
              $this->hashed_password = $row['hashed_password'];
              $this->dob = $row['dob'];
              ...
         }
     }
}//class

However, I was told that the function isPasswordCorrect shouldn't be implemented inside class User, as it is not its job to determine whether the login is valid or not.  Instead, I should create an authService helper and use it to determine whether the login is good or not.

Now, this makes me wonder if the rest of my User class design is okay or not. If I shouldn't put the password checking function in the User class, then is it okay to implement the database related functions in User?  How do I determine which function should be implemented in the class?  Should I follow Single Responsibility principle? Wouldn't it be too extreme?


texts: Checking if each char in a string is a decimal digit

texts:
I had to write a program that would verify that a string contains any digits beside numbers 0-9 and the first '-' sign to indicate if pos/neg. The algorithm works like I want it to, but is there a better way of writing it, e.g. streamlining it, making it shorter?

bool isNum(string number) {
    // Checks if first char in buffer contains invalid digits
    // Needed because any negative sign after the one used to indicate negative sign.
    if (!((number[0] >= '0' && number[0] <= '9') || number[0] == '-' || number[0] == '+'))
        return false;

    // Checks if each digit after the first is anything but 0-9
    for (int i = 1; number[i] != '\0'; i++) {
        if (number[i] < '0' || number[i] > '9')
            return false;
    }
    // If neither statement returns false, returns true by default
    return true;
}


texts: Square root calculation in Scheme (SICP Exercise 1.7)

texts:
I have done exercise 1.7 in SICP (calculate square root precision when change in guesses is under a certain value), but I am calling the change-in-precision function twice in each iteration, which disturbs me. I wonder if there is a better way to implement this.

(define (average . ns) (/ (apply + ns) (length ns)))

(define (change-in-precision guess x)
  ( - (- guess (average guess (/ x guess)))))

(define (sqrt guess x)
  (if (< (abs (change-in-precision guess x)) (/ 0.00000001 guess))
  (+ guess (change-in-precision guess x))
  (sqrt (+ guess (change-in-precision guess x)) x)))


texts: Creating a form based on flight intentory

texts:
I have an Angular 5 project with a method named createForm. It will basically create just a form. However, the form created changes depends on the flight inventory code. If flight inventory code id TAG_ON I will create a form omitting messagePrefixSMSValidator and also form control named message to empty.

createForm() {

    this.formGroup = this.fb.group(
      {
        defaultTemplate: [this.defaultInitialValue],
        language: [null, Validators.required],
        message: [ this.messagePrefix ? this.messagePrefix:'', [Validators.required]],
        longUrl: ['']
      },
      {
        validator: [
                    hasUrlTagValidator(TemplatesService.urlTag),
                    messagePrefixSMSValidator(this.messagePrefix? this.messagePrefix: null, 'message')
                  ]
      }
    );

   if(this.flight.inventory.code === FlightInventoryCode.TAG_ON) {

    this.formGroup =  this.fb.group(
      {
        defaultTemplate: [this.defaultInitialValue],
        language: [null, Validators.required],
        message: [ '', [Validators.required]],
        longUrl: ['']
      },
      {
        validator: [
                    hasUrlTagValidator(TemplatesService.urlTag),
                  ]
      }
    );
   }

  }

Is there a way to rewrite my code so that it looks simple?


texts: Checking if a user exists on the database and return user in JSON format

texts:
below code takes data (email,password,user type) from $_POST[] and use them to search whether a user exists on the database. If yes sends a JSON object to the client and also stores cookies on the browser.

I have two user types and have them stored in two tables in my database.

User_Table
Driver_Table

I need to change the database tables depending on the user type because I have used common SQL statement for both.
For that, I have implemented selection($userType) in credentials.php

SQL Statement

$sql = "SELECT * FROM $credentials->userTable WHERE email='$credentials->email'";

./lib/database.php contains the database connection details and connects to the database.

in Log_In.php

include "./lib/user.php";
include "./lib/credentials.php";
include "./lib/database.php";

$userDetails = json_decode($_POST["m"]);
$credentials = new credentials($userDetails);
$sql = "SELECT * FROM $credentials->userTable WHERE email='$credentials->email'";
$result = $conn->query($sql);

//checking the user details
if($result->num_rows === 1) {
    $details = $result->fetch_assoc();
    $validate = password_verify($credentials->password,$details["userPassword"]);

        if($validate === TRUE){
            if($login_record === TRUE){
                $user = new user($details);
                $user->userType = $credentials->userType;
                $user->loggedInStatus = true;
                $credentials->setCookies($user);
                echo json_encode($user);
                $conn->close();
                }
        }
        else {
            echo "error";
            $conn->close();
            }

}

In credentials.php

class credentials {

    public function __construct ($credentials) {

        $this->email = $credentials->email;
        $this->password = $credentials->password;
        $this->userType = $credentials->userType;
        $this->userTable = $this->selection ($credentials->userType);
    }

    public function selection ($userType) {
        if ($userType === 'driver') {
            return "Driver_Details";

        }
        if ($userType === 'passenger') {
            return "User_Details";
        }

    }

    public function setCookies ($user) {

        foreach ($user as $key => $value) {
           setcookie($key,$value,time()+86400,"/");
        }
        setcookie("t",time(),time()+86400,"/");

    }
}

in user.php

class user {
    public function __construct ($details) {
         $this->userName = $details["name"];
         $this->userLocation = $details["country"];
         $this->userId = $details["User_ID"];
         $this->loggedInStatus = false;
         if (isset($details["driverVehicle"])) {
             $this->userVehicle = $details["driverVehicle"];
         }

    }
}

I need to check the type of user and change the tables to use more than one time in different php files.

I'm looking for some expert ideas and suggestions on a better way to change the database table depending on the user type. Mostly because I need to use that on more different php files.


texts:
I'm given two sorted arrays, arr1 and arr2. They can either be of the same length or arr2 will be longer than arr1. I implemented a method findDuplicates that returns an array of all numbers that are both in arr1 and arr2. Note that the output array should be sorted in an ascending order.

I know there are better solutions than the one I came up with. What I'm trying to understand is the space complexity of the solution I came up with.

  static int[] findDuplicates(int[] arr1, int[] arr2) {
   // your code goes here
   HashMap<Integer, Integer> table = new HashMap<>();
   ArrayList<Integer> returnlist = new ArrayList<Integer>();
   int arr1Length = arr1.length;
   int arr2Length = arr2.length;

   // this is for the first array
   for(int i=0; i<arr1Length; i++){
      int n = arr1[i];
      table.put(n, 1);
   }

   for(int i=0; i<arr2Length; i++){
     int n = arr2[i];

     if(table.containsKey(n)){
       returnlist.add(n);
    }
  }
  int[] arr = new int[returnlist.size()];

  for(int i=0; i<=returnlist.size()-1; i++){
    arr[i] = returnlist.get(i);
  }
  return arr;
} // end of method

Since I created a temporary Hashtable and an ArrayList, and then another array to return the duplicates is my space complexity \$O(n^3)\$. I know its greater than \$O(n)\$. If someone can help me understand this better, I would really appreciate it.


texts:
I have the following HTML structure for a form (simplified):

<form class="form">

First

Last

Whatever

City

Country

Phone

</form>

As I don't have any control over the output, I need to reorder the columns by using JavaScript:

const form = (() => {
  const colClassName = 'formCol';
  const rowClassName = 'formRow';
  const clearClassName = 'clear';

  function createRow(elForm) {
    const elRow = document.createElement('div');
    const elClear = document.createElement('div');
    elRow.className = rowClassName;
    elClear.className = clearClassName;
    elRow.appendChild(elClear);
    elForm.insertAdjacentElement('beforeEnd', elRow);

    return elRow;
  }

  function moveColumn(elForm, elRow, colName) {
    const elCol = elForm.querySelector(`.${colClassName}[data-id='${colName}']`);
    elRow.insertAdjacentElement('afterbegin', elCol);
  }

  function removeEl(el) {
    el.parentNode.removeChild(el);
  }

  function reorder(elForm, order) {
    const elRows = elForm.querySelectorAll(`.${rowClassName}`);
    const maxRows = Math.max(elRows.length, order.length);
    let elCol;

    for (var i = 0; i < maxRows; i++) {
      if (order[i]) {
        if (!elRows[i]) {
          elRows[i] = createRow(elForm);
        }

        if (!Array.isArray(order[i])) {
          moveColumn(elForm, elRows[i], order[i]);
        } else {
          for (j = order[i].length - 1; j >= 0; j--) {
            moveColumn(elForm, elRows[i], order[i][j]);
          };
        }
      } else {
        elCol = elRows[i].querySelector(`.${colClassName}`);

        if (!elCol) {
          removeEl(elRows[i]);
        }
      }
    }
  }

  return {
    reorder,
    // other functions for form
  };
})();

form.reorder(document.querySelector('.form'), [
  ['Last', 'City'],
  'First',
  'Country',
  'Phone',
]);

It does the following:

Reorders the elements as specified in the array (multiple columns).
Does not delete columns if they are not in the array (see column "Whatever").
Creates new rows if necessary and deletes empty rows

While that works as is (see https://jsfiddle.net/6cy4mjvd/), I don't know if there are ways to improve readability / code in general, e.g. it feels wrong how I currently create new rows and modify elRows and also that I  pass elForm to all helper functions... and probably a few other spots.

Btw. I plan on adding other functions other than reorder to modify the form. That's why I return an object (line // other functions for form) in the function.


texts: Is this an ok implementation of an UnorderedPair?

texts:
I want to create pair, where new UnorderedPair(ObjA, ObjB) == UnorderedPair(ObjB, ObjA) returns true. I also want to avoid any (un)boxing.

Have I gone about this in the correct way?

public struct UnorderedPair<T> : IEquatable<UnorderedPair<T>>
{
    public T A;
    public T B;

    public UnorderedPair(T a, T b)
    {
        A = a;
        B = b;
    }

    public override int GetHashCode()
    {
        return A.GetHashCode() ^ B.GetHashCode();
    }

    public bool Equals(UnorderedPair<T> other)
    {
        return (other.A.Equals(A) && other.B.Equals(B)) ||
               (other.A.Equals(B) && other.B.Equals(A));
    }

    public override bool Equals(object obj)
    {
        return Equals((UnorderedPair<T>)obj);
    }

    public static bool operator ==(UnorderedPair<T> a, UnorderedPair<T> b)
    {
        return a.Equals(b);
    }

    public static bool operator !=(UnorderedPair<T> a, UnorderedPair<T> b)
    {
        return !(a == b);
    }
}


texts:
I combined the ideas from this answer and a comment to this question to create a new instance of a type extracted from a type list. The index of the desired type within the type list is provided at run time, only.

#include <iostream>
#include <memory>

class Base
{
public:
    virtual void foo() = 0;
};

class A : public Base
{
public:
    void foo() override
    {
        std::cout << "A" << std::endl;
    }
};

class B : public Base
{
public:
    void foo() override
    {
        std::cout << "B" << std::endl;
    }
};

template <class... Types>
class type_list {};

using list_t = type_list<A,B>;

template <class... Types>
static constexpr std::size_t length = sizeof...(Types);

template <std::size_t idx, class... Types>
class extract
{
    static_assert(idx < sizeof...(Types), "index out of bounds");

    template <std::size_t i, std::size_t n, class... Rest>
    struct extract_impl;

    template <std::size_t i, std::size_t n, class T, class... Rest>
    struct extract_impl<i, n, T, Rest...>
    {
        using type = typename extract_impl<i + 1, n, Rest...>::type;
    };

    template <std::size_t n, class T, class... Rest>
    struct extract_impl<n, n, T, Rest...>
    {
        using type = T;
    };

public:
    using type = typename extract_impl<0, idx, Types...>::type;
};

template <std::size_t idx, class TypeList>
struct type_list_extract;

template <std::size_t idx, template <class...> class TypeList, class... Types>
struct type_list_extract<idx, TypeList<Types...>>
{
    using type = typename extract<idx, Types...>::type;
};

template <std::size_t idx, class TypeList>
using type_list_extract_t = typename type_list_extract<idx, TypeList>::type;

template<std::size_t idx, bool done = false, class... Types>
struct action_wrapper
{
    static std::unique_ptr<Base> get_instance_by_id(std::size_t id)
    {
        if (id == idx)
        {
            using type = type_list_extract_t<idx, Types...>;
            return std::make_unique<type>();
        }

        static constexpr auto cont = length<Types...> < idx + 1;
        return action_wrapper<idx + 1, cont, Types...>::get_instance_by_id(id);
    }
};

template<std::size_t idx, class... Types>
struct action_wrapper<idx, true, Types...>
{
    static std::unique_ptr<Base> get_instance_by_id(std::size_t id)
    {
        return nullptr;
    }
};

static std::unique_ptr<Base> get_instance_by_id(std::size_t id)
{
    return action_wrapper<0, false, list_t>::get_instance_by_id(id);
}

int main()
{
    std::unique_ptr<Base> ptr = get_instance_by_id(1);
    if (ptr)
    {
        ptr->foo();
    }
}


texts: C# MySQL Database insert list of components

texts:
I am writing a function to have insert a list of strings into a MySQL database and C#.

The process of creating the list of Components:

User has to scan multiple barcodes and have them stored in a list.
The goal is to take that list and insert it into a MySQL database on the click of a submit button.

Is the function below the best way to insert a list of strings into MySQL?

public static void insert_db(List components, int id, string product)
{
    string sql = "INSERT INTO table (id, Product, Component) VALUES ";
    for(int i = 0; i < components.Count(); i++))
    {
        sql += "(" + id +"," + product + "," + component + ")";
        if(i+1 != components.Count()) // Make sure its not the last value in the list
        {
            sql = sql + ",";
        }
    }
    sqlCommand InsertDataCmd = new SqlCommand(sql, dbConn);
    try
    {
        InsertDataCmd.ExecuteNonQuery();
    }
    catch (SqlException sq)
    {
        MessageBox.Show(sq.Message);
    }
}


texts: Shuffling and hiding views specified by parameters

texts:
In my Angular app, users click on different icons. When a user clicks on respective icon, I can show the icons gallery, as well shuffle the view.

Apart from this shuffling functionality, I need to hide whatever other gallery is already open.

For that, I've written the following function, but, I think it could use some refactoring.

$scope.galleryMenu = function ( GalleryType ) {

            var hideGallery = (function (type) {

                return {

                    galleryVideoShow : function () {

                        //closing others
                        $scope.contractorShow = false;
                        $scope.galleryPhotoShow = false;
                    },

                    contractorShow : function () {
                        //closing others
                        $scope.galleryPhotoShow = false;
                        $scope.galleryVideoShow = false;

                    },

                    galleryPhotoShow : function () {

                       //closing others
                        $scope.contractorShow = false;
                        $scope.galleryVideoShow = false;

                    }

                }

            })();

            $scope.$watch('viewProjectInfo', function ( newValue, oldValue ) {

                if(!newValue) return;

                $scope.photos = $scope.viewProjectInfo.ImagePaths;

                $scope[GalleryType] = !$scope[GalleryType];
                $scope.shownGallery =  GalleryType;

                hideGallery[GalleryType](); //manually close other open gallery

                $('html, body').animate({scrollTop:$(document).height()}, 'slow');

            });

        };


texts: Haskell searching through a large textfile efficiently

texts:
I have been given a list xs and a function f, and I want to know stuff like how many x <- xs satisfy (f x) `elem` xs or which ones do, etc. However, the problem is that the list xs is available only as an external file.

import Data.Char
import System.IO.Strict
import qualified Data.Set as Set

vowel x = elem x "aeiou"

toPigLatin :: String -> String
toPigLatin word
    | vowel (head word) = word ++ "ay"
    | not $ null [x | x <- word, vowel x] = let (v, c) = span (not.vowel) word in c ++ v ++ "ay"
    | otherwise = word

wordList = lines <$>  System.IO.Strict.readFile "toyWordSet"
wordSet = Set.fromList <$> wordList

good :: String -> IO Bool
good word = (Set.member (toPigLatin word)) <$> wordSet

mapMBool :: (a -> IO b) -> [a] -> IO [b]
mapMBool f l = do
                case l of
                    [] -> return []
                    (x:xs) -> do
                            b1 <- f x
                            bs <- mapMBool f xs
                            return (b1:bs)

Ultimately, I want to compute wordList >>= mapMBool good, which is a value of type IO [Bool] which have True at the positions where the desired property is satisfied.

Now, I have three main concerns:

When I run my code with a toyWordSet, it runs fine but I ultimately intend to replace it with /usr/share/dict/words, on which my PC freezes. How do I make my program more efficient?
Writing a function like mapMBool is not the most elegant idea ever. How can I do this more elegantly?
For some reason, I get some strange exceptions, when I try to use the lazy readFile instead of the strict version. What is happening? Why must I use strictness?

Other general comments on the coding style or practice is also welcome.


texts: Simpler way of showing, hiding & disabling elements

texts:
I'm currently having this code & looking for a simpler and shorter way of showing, hiding & disabling my elements...

$("#chReportData").click(function(){
            if($(this)[0].checked){
                $("#reportDataOptions").show();
            } else {
                $("#ReportDataStatusOptions").hide();
                $("#reportDataOptions").hide();
                $('#chkReportPermission').attr('checked', false);
                $('#chReportDataStatus').attr('checked', false);
                $('#chReportDataCummulative').attr('checked', false);
                $('.allowedUpload').attr('checked', false);
                $('.allowedDelete').attr('checked', false);
            }
        });

        $("#chReportDataStatus").click(function() {
            if ($(this)[0].checked) {
                $("#ReportDataStatusOptions").show();
            } else if ($('#chReportDataCummulative').is('checked')) {
                $("#ReportDataStatusOptions").hide();
                $('.allowedUpload').attr('checked', false);
                $('.allowedDelete').attr('checked', false);
            } else {
                $("#ReportDataStatusOptions").hide();
                $('.allowedUpload').attr('checked', false);
                $('.allowedDelete').attr('checked', false);
            }
        });

It works fine, I'm just looking for a simpler way... If you know of a shorter & simpler way, please share...

Added HTML...

Report Data:<asp:CheckBox ID="chReportData" runat="server" CssClass="floatL shad1 trans1" ClientIDMode="Static"/>

                    Report Management:<asp:CheckBox ID="chkReportPermission" runat="server" CssClass="floatL shad1 trans1" ClientIDMode="Static"/>

                    <asp:RadioButton ID="chReportDataStatus" runat="server" ClientIDMode="Static" CssClass="floatL shad1 trans1" GroupName="reportData" Text="Report Type: Status" TextAlign="Left"/>

                    <asp:RadioButton ID="chReportDataCummulative" runat="server" ClientIDMode="Static" CssClass="floatL shad1 trans1" GroupName="reportData" Text="Report Type: Cummulative" TextAlign="Left"/>

                    Upload Files <asp:CheckBox ID="chkAllowedUpload" runat="server" CssClass="floatL shad1 trans1" class="allowUpload"/>

                    Delete Files <asp:CheckBox ID="chkAllowedDelete" runat="server" CssClass="floatL shad1 trans1" class ="allowDelete"/>


texts:
I have created the following function in Swift for this library I am writing, which joins two arrays on a key (extracted using given closures), and then groups them by key in a [T:[S]] where S is the result type (also through a given closure).

extension Array {
    /// Joins the array with another array on a specific key, and then gives two matching elements to a closure to create a result type.
    /// Groups the result by key. Faster than `.join().groupBy()`
    ///
    /// :param: otherArray the other array to join
    /// :param: thisKeyClosure the closure that extracts the key from this array
    /// :param: otherKeyClosure the closure that extracts the key from the other array
    /// :param: resultClosure creates a resulttype from two inputtypes
    func groupJoin<R, S: Equatable, P>(otherArray: [R], thisKeyClosure: T -> S, otherKeyClosure: R -> S, resultClosure: (T,R) -> P) -> [S:[P]] {
        var result: [S:[P]] = [:]
        for thisItem in self {
            for otherItem in otherArray {
                let thisKey = thisKeyClosure(thisItem)
                if thisKey == otherKeyClosure(otherItem) {
                    if result[thisKey] == nil {
                        result[thisKey] = []
                    }
                    result[thisKey]!.append(resultClosure(thisItem, otherItem))
                }
            }
        }
        return result
    }
}

groupBy and join are methods in my own library, implementation groupBy and join

An example usage might be this method call:

class Person {
    var age: Int
    var name: String
}

class Dog {
    var owner: String
}

var arrayOfPeople: [Person] = [...]
var arrayOfDogs: [Dog] = [...]

let peopleWithDogs = arrayOfPeople.groupJoin(arrayOfDogs, {$0.name}, {$0.owner}, {$1})
// Joins both arrays on person.name and dog.owner, grouped in the array by name of owner, linked to an array of Dogs


texts:
My current task is to extend some JavaScript of a framework we are using. A pop-up should slide in, instead of just appear in the middle of the window.
So I have overridden one of the framework's methods, and do at the end this:

AdfDhtmlPage.prototype.showMessages = function (componentId) {

// Some code here

function slideIn() {
  var maxTop = windowHeight - (thisHeight + 18);
  var tempTop = parseInt(popupElement._rootElement.style.top);

  if (maxTop >= tempTop) {
    setTimeout(function () {
      AdfPage.PAGE.clearMessages(componentId);
    },5000);
    return;
  }

  popupElement._rootElement.style.top = tempTop - 1 + 'px';
  setTimeout(slideIn, 20);
}
slideIn();
}

Everything worked just fine, but then I thought that the slideIn method should somehow be a behavior of the popupElement.
During refactoring I encountered a behavior that was new to me and which is here called binding loss.
So what I came up with is this:

AdfDhtmlPage.prototype.showMessages = function (componentId) {
    // Some code here
    popupElement._slideIn(popupElement, componentId);
}

AdfDhtmlSimpleFloat.prototype._slideIn = function(element, componentId) {
    var maxTop = AdfAgent.AGENT.getWindowHeight() - (element.getHeight() + 18);
    var thisTop = parseInt(element._rootElement.style.top);

    if (maxTop >= thisTop) {
        setTimeout(function () {
            AdfPage.PAGE.clearMessages(componentId);
        },5000);
        return;
    }

    element._rootElement.style.top = thisTop - 1 + 'px';
    setTimeout(function() {
        element._slideIn(element, componentId);
    }, 20);
}

So when calling the _slideIn method of popupElement I need to pass popupElement as argument. So I can access the objects properties, after the method has been called via setTimeout (When the binding loss happens).

However, this seems odd to me. So I would like to ask you to review my design. Maybe someone comes up with a better solution?

that was, what I wanted to do:

AdfDhtmlPage.prototype.showMessages = function (componentId) {
    // Some code here
    popupElement._slideIn(componentId);
}

AdfDhtmlSimpleFloat.prototype._slideIn = function(componentId) {
    var maxTop = AdfAgent.AGENT.getWindowHeight() - (this.getHeight() + 18);
    var thisTop = parseInt(this._rootElement.style.top);

    if (maxTop >= thisTop) {
        setTimeout(function () {
            AdfPage.PAGE.clearMessages(componentId);
        },5000);
        return;
    }

    this._rootElement.style.top = thisTop - 1 + 'px';
    setTimeout(this._slideIn, 20);
}


texts: Looking for matching names among two text files

texts:
I'm trying to enhance the execution speed of my below code. I am using only vanilla JavaScript. I would be willing to bring in additional libraries and plugins as long as they will enhance the overall speed of the code.

The goal is to have the absolute fastest execution time of the below code.

Currently, it executes from start to finish in approx. 320 - 350 ms. I want to make any modifications necessary to make it perform faster than that, particularly with exponentially larger datasets.

Setup

I have two .txt files, names and data.
names contains a list of last names, one name per line:

Nader
Sanford
Kovacek
Lynch
etc...

data contains a much longer list, of first names, last names, a comma and a value:

Kailee Huel,2
Arianna Runolfsson,4
Marshall Kuhn,3
Cristina Huel,4
Garnett Medhurst,3
etc...

Task

Iterate through data.txt using the last names in names.txt. If any of the last names from names.txt have a match in data.txt, increment a counter with the value on that line (after the comma). Some last names are repeated in both names.txt and data.txt. Output the final value of the counter.

<script type="text/javascript">

  var names,
  data;

    // doc rdy
    document.onreadystatechange = function(){
      console.time('execution length');
      if( document.readyState == "complete" ){
        init();
      }
    }

    // setup
    function init(){
      var base      = "data/sample2/",
          namesFile = base+"names.txt",
          dataFile  = base+"data.txt";

      loadFile(namesFile, function(e){
        names = e;
        loadFile(dataFile, function(ev){
          processData(ev);
        });
      });
    }

    function processData(e){
      var counter = 0;
      var namesProcessed = {};

      // for each last name,
      for( var i=0; i<names.length; i++ ){
        // if "data object" contains "this name" AND "this name" does not exist in rmvdNames, add its val to counter
        if( e.hasOwnProperty(names[i]) && ! namesProcessed.hasOwnProperty(names[i]) ){
          counter += e[names[i]];
          namesProcessed[names[i]] = true;
        }
      }
      console.log(counter);
      console.timeEnd('execution length');
    }

    // ajax loading
    function loadFile( filename, callback ){
      var client = new XMLHttpRequest();
      var result;
      client.open('GET', filename);
      client.onreadystatechange = function() {
        if( client.readyState==4 && client.status==200 ){
          result = client.responseText.split("\n");
          // custom handling for the data set..
          if( result[0].search(',') !== -1 ){
            result = arrCSVtoObj(result);
          }

          callback(result);
        }
      }
      client.send();
    }

    // converts an array of CSV to a key:value object
    function arrCSVtoObj(csvArr) {
      var obj = {};

      // for each line in the array,
      for( var i=0; i<csvArr.length; i++ ){
        // split into key:value on comma
        var split = csvArr[i].split(",");
        var key =  getLastName(split[0]);
        var val = parseInt(split[1]);

        // assign the new property to the object
        if( ! obj.hasOwnProperty(key) ){
          if( val > 0 ){
            obj[key] = val;
          }
        }else{
          obj[key] += val;
        }
      }
      return obj;
    }

    function getLastName(e){
      var nameArr = e.split(" ");
      return nameArr[1];
    }

  </script>

I know the biggest time sink in this script are the loops (there are several: looping through object properties, looping through data to parse it, etc). How can I speed these actions up? What measures can I take to improve the above code and optimize absolute speed with large datasets?


texts:
This is the biggest program I have ever made. I created a Rock Paper Scissors game. It asks you if you want to play, takes your input, compares it with the random computer input, gives you the outcome, and then asks if you want to play again.

I am POSITIVE that I could have done this in fewer lines of code, so I would absolutely appreciate feedback. I'm brand new to Python. I am currently using Python 3.

import random
import sys
#begin the game and then loop after the first play.

def play():
    while True:
        p_choice = input("What do you choose?")
        cpu_random = random.randint(1,3)
        cpu_choice = cpu_random
        if cpu_random == 1:
            cpu_choice = "Rock"
        elif cpu_random == 2:
            cpu_choice = "Paper"
        elif cpu_random == 3:
            cpu_choice = "Scissors"

#Compare the data given by the user to the CPU

        def compare():

            play_again = None
#Tie outcome
            if p_choice == cpu_choice:
                print("Tie!")
                play_again = input("Play again?")

#Rock outcome

            elif p_choice == "Rock" and cpu_choice == "Paper":
                print("You Lose!")
                play_again = input("Play again?")
            elif p_choice == "Rock" and cpu_choice == "Scissors":
                print("You Win!")
                play_again = input("Play again?")

#Paper outcome

            elif p_choice == "Paper" and cpu_choice == "Scissors":
                print("You Lose!")
                play_again = input("Play again?")
            elif p_choice == "Paper" and cpu_choice == "Rock":
                print("You Win!")
                play_again = input("Play again?")

#Scissors outcome

            elif p_choice == "Scissors" and cpu_choice == "Rock":
                print("You Lose!")
                play_again = input("Play again?")
            elif p_choice == "Scissors" and cpu_choice == "Paper":
                print("You Win!")
                play_again = input("Play again?")

#Ask if you want to play again, then give input

            if play_again == "Yes":
                play()
            elif play_again == "No":
                print("Game Over")
                sys.exit()
            else:
                print("Please try again")
                play_again = input("play again?")
                return play_again

        compare()

#ask if player wants to start
def game_start():
    while True:
        begin = input("Would you like to play Rock, Paper, Scissors?")
        if begin == "Yes":
            play()
            return begin
        while begin != "Yes":
            if begin == "No":
                print("Game Over")
                return begin
            else:
                print("Please try again")
                break

game_start()


texts:
I came across a problem where given a array of integer arrays of different lengths [[1,2,3],[4,1,1], [9,2,1]] you need to return an array of arrays, each array containing indices of the arrays (of the input array) such that the corresponding arrays have the same mean: [[0,1],[2]] This seems relatively simple to solve using Python:
def groupByMean(a):
    d,e=[],[]
    for i,j in enumerate(a):
        if sum(j)/len(j)not in e:
            e+=[sum(j)/len(j)]
            d+=[[i]]
        else:
            d[e.index(sum(j)/len(j))]+=[i]
    return d

However, when trying to solve this in Java this was my approach: using a hashmap, map each new mean to a list of the corresponding indices. Then iterate the hashmap, to get the arraylists and convert them to int[] arrays and construct the 2d array ...
Is there a simpler approach to solve this using Java?
This is my java code - looking for a different way to solve this:
public static void main(String[] args) {
    int[][] arr = { { 1, 2, 3 }, { 2, 3, 4 }, { 2, 4, 0 } };
    for (int[] nums : groupBySum(arr)) {
        for (int n : nums) {
            System.out.print(n + " ");
        }
        System.out.println();
    }
}

public static int[][] groupByMean(int[][] arr) {
    Map<Double, List<Integer>> map = new HashMap<>();
    int i = 0;
    for (int[] nums : arr) {
        double average = getAverage(nums);
        if (!map.containsKey(average)) {
            List<Integer> indices = new ArrayList<>();
            indices.add(i);
            map.put(average, indices);
        } else {
            map.get(average).add(i);
        }
        i++;
    }
    int[][] result = new int[map.size()][];
    int row = 0;
    for (List<Integer> indices : map.values()) {
        result[row] = new int[indices.size()];
        for (int k = 0; k < indices.size(); k++) {
            result[row][k] = indices.get(k);
        }
        row++;
    }
    return result;
}

public static double getAverage(int[] arr) {
    int sum = 0;
    for (int num : arr) {
        sum += num;
    }
    return ((double) sum) / arr.length;
}


texts: Is this proper usage of "safe publication"?

texts:
With regards to Safe Publication, consider this piece of code:

public class Test {
    public static void main(String args[]) {
        ThreadB t = new ThreadB();
        t.start();
        t.Grab(new Bag("HI"));
    }
}

class Bag {
    private String item; // <-- no final here

    public String Item() {
        return item;
    }

    public Bag(String item) {
        this.item = item;
    }
}

class ThreadB extends java.lang.Thread {
    private Bag bag;

    public void Grab(Bag bag) {
        this.bag = bag;
    }

    @Override
    public void run() {
        try {
            while (true) {
                if (bag != null) {
                    System.out.println(bag.Item());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Is it guaranteed that thread B sees the item ("HI") in bag,

Or is it true that thread B may in fact see the item in the bag as null, and will never see the item "HI" in the bag?


texts:
I am practicing test-driven development in Python. Feedback about both the tests and the code is appreciated. I'm using luhn algorithm and regex to check credit card numbers for validity.

Here are the tests:

from unittest import TestCase
import luhn_check

class TestLuhnCheck(TestCase):

    def setUp(self):
        pass
    def test_known_sum(self):
        self.assertEquals(67, luhn_check.check_sum("7992739871"))

    def test_check_digit(self):
        self.assertEquals(3, luhn_check.find_check_digit("7992739871"))

    def test_check_valid(self):
        self.assertFalse(luhn_check.is_luhn_valid("abcdefg"))
        self.assertTrue(luhn_check.is_luhn_valid("79927398713"))

    def test_check_invalid(self):
        self.assertFalse(luhn_check.is_luhn_valid("79927398714"))

    def test_regex(self):
        self.assertTrue(luhn_check.check_regex("346340033233241"))
        self.assertFalse(luhn_check.check_regex("996340033233241"))

    def test_check_cc(self):
        #amex
        self.assertTrue(luhn_check.is_valid_cc("346340033233241"))
        #discover
        self.assertTrue(luhn_check.is_valid_cc("6011066253550425"))
        #visa
        self.assertTrue(luhn_check.is_valid_cc("4485332611430235"))
        #mc
        self.assertTrue(luhn_check.is_valid_cc("5463393720504875"))
        #bad:
        self.assertFalse(luhn_check.is_valid_cc("abcdefg"))
        self.assertFalse(luhn_check.is_valid_cc("11abcdefg"))
        self.assertFalse(luhn_check.is_valid_cc("946340033233241"))
        self.assertFalse(luhn_check.is_valid_cc("546339372050487500"))

and here is the module:

import re

def sum_digits(numeric_string):
    return sum([int(d) for d in numeric_string])

def valid_length_cc(cc_candidate):
    return len(cc_candidate) == 16 or len(cc_candidate) == 15

def check_sum(numeric_string):
    odds = numeric_string[:-1][::-2]
    evens = numeric_string[::-2]
    return sum([int(i) for i in odds]) + sum([sum_digits(str(int(i) * 2)) for i in evens])

def find_check_digit(numeric_string):
    return (check_sum(numeric_string) * 9) % 10

def is_luhn_valid(candidate):
    if candidate.isdigit():
        check_digit = int(candidate[-1:])
        return (check_sum(candidate[:-1]) + check_digit) % 10 == 0
    else:
        return False

def is_valid_cc(candidate):

    return check_regex(candidate) and valid_length_cc(candidate) and is_luhn_valid(candidate)

def check_regex(candidate):
    # are the digits correct?
    pattern = "^((4\d{3})|(5[1-5]\d{2})|(6011)|(7\d{3}))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$"
    r = re.compile(pattern)
    return bool(r.match(candidate))


texts:
I have created an central AJAX function (using JQuery) which will be responsible for handling all the AJAX calls in my project.

var ajaxCall = function(_url, _type, _data, _successCallback, _errorCallback, isAsync, _completeCallback){

    // Handling _url
    if(!_url.trim()) throw new Error('Sucess callback is not defined');

    // Handling _type
    if(!_type.trim()) throw new Error('TYPE is not defined');

    // Handling _successCallback
    if(!_successCallback || typeof _successCallback !== "function") throw new Error('Success callback is not defined');

    // Handling _errorCallback
    if(!_errorCallback || typeof _errorCallback !== "function") _errorCallback = function() {};

    // Handling _completeCallback
    if(!_completeCallback || typeof _completeCallback !== "function") _completeCallback = function() {};

    // AJAX configuration object
    var ajaxObj = {
        url : _url.trim(),
        contentType : "application/json",
        type : _type.trim(),
        data : _data || {},
        async: !!isAsync,
        success : function(data) {
            try {
                _successCallback(data);
            } catch (exception) {
                global.logger.i(TAG, 'Exception! ' + exception);
            }
        },
        error : _errorCallback,
        complete: _completeCallback
    };

    // Capturing AJAX call
    return $.ajax(ajaxObj);

};

Let me know if this is a valid way to centralize the AJAX calls.


texts:
I have a program to find the perfect number from 1 to n:

How can this be reduced without changing it?

class PerfectNumber
{
    public static StringBuffer fact(int a)
    {
        StringBuffer sb=new StringBuffer(" ");
        for(int i=1;i<a;i++)
        if(a%i==0)
        {
            sb.append(i+",");
        }
        return sb;
    }
    public static String isPrime(int a)
    {
        int sum=0;
        for(int i=1;i<a;i++)
        {
            if(a%i==0)
        {
            sum+=i;
        }

        }
        if (sum==a)
        {
            return "true";
        }
        else
            return "false";
    }
    public static int perfecrNo(int a)
    {
        int sum=0;
        for(int i=1;i<a;i++)
        {
            if(a%i==0)
        {
            sum+=i;
        }

        }
        return sum;
    }
    public static void main(String[] args)
    {

        System.out.println("--------------------------------------------------------------------------");
        System.out.printf("%s%40s%15s%15s%n","NO","fact","sum","isPrime");
        System.out.println("--------------------------------------------------------------------------");
        for(int i=1;i<100;i++)
        {
            System.out.printf("%n %d %40s\b %15d %15s",i,fact(i),perfecrNo(i),isPrime(i));
        }

    }
}


texts: Command line utility to convert image formats of photos

texts:
Below is some code for a basic command line utility to convert image formats of photos. I'm wondering how any part of it might be written with better style, i.e. how it could be neater, clearer and generally "better".

import os
import argparse
from PIL import Image

def get_arguments():
    ''' Get command line arguments '''
    parser = argparse.ArgumentParser(
        description='A command line tool to convert images to different formats')
    parser.add_argument(
        'input',
        help='full path to the input file or folder')
    parser.add_argument(
        'outext',
        choices=Image.registered_extensions().keys(),
        help='output extension for file')
    parser.add_argument(
        '-n', '--new-name',
        help='give the output file a new name')
    parser.add_argument(
        '-d', '--destination',
        help='set new destination directory')
    parser.add_argument(
        '-R', '--remove-input',
        action='store_true',
        help='also remove the input file')
    args = parser.parse_args()
    if not (os.path.isfile(args.input) or os.path.isdir(args.input)):
        # easier to check file validiy here and keep infile as str,
        # rather than use type checking in parser.add_argument()
        raise parser.error('Unrecognised input type - input must be a file or folder')
    else:
        return args

def convert_image(infile, outext, outname=None, outdir=None, remove_infile=False):
    ''' Convert an image to a new format and optionally:
          * Change the filename
          * Put the file in a new directory
          * Remove the input file
    '''
    indir, inname = os.path.split(infile)
    inname = os.path.splitext(inname)[0]
    if outname is None:
        outname = inname
    if outdir is None:
        outdir = indir
    outfile = os.path.join(outdir, '{}{}'.format(outname, outext))
    if not os.path.isdir(outdir) and outdir != '':
        os.makedirs(outdir)
    Image.open(infile).save(outfile)
    if remove_infile:
        os.remove(infile)

def convert_images(im_dir, outext, outname=None, outdir=None, remove_infile=False):
    ''' run convert_image() for all files in a folder '''
    for item in os.listdir(im_dir):
        if os.path.splitext(item)[1] in Image.registered_extensions().keys():
            convert_image(
                os.path.join(im_dir, item),
                outext,
                outname=outname,
                outdir=outdir,
                remove_infile=remove_infile)

def main():
    args = get_arguments()
    if os.path.isdir(args.input):
        convert_images(
            args.input,
            args.outext,
            outname=args.new_name,
            outdir=args.destination,
            remove_infile=args.remove_input)
    elif os.path.splitext(args.input)[1] in Image.registered_extensions().keys():
        convert_image(
            args.input,
            args.outext,
            outname=args.new_name,
            outdir=args.destination,
            remove_infile=args.remove_input)
    else:
        raise ValueError('Unsupported file format')

if __name__ == '__main__':
    main()


texts: Javascript / ES6 parse value from arrays of objects

texts:
I want to write a generic parser which takes a value, and type and returns label of given value instead.

Currently, this is my code:

import a from "../constants/a"
import b from "../constants/b"
import c from "../constants/c"

const find = (value, fromArray) => fromArray.find((term) => term.value === value);
const getLabel = (of, fromArray) => {
    const value = find(of, fromArray);
    return (value && value.label) || 'No info';
};

export default (value, type) => {
    switch (type) {
        case 'paymentMethod':
            return getLabel(value, paymentMethods);
        case 'paymentTerm':
            return getLabel(value, paymentTerms);
        case 'dateType':
            return getLabel(value, dateTypes);
        default:
            return 'No info';
    }
}

What would be more ES6, faster and concise way to achieve this?


texts: hash image url and if valid store image url

texts:
I am trying to get all image urls which are valid and unique.To make sure i wont end up using the same image again i calculate hash of the image and store it in a text file and read the text file again.if there is any better way to do this, please let me know.Overall any speed optimisation would be really helpful, thanks in advance.

import multiprocessing as mp
import socket
# Set the default timeout in seconds
timeout = 20
socket.setdefaulttimeout(timeout)

from PIL import Image
import hashlib
import os
import pickle

def getImages(val):
    # import pdb;pdb.set_trace()
    #Dowload images
    f = open('image_files.txt', 'a')
    k = open('image_hash.txt', 'a')
    try:
        url=val # preprocess the url from the input val
        local=url.split('/')[-1] #Filename Generation From Global Varables And Rand Stuffs...
        urllib.request.urlretrieve(url,local)
        md5hash = hashlib.md5(Image.open(local).tobytes())
        image_hash = md5hash.hexdigest()
        k.write(image_hash+'\n')
        z = open('image_hash.txt', 'r')
        a = z.readlines()
        image_hash_list = [c.strip('\n') for c in a]
        if image_hash not in image_hash_list:
            os.remove(local)
            f.write(url+'\n')
            print("DONE - " + url)
            return 1
        else:
            os.remove(local)
    except Exception as e:
        # print(e)
        print("CAN'T DOWNLOAD - " + url )
        return 0

files = "Identity.txt"
lst = list(open(files))
lst = [l.replace("\n", "") for l in lst]
lst = lst[::-1]
pool = mp.Pool(processes=12)
res = pool.map(getImages, lst)
print ("tempw")

Here identity.txt file looks like this,

http://url1.com
http://url2.com
...


texts:
I wonder if the following 301 redirect is the best way for my situation. I used this post on SO to give me the following 301 redirect:

RewriteRule locations\.php$ compare-biomass.php [R=301]

What we've done is changed a filename from locations.php to compare-biomass.php.

The new URL should be:

  www.mydomain.com/compare-biomass.php?variable1=1&variable2=2&variable3=3.

The above SO post mentioned that the old query string gets appended to the new filename, which is exactly what I want. However, I found that I was being redirected so that SERVER["DOCUMENT_ROOT"] was being appended to the domain, so the URL was:

  www.mydomain.com/home/mydomain/public_html/compare-biomass.php?variable1=1&variable2=2&variable3=3

I worked out that I had to include the following in my .htaccess file

RewriteBase /

However, now that I've had a problem and this is the very first time I'm doing anything related to Apache, can you please tell me if the .htaccess file I'm using is optimal for me:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^mydomain.com [NC]
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [R=301,L]
RewriteBase /
RewriteRule locations\.php$ compare-biomass.php [R=301]


texts: Remove elements compared with other elements in a Set based on a condition

texts:
Simplified the actual problem to focus on comparing/removing performance.

Given a set S with n elements , find the most optimal way to compare each element to all others until a condition is met that decides if and which item to remove. I experience long runtimes when n is high (e.g. n=3000 has a runtime of 2500ms on an intel i5-6500 cpu)

An element is a Tuple object (itv, t) where itv holds an integer interval value (between 0 and 4, inclusive) and t holds an integer total benefit value.

The condition: Given Tuple s and another Tuple s', if itv == itv', then if t <= t' remove s, else remove s'.

A naïve example. S={(1,20),(0,40),(1,35)}

Compare (1,20) with (0,40): itv != itv', continue.
Compare (1,20) with (1,35): itv == itv', t < t', remove (1,20) from S.
Compare (0,40) with (1,34): itv != itv', return S.

Due to Java's constraints on removing elements while iterating, for-loops are wildly inefficient and I currently use a nested foreach-loop inside an Iterator loop. However, I still feel like it underperforms. This thought is mostly because the code looks terrible, in my opinion.

Below is my implementation. It tries to reduce the amount of unnecessary comparisons as much as possible. My code uses an outer Iterator for comparing the main Tuple to the others. In the case that the interval matches and the main Tuple's total benefit is worse, the inner loop is stopped, the main Tuple is removed and we continue with the next Iterator item. If the inner Tuple is worse, however, then the inner Tuple is marked for deletion and will be deleted at the end of the outer loop iteration.

Does anyone see any glaring mistakes, have any comments about performance (expensive calls) or refactoring for code clarity?

public static HashSet<Tuple> compareAndRemove(HashSet<Tuple> set) {
    HashSet<Tuple> bestTuples = new HashSet<>(set.size()); //Return set
    Collection<Tuple> tupleRemovals = new HashSet<>(); //Tuples to remove this iteration
    Iterator<Tuple> s_iter;

    do {
        set.removeAll(tupleRemovals);
        removedElements += tupleRemovals.size();
        tupleRemovals = new HashSet<>();

        s_iter = set.iterator();
        if (s_iter.hasNext()) {
            Tuple s = s_iter.next();
            if (!s_iter.hasNext()) { //Last element; nothing to compare anymore
                bestTuples.add(s);
                s_iter.remove();
                break;
            }

            //Compare with other
            boolean removeMainTuple = false;
            for (Tuple s_prime : set) {
                boolean equalIntervals = true;
                if (s.equals(s_prime)) continue; //Skip same element

                //Check interval
                if (s.itv == s_prime.itv) {
                    //Decide which Tuple to discard
                    if (s.t <= s_prime.t) {
                        removeMainTuple = true; //Remove Iterator element
                        break;
                    } else {
                        tupleRemovals.add(s_prime); //Remove foreach element
                    }
                }
            }
            //Move current item to return set if it was the best
            if (!removeMainTuple) {
                bestTuples.add(s);
            }
            s_iter.remove();
        }
    } while (s_iter.hasNext());

    bestTuples.addAll(set);

    return bestTuples;
}


texts: Reduce encoded length of UTF-8 encoded Ruby string in C extension

texts:
I'm writing a Ruby extension in C. It's a string processing module working on UTF-8 encoded strings only.

One method, full_width_to_ascii!, converts full width characters to ASCII equivalents (https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms). Essentially, it subtracts an offset of 0xfee0 from any full width characters. As the bang in the name implies, it works on the string in-place.

For example:

full_width_to_ascii!('Ａ Ｂ Ｃ')
=> 'A B C'

In UTF-8, all full-width characters are encoded in 3 bytes each, while ASCII characters are 1 byte each. So while the length of the resulting string in Unicode code points will always be the same, the new UTF-8 encoded length in bytes may be smaller.

I modify the encoded string data (retrieved using StringValueCStr()) and null-terminate it at the new end-point. Finally, I call the following function to reduce the encoded string length:

// from internal.h from MRI
#define STR_NOEMBED      FL_USER1
#define STR_SHARED       FL_USER2 /* = ELTS_SHARED */
#define STR_EMBED_P(str) (!FL_TEST_RAW((str), STR_NOEMBED))

void reduce_encoded_length(VALUE str, int length) {
  if (!STR_EMBED_P(str)) {
    RSTRING(str)->as.heap.len = length;
  } else {
    // see string.c, STR_SET_EMBED_LEN
    RBASIC(str)->flags &= ~RSTRING_EMBED_LEN_MASK;
    RBASIC(str)->flags |= (length) << RSTRING_EMBED_LEN_SHIFT;
  }
}

Looking at the MRI source, the implementation of strings is surprisingly complicated, but from my understanding so far, the function above should be safe for UTF-8 encoded strings.

Does this seem reasonable? Will it break horribly on older Ruby versions? Across platforms?

See also:

https://github.com/ruby/ruby/blob/32674b167bddc0d737c38f84722986b0f228b44b/string.c
http://patshaughnessy.net/2012/1/4/never-create-ruby-strings-longer-than-23-characters


texts: Finding multiples of 3 or 5 with MIPS assembly (Project Euler #1)

texts:
I just started learning MIPS assembly at my university and I would like some feedback on this code. The program is Project Euler Problem #1, finding the sum of multiples of 3 or 5 less than 1000. It works but I am interested to hear what I could do to improve it (best practice, efficiency, etc). I found x86 solutions to this problem but it seems very different than MIPS.

$
# Testing.asm
    .text

main:

    li  $t0, 1000       # number of iterations
    li  $t1, 3          # starting number
    li  $t2, 0          # sum of multiples of 3 or 5
    li  $t6, 3          # constant of 3
    li  $t7, 5          # constant of 5

    loop:
    beq $t1, $t0, end   # end loop if iterator and number of iterations is equal
    div $t1, $t6        # divide iterator by 3
    mfhi    $t3         # $t3 is remainder of iterator divided by 3
    beq $t3, 0, equal       # if remainder is 0, go to equal label
    div $t1, $t7        # divide iterator by 5
    mfhi    $t3         # move remainder into $t3
    beq $t3, 0, equal       # go to equal if remainder is 0
    add $t1, $t1, 1     # increment iterator by 1
    j   loop

    equal:
    add $t2, $t2, $t1       # increment $t2 by iterator
    add $t1, $t1, 1     # increment iterator by 1
    j   loop            # jump back to loop

    end:
    move    $a0, $t2        # load answer into $a0
    li  $v0, 1          # set syscall to print_int
    syscall

    li  $v0, 10         # terminate program
    syscall


texts: Powershell Interaction with Excel (Highlighting Cells)

texts:
I'm using Powershell to compare two, large csv files and output the rows which don't match.  Once the two output files are made (one for the differences on each), I bring them up on Excel.  Now I want to highlight the mismatching fields for the output to be easily read by my customer.  Starting where I open the files in Excel, my current code is:

$excel= New-Object -ComObject "excel.application"
$excel.Visible=$true
$ocomp1=$excel.Workbooks.Open("C:\Users\aja3885.BUD\Desktop\agclink-data-mining\agclink-data-mining\test1.csv")
$ocomp2=$excel.Workbooks.Open("C:\Users\aja3885.BUD\Desktop\agclink-data-mining\agclink-data-mining\test2.csv")
$comp1=$ocomp1.worksheets.item(1)
$comp2=$ocomp2.worksheets.item(1)
$Row=$comp1.UsedRange.rows.count
$Column=$comp1.UsedRange.columns.count
$comp1.UsedRange.EntireColumn.AutoFit()|out-null
$comp2.UsedRange.EntireColumn.AutoFit()|out-null
$i=1
for($i=2; $i -le $row; $i++)
{if($comp1.cells.item($i,1).value2 -eq 'pntval'){if($comp1.cells.item($i,8).value2 -eq 'VALUTYPE=1'){$comp1.cells.item($i,4).interior.colorindex=3} elseif($comp1.cells.item($i,8).value2 -eq 'VALUTYPE=2'){$comp1.cells.item($i,6).interior.colorindex=3} elseif($comp1.cells.item($i,8).value2 -eq 'VALUTYPE=3'){$comp1.cells.item($i,5).interior.colorindex=3} elseif($comp1.cells.item($i,8).value2 -eq 'VALUTYPE=4'){$comp1.cells.item($i,7).interior.colorindex=3}}}

for($i=2; $i -le $row; $i++)
{if($comp2.cells.item($i,1).value2 -eq 'pntval'){if($comp2.cells.item($i,8).value2 -eq 'VALUTYPE=1'){$comp2.cells.item($i,4).interior.colorindex=3} elseif($comp2.cells.item($i,8).value2 -eq 'VALUTYPE=2'){$comp2.cells.item($i,6).interior.colorindex=3} elseif($comp2.cells.item($i,8).value2 -eq 'VALUTYPE=3'){$comp2.cells.item($i,5).interior.colorindex=3} elseif($comp2.cells.item($i,8).value2 -eq 'VALUTYPE=4'){$comp2.cells.item($i,7).interior.colorindex=3}}}

This code works, but the part which highlights the fields (the for loops on bottom) is cripplingly slow.  How can I speed this up?


texts:
Challenge
Given a test case print out a FizzBuzz Series.
Specifications

The first argument is a path to a file.
Each line includes a test case.
Each test case is comprised of three spaced delimited integers.

The first two integers are the dividers X and Y.
The third integer, N is how far to count.

Print out the series 1 through N, replacing numbers divisible by X with F, numbers divisible by Y with B and numbers divisible by both with FB.

Constraints

The input file is formatted correctly.
The numbers are valid positive integers.
X is in range [1, 20]
Y is in range [1, 20]
N is in range [21, 100]
Output should be one line per set with no trailing or empty spaces.

Input Sample

3 5 10
2 7 15

Output Sample

1 2 F 4 B F 7 8 F B
1 F 3 F 5 F B F 9 F 11 F 13 FB 15

Source
My Solution:
#include <stdio.h>

void print_buzzified(int fizz, int buzz, int count) {
    for (int i = 1; i <= count; i++) {
        if (i % fizz == 0 && i % buzz == 0) {
            printf("%s", "FB");
        } else if (i % fizz == 0) {
            printf("%s", "F");
        } else if (i % buzz == 0) {
            printf("%s", "B");
        } else {
            printf("%d", i);
        }

        printf(i < count ? " " : "\n");
    }
}

int main(int argc, const char * argv[]) {
    FILE *file;
    if (argc < 2 || !(file = fopen(argv[1], "r"))) {
        puts("No argument provided / File not found.");
        return 1;
    }

    file = fopen(argv[1], "r");
    int fizz;
    int buzz;
    int count;

    while (!feof(file)) {
        fscanf(file, "%d %d %d", &fizz, &buzz, &count);
        print_buzzified(fizz, buzz, count);
    }

    fclose(file);
}


texts:
I implemented this merge sort in JS and noticed that for random integer numbers it's a lot faster than the build in sort functions of all the browsers I tested (Chrome, FF, IE).
Does anyone have an idea why that is? Also, is there a way to make my code even faster?

function bubbleSort(f, a, start, end) {
    end--;
    while(end > start) {
        for(var i = start; i < end; i++) {
            var x = a[i], y = a[i+1];
            if(f(x, y) > 0) {a[i] = y; a[i+1] = x;}
        }
        end--;
    }
}

function merge(f, a, start, a2, start2, mid, end) {
    var i = start, i1 = start2, i2 = mid;
    while(i1 < mid && i2 < end) {
        if(f(a2[i1], a2[i2]) <= 0) a[i++] = a2[i1++];
        else a[i++] = a2[i2++];
    }
    if(i1 >= mid) {
        i1 = i2;
        mid = end;
    }
    while(i1 < mid) {
        a[i++] = a2[i1++];
    }
};

function _mergeSort(f, a1, a2, start, end) {
    var mid;
    if(end - start < 2) return;
    if(end - start < 8) { bubbleSort(f, a1, start, end); return; }
    mid = Math.floor((start + end)/2);
    _mergeSort(f, a2, a1, start, mid);
    _mergeSort(f, a2, a1, mid, end);
    merge(f, a1, start, a2, start, mid, end);
};

function mergeSort(f, a) {
    var a2 = a.slice();
    _mergeSort(f, a, a2, 0, a.length);
};

Here is some JSFiddle site to test the code
http://jsfiddle.net/mxbppLu0/
In Chrome I get the biggest difference (1.4 vs. 3 seconds for 10 million numbers)


texts:
I'm developing a Chrome extension so I can use bleeding-edge technologies like flexbox:

jsfiddle

HTML:

Classic search example

    <input type="text" id="example-search" />
    <button>Search</button>

CSS (cleared to highlight flexbox):

.input-wrapper {
    display: flex;
    flex-flow: row nowrap;
}

.input-wrapper > input {
    flex: 1 1 auto;
}

.input-wrapper > button {
    flex-shrink: 0;
}

I have two questions:

Is this the right way to work with flexbox?
Is there is a way to gracefully degrade this to use in websites?

Using flexbox for production:

I recently found a great article about my issue: flexbox in the real world

Raw insigsts from atricle:

use autoprefixer to support all old desktop and mobile browsers (they use old flexbox model syntax)
use progressive enhancement for IE8- (see Scenario 3 from article)


texts:
I have a model of the solar system that I'm working on at the moment. Now is the time to start cleaning my code up a little.

Here's what I have so far:

A main 'driver' method:

public class SolarModel {

public static void main(String[] args){
    SolarSystem model = new SolarSystem(700, 700);

    /* Create new instances of each object in the solar system */
    SunObject sun = new SunObject(0, 0, 50, "YELLOW", 0);
    PlanetObject mercury = new PlanetObject(60, 30, 15, "LIGHT_GRAY" ,5);
    PlanetObject venus = new PlanetObject(90, 30, 15, "GREEN", 3);
    PlanetObject earth = new PlanetObject(140, 30, 15, "BLUE", 2);
    PlanetObject mars = new PlanetObject(180, 30, 15, "RED", 1.2);

    MoonObject moon = new MoonObject(15, 30, 2, "WHITE", 1.5);

    while(true){
        /*Draw all the planets onto the SolarSystem model */
        model.drawSolarObject(sun.getDistance(), sun.getAngle(), sun.getDiameter(), sun.getColour());
        model.drawSolarObject(mercury.getDistance(), mercury.move(), mercury.getDiameter(), mercury.getColour());
        model.drawSolarObject(venus.getDistance(), venus.move(),venus.getDiameter(), venus.getColour());
        model.drawSolarObject(earth.getDistance(), earth.move(), earth.getDiameter(), earth.getColour());
        model.drawSolarObject(mars.getDistance(), mars.move(), mars.getDiameter(), mars.getColour());

        /* Draw the Earth's moon.
         * Use the Earth's PointInSpace as a point in which the moon orbits around
         */
        model.drawSolarObjectAbout(moon.getDistance(),moon.getAngle() + moon.move(), moon.getDiameter(), moon.getColour(),
                                    earth.getDistance(), earth.getAngle());

        /* Draw Mars's moon.
         * Use Mars's PointInSpace as a point in which the moon orbits around
         */
        model.drawSolarObjectAbout(moon.getDistance(), moon.getAngle() + moon.move(), moon.getDiameter(), moon.getColour(),
                                    mars.getDistance(), mars.getAngle());

        model.finishedDrawing();
        }
    }

}

A PointInSpace class:

public class PointInSpace {

private double distance;
private double angle;
private double diameter;
private String colour;
private double speed;

public double getDistance(){
    return distance;
}
public double getAngle(){
    return angle;
}
public double getDiameter(){
    return diameter;
}
public String getColour(){
    return colour;
}
public double getSpeed(){
    return speed;
}

public double move(){
    angle += speed;
    return angle;
}

public PointInSpace(double distance, double angle, double diameter, String colour, double speed){
    this.distance = distance;
    this.angle = angle;
    this.diameter = diameter;
    this.colour = colour;
    this.speed = speed;
    }

}

And classes representing Objects in the solar system

public SunObject(double distance, double angle, double diameter, String colour, double speed){
    super(distance, angle, diameter, colour, speed);

    }
}
    public PlanetObject(double distance, double angle, double diameter, String colour, double speed){
    super(distance, angle, diameter, colour, speed);

    }
}
    public MoonObject(double distance, double angle, double diameter, String colour, double speed){
    super(distance, angle, diameter, colour, speed);

    }
}

Any tips on how I can possibly refactor this code? As you can tell my 'driver' class is huge. How would I pass each object into an array and use the drawSolarObject() method from there? Any other possible way to cut down the size of this class?

What are the other weaknesses in my code?


texts: OOP Web-scraper w/ Python and BeautifulSoup

texts:
This is my first major web scraping program in python. My code works nonetheless, I'm just not sure if it's the best OOP design. My code is below:

from bs4 import BeautifulSoup
import requests
import argparse
import sys

class ComicScraper():  # Class ComicScraper for scraping comic books
    def __init__(self, comic_titles, comic_prices, all_comics):
        self.comic_titles = comic_titles
        self.comic_prices = comic_prices
        self.all_comics = all_comics
        # url of comicbook site
        self.url = 'https://leagueofcomicgeeks.com/comics/new-comics/2020/'
        self.webpage = requests.get(self.url)  # HTTP request for url
        # BeautifulSoup object of webpage
        self.soup = BeautifulSoup(self.webpage.content, 'html.parser')
        self.titles = list(
            map(BeautifulSoup.get_text, self.soup.find_all('div', class_='comic-title')))
        self.comicinfo = [x.replace(u'\xa0', u'').strip()
                          for x in list(map(BeautifulSoup.get_text, self.soup.find_all('div', class_='comic-details comic-release')))
                          ]
        self.prices = [
            prices[-5:] if prices[-5:].startswith('$') else 'No price' for prices in self.comicinfo]

    def main(self):
        if len(sys.argv) == 1:
            print("###### New Comics ######")
            for title, info in zip(self.titles, self.comicinfo):
                print(title, '--->', info)
        if self.all_comics:
            print("###### New Comics ######")
            for titles, info in zip(self, titles, self.comicinfo):
                print(title, '--->', info)
        if self.comic_titles and self.comic_prices:
            print("###### New Comics ######")
            for title, prices in zip(self.titles, self.prices):
                print(title, '--->', info)
        if self.comic_titles:
            for comic_title in self.comic_titles:
                print(comic_title)
        if self.comic_prices:
            for dol_amount in comic_prices:
                print(dol_amount)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    # Titles of comicbooks i.e "Detective Comics #1"
    parser.add_argument('-t', '--titles', help='Print comic titles ONLY', dest='titles')
    # Scrape prices of comic books in order
    parser.add_argument('-m', '--prices', help='Get comic prices ONLY', dest='prices')

    parser.add_argument('-a', '--all', help='Get titles, prices, publisher, and descriptions',
                        dest='all_comics', action='store_true')
    args = parser.parse_args()
    scraper = ComicScraper(args.titles, args.prices, args.all_comics)
    scraper.main()

I have some doubts about how much instance variables I've used? Would refactoring this code as a bunch of functions be the best way?


texts:
I've decided to write a C++ FizzBuzz with the focus on some new C++11 features, ridiculous optimizations and unit-testability.

Are there improvement possibilities in those regards?

template <typename T>
static void fizzbuzz(std::ostream& out, const T& number, const std::vector<std::pair<std::string, T>>& values)
{
    bool found = false;

    std::for_each(values.begin(), values.end(),
        [&](decltype(*values.begin()) i)
        {
            if (0 == number % i.second)
            {
                out << i.first.c_str();
                found = true;
            }
        }
    );

    if (!found)
    {
        out << number;
    }
}

template <typename T>
static void filter_fizzbuzz(const T& end, std::vector<std::pair<std::string, T>>& values)
{
    // Needs to be sorted as the filtering only looks for divisible numbers up to the current one
    std::sort(values.begin(), values.end());

    for (auto i = values.begin(); i != values.end();)
    {
        // i > end will never become 0
        if (i->second > end)
        {
            i = values.erase(i);
            continue;
        }

        // Is the current number already handled by a divisor?
        bool alreadyHandled = false;
        for (auto j = values.begin(); j != i; j++)
        {
            if (0 == i->second % j->second)
            {
                alreadyHandled = true;
            }
        }

        if (!alreadyHandled)
        {
            i++;
            continue;
        }

        i = values.erase(i);
    }
}

template <typename T>
void fizzbuzz(std::ostream& out, const T& start, const T& end, std::vector<std::pair<std::string, T>>& values)
{
    if (start > end)
        throw std::out_of_range("start > end");
    if (!values.size())
        return;

    filter_fizzbuzz(end, values);
    for (T i = start; i < end; i++)
    {
        fizzbuzz(out, i, values);
        out << std::endl;
    }
}


texts:
This piece of code is supposed to walk through a TLV string and print out its contents. For this particular example, tag field length is 2, size field length is 3.

As a mostly C programmer, this is what I came up with. I know I can parametrize the tag and length field sizes, but I don't care about that right now. Just interested to know the more pythonic way of parsing the string.

tlv = "01011Lorem ipsum02014dolor sit amet03027consectetur adipiscing elit"

temp = tlv[:]

while len(temp):
  print('tag: {}'.format(temp[0:2]))
  print('length: {}'.format(temp[2:2+3]))
  tam = int(temp[2:2+3])
  print('value: \'{}\'\n'.format(temp[5:5+tam]))
  temp = temp[5+tam:]


texts:
I answered a question in stackoverflow but I gave a solution that looks a little dirty to me, I'd like your opinion because I think there is a much smarter way to do it.

A guest user should be able to choose between two different view modalities.

My approach was to implement an action and store the choice in the session.
I paste some relevant code here as well:

  # application_controller.rb
  def set_view_type # TODO: here is the part I don't like
    session[:view_type] = params[:view_type]
    redirect_to :back
  end

  # x_controller.rb
  def index
    case session[:view_type].to_sym
    when :box render 'index_box'
    else      render 'index_list'
    end
  end

Then I use two link_to (instead of radiobutton as in stackoverflow) to choose the view, and those should be visible anytime in the layout, this is why I use application_controller for that.

PS: I don't know if it's correct to ask for a question that it's still open in SO, feel free to answer straight there by me, I just think here I'm posting my solution that I would like to be revised.


texts: Filtering a list by comparing enums against a user choice

texts:
I have a list of objects where one of the properties on the object class is an enum.

The program below simply loops through each item in the list, checks an int value, then checks the enum value for that item, then adds the item to another list when the condition is met.

I am using if-else statements, I attempted to use a switch statement but it doesn't seem possible to place 2 constants on a single case.

I'd like to know if there's a better / more elegant way to do this or is what I've done sufficient in this scenario?

Program Code

// User inputs number from 1 - 5
int SelectedOppType = Int32.Parse(Console.ReadLine());

foreach (Opportunities Opp in OpportunitiesList)
{
    if (SelectedOppType == 1 && Opp.OpportunityStatusID == OpportunityStatus.Active) // Opp.OpportunityStatusID == OpportunityStatus.Draft
    {
        FilterdOppsList.Add(Opp);
    }
    else if (SelectedOppType == 2 && Opp.OpportunityStatusID == OpportunityStatus.Draft)
    {
        FilterdOppsList.Add(Opp);
    }
    else if (SelectedOppType == 3 && Opp.OpportunityStatusID == OpportunityStatus.Closed)
    {
        FilterdOppsList.Add(Opp);
    }
    else if (SelectedOppType == 4 && (Opp.OpportunityStatusID == OpportunityStatus.Active || Opp.OpportunityStatusID == OpportunityStatus.Draft))
    {
        FilterdOppsList.Add(Opp);
    }
    else if (SelectedOppType == 5)
    {
        FilterdOppsList.Add(Opp);
    }

}

foreach (var OppItem in FilterdOppsList)
{
    Console.WriteLine(OppItem.OppText);
}

Console.ReadLine();


texts: Match two dictionary keys efficiently in Python

texts:
I have two dictionaries that I need the keys to match and if they match i will get the value of the first dictionary and then get the value of 2nd dictionary and build a new dictionary out of those.

dic1 = {u'ShutterHours': 732, u'ShieldHours': 732, u'MaskHours': 28, u'TargetHours': 790, u'GndRingHours': 25}
dic2 = {u'ShutterHours': u'Shutter Hours', u'ShieldHours': u'Shield Hours', u'MaskHours': u'Mask Hours', u'TargetHours': u'Target Hours', u'GndRingHours': u'Ground Ring Hours'}

This is my code so far:

final = {}
for k,k2 in zip(dic1,dic2):
    if k == k2:
        final[dic2[k]] = dic1[k]

Expected output:

{u'Ground Ring Hours': 25, u'Shutter Hours': 732, u'Shield Hours': 732, u'Mask Hours': 28, u'Target Hours': 790}

This works fine but I'm a bit skeptical if this is the best and Pythonic way to do this.


texts:
I have the following function that takes JSON and turns it into table rows:

function addDataFromJson(json) {
    var data = json.data;
    var rows = '';
    $('.uiGridContent tbody').html('');

    for (var i = 0; i < data.length; i++) // for each row
    {
        var columns = '';

        for (var b = 0; b < Object.keys(data[i]).length; b++) // for each column
        {
            var content = data[i][Object.keys(data[i])[b]];

            columns += '' + content + '	';
        }

        var row = columns;

        row = '
\
                    <input type="checkbox">	\
                    \

\
                            Actions\

\
                    	\
                    ' + columns + '\

';

        rows =+ row;

    }

    $(rows).appendTo('.uiGridContent tbody');
}

The JSON looks like this (for those curious):

"data": [{
        "id": 1,
        "name": "Sheffield University",
        "departments": ["Software", "Recruitment", "Consulting"],
        "locations": ["Sheffield", "Rotherham", "London", "New York"]
    }, {
        "id": 2,
        "name": "Sheffield College",
        "departments": "",
        "locations": ["Hillsborough", "City Centre", "Crystal Peaks"]
    }, {
        "id": 3,
        "name": "Sheffield High School",
        "departments": ["Medical", "Family", "Criminal"],
        "locations": ["Sheffield", "Rotherham"]
    }...

However if I pass back 1000+ records then the JavaScript struggles and it takes a few seconds to do it and causes the browser to lock up.

Any ideas on how to improve this code?

It seems to be the line where I append the rows to the page:

$(rows).appendTo('.uiGridContent tbody');

As if I comment that line out, then it's really fast...


texts: Filtering user input to not contain a specific character

texts:
I need to filter an input from a user to never have the have the Pilcrow Sign (¶) character. The following methods filters the input from the user

public String filterInput(String userInput) {
    StringBuilder sBuilder = new StringBuilder();

    for (char character : userInput.toCharArray()) {
        if (checkCharacter(character)) {
            sBuilder.append(character);
        }
    }
    return sBuilder.toString();
}

public boolean checkCharacter(char charToCheck) {
    return charToCheck != 182;
}

filterInput gets passed a String containing the user input which is taken from Scanner(System.in) No previous filtering has been done on the user input.

My concern is, is the code well written or is there still a way for the user to write the Pilcrow sign in such a way that when the String is broken into characters, it could bypass the checkCharacter method and return true, effectively managing to inject the forbidden character in my app?


texts:
I just started working in a project that wasn't developed by me, I'm worried about some of the functionalities and I would like some suggestions.

After the login validations, the login procedure is made like this:

var _ticket = new FormsAuthenticationTicket(1, user.ID, DateTime.Now, DateTime.Now.AddDays(30), true, user.ID);

string encTicket = FormsAuthentication.Encrypt(_ticket);
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

As we can see, there is a user object which stores the details of the logged in user (Id, name, e-mail...)

The first problem that I see is that on the FormsAuthenticationTicket the user ID is passed as the name. And every time I want to get any info from the user I have to do this:

Item user = Framework.Business.Item.Load(HttpContext.Current.User.Identity.Name);

The project uses master page, and on every page I have to do this to get the ID/name/picture of the logged user

By the way, at least the load method gets the user date from a collection, BUT, this collection stores not only the users data but all the data that needs to be cached (since ID's are GUIDs) ids won't be duplicated and I think because of this reason, there is only one Collection for everything.

I would like to know if this is right, or what should I do to make it better


texts:
I am not new to html however would like to know about best practices. I need to develop a layout like this:

This is what I have proposed:

                <image></image>

                Text goes here
                <image></image>

            <image></image>

            <image></image>

            Text goes here
            <image></image>

http://jsfiddle.net/gdWM5/

Can this be improved in any way?