texts:
I wrote this piece of code for a GUI i am making, which is a playlist interface. I was wondering if I could write all of this code out differently, but to the point where it functions exactly the same, as I am intrigued in learning different ways to write java to boost my flexibility and knowledge in the language.

package java;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import static coursework.VideoData.setRating;

public class UpdateVideos extends JFrame implements ActionListener {

    JTextField trackNo = new JTextField(2);
    JTextField newrate = new JTextField(2);
    TextArea content = new TextArea(6, 50);
    JButton apply = new JButton("Apply");

    public UpdateVideos() {
        setLayout(new BorderLayout());
        setBounds(100, 100, 400, 200);
        setTitle("Check Videos");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel top = new JPanel();
        top.add(new JLabel("Enter Video Number:"));
        top.add(trackNo);
        top.add(new JLabel("Enter Rating:"));
        top.add(newrate);
        top.add(apply);
        apply.addActionListener(this);
        add("North", top);

        JPanel middle = new JPanel();

        middle.add(content);
        add("Center", middle);
        setResizable(false);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {

        String key = trackNo.getText();
        String name = VideoData.getName(key);
        Integer ratingnum;
        String newratenum;
        newratenum = newrate.getText();
        ratingnum = Integer.parseInt(newratenum);

        if (e.getSource() == apply) {
            if (name == null) {
                content.setText("No such video number");
            } else {
                setRating(key,ratingnum);
                content.setText(name + " - " + VideoData.getDirector(key));
                content.append("\nRating: " + stars(VideoData.getRating(key)));
                content.append("\nPlay count: " + VideoData.getPlayCount(key));
            }

        }
    }

    private String stars(int rating) {
        String stars = "";
        for (int i = 0; i < rating; ++i) {
        stars += "*";
        }
        return stars;
    }
}


texts:
I have an abstract PersonDao class, extended by several other DAO classes, for example EmployeeDao, StaffDao.

The non-abstract DAOs correspond to different tables. The tables have some common fields, and also some unique fields. Operations on the common fields are implemented in the abstract parent PersonDao class, operations on the unique fields are implemented in the specialized DAOs.

The parent DAO looks like this:

public abstract class PersonDao {

    private SimpleJdbcTemplate simpleJdbcTemplate;

    public PersonDao() {
        final String tableName = getTableName();
        fieldNamesCSV = getFieldNames();

        String select = String.format("SELECT %s FROM %s ", fieldNamesCSV, getTableName());
    }

    abstract String getTableName();

    abstract String getHistoricalTableName();

    public void setDataSource(DataSource dataSource) {
        this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
    }

    // more methods, common to all persons
}

An example specialized DAO looks like this:

public class EmployeeDao extends PersonDao {

    private static final String TABLE_NAME = "EMPLOYEE";
    private static final String HISTORICAL_TABLE_NAME = "EMPLOYEE_HIST";

    @Qualifier("employeeDS")
    @Override
    public void setDataSource(DataSource dataSource) {
        super.setDataSource(dataSource);
    }

    @Override
    String getTableName() {
        return TABLE_NAME;
    }

    @Override
    String getHistoricalTableName() {
        return HISTO_TABLE_NAME;
    }

    // more methods, unique to employees
}

My question is about the code duplication in the specialized DAOs. They all have the boilerplate code of setting the data source (configured by Spring), and the overridden methods for the table names, so that the common methods in the parent class work with any table. Code quality analysis tools like Sonar detect and flag an error for these blocks.

Do you suspect something wrong with my design that necessitates the boilerplate code? If so, please give some tips to improve it.
If the design looks legit, do you see a way to reduce the duplication? Moving the table name constants to the methods as hard-coded strings would fool the code analysis tool, but that's hardly the solution.
Any other tips come to mind?

UPDATE

As @pinoniq pointed out, the setDataSource was smelly. I vaguely remembered that Spring forced me to do it that way, and differentiate the specialized classes with the @Qualifier annotation. It seems that's not the case, I could move data source to the constructor of the specialized classes, and everything seems to work well.


texts:
I implemented a CustomHashMap in Java, and would like to know if my approach is good or not.

Below I am sharing the complete code of my CustomHashMap:

CustomHashMap.java

import java.util.Iterator;
import java.util.Objects;
import com.custom.utils.*;

public class CustomHashMap<K, T> implements Iterable<Entity> {

    private static final int capacity_init = 10;
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    private int indexCount = 0;

    Entity[] bucket = null;

    Entity[] bucketItr = null;

    public CustomHashMap() {
        init(capacity_init);
    }

    public CustomHashMap(int capacity) {
        init(capacity);
    }

    private void init(int intcapacity) {

        bucket = new Entity[intcapacity];
    }

    private int hash(Object key) {

        return key.hashCode() >> 1;
    }

    public void add(K key, T value) {

        int hashcode = hash(key);

        if(indexCount == bucket.length){
            Entity[] obj = bucket;
            int k = (int) (obj.length*2);
            bucket = new Entity[k];
            System.arraycopy(obj, 0, bucket, 0, indexCount-1);
        }

        if (bucket[hashcode] == null) {
            indexCount++;
            Entity head = new Entity(key, value, null);
            bucket[hashcode] = head;
        } else {
            Entity temp = bucket[hashcode];
            while (temp.next != null) {
                temp = temp.next;
            }
            Entity neEntity = new Entity(key, value, null);
            neEntity.next = temp;
            bucket[hashcode] = neEntity;

        }

        bucketItr = new Entity[bucket.length];
        System.arraycopy(bucket, 0, bucketItr, 0, bucket.length);

    }

    public T get(K key) {
        int hashcode = hash(key);
        if (bucket[hashcode] == null) {
            return null;
        } else {
            Entity temp = bucket[hashcode];
            while (temp != null) {

                if (temp.key.equals(key)) {
                    return (T) temp.value;
                }
                temp = temp.next;
            }
            return null;
        }

    }

    public void delete(K key) {
        int hashcode = hash(key);
        Entity deleteNode = bucket[hashcode];
        deleteNode = null;
        bucket[hashcode] = deleteNode;
    }

    @Override
    public Iterator<Entity> iterator() {
        // TODO Auto-generated method stub
        bucketItr = new Entity[indexCount];
        int entryCount = 0;
        for (Entity e : bucket) {

            if (Objects.nonNull(e)) {
                bucketItr[entryCount] = e;
                entryCount++;
            }

        }

        return new MapItr();
    }

    class MapItr implements Iterator<Entity> {

        int count = 0;
        Entity node = bucketItr[0];

        @Override
        public boolean hasNext() {
            // TODO Auto-generated method stub

            return count < bucketItr.length;
        }

        @Override
        public Entity next() {

            Entity result = null;

            if (hasNext()) {
                result = node;
                if ( Objects.nonNull(node) && node.next != null) {
                    node = node.next;
                } else {
                    count++;
                    if (count < bucketItr.length)
                        node = bucketItr[count];
                }

                return result;
            } else {
                return null;
            }
        }

    }

}

Entity.java

public class Entity<K, T> {
    public K key;
    public T value;
    public Entity next;

    public Entity(K key, T value, Entity next) {

        this.key = key;
        this.value = value;
        this.next = next;

    }

}

Please suggest improvements and things which you feel I need to add to it.


texts: Connect Four: Bitboard checking algorithm

texts:
I'm rather new to Clojure and so I decided to program a Connect Four for fun and learning.

The code below is a Clojure implementation of this bitboard algorithm.

The whole code can be found here: https://gist.github.com/3639220

What I'm unsure about are the functions (insert) and (bit-check-board):

(defn insert
  "Inserts symbol for given player (either 1 or 2) at specified x and
   calls bit-insert for corresponding bitboard."
  [boards x player-num]
  (let [y (get-y (boards 0) x)]
    (if (= player-num 1) ; TODO: improve
      (vector
       (assoc-in (boards 0) [y x] (player player-num))
       (bit-insert (boards 1) (- 5 y) x)
       (boards 2))
      (vector
       (assoc-in (boards 0) [y x] (player player-num))
       (boards 1)
       (bit-insert (boards 2) (- 5 y) x)))))

(defn bit-check-board ; TODO: improve
  "Checks whether given bitboard is a win."
  [bitboard]
  (let [diag1 (bit-and bitboard (bit-shift-right bitboard 6))
        hori  (bit-and bitboard (bit-shift-right bitboard 7))
        diag2 (bit-and bitboard (bit-shift-right bitboard 8))
        vert  (bit-and bitboard (bit-shift-right bitboard 1))]
    (bit-or (bit-and diag1 (bit-shift-right diag1 (* 2 6)))
            (bit-and hori  (bit-shift-right hori  (* 2 7)))
            (bit-and diag2 (bit-shift-right diag2 (* 2 8)))
            (bit-and vert  (bit-shift-right vert  (* 2 1))))))

insert: Is there a better way to somehow make function calls depend on some test?
bit-check-board: A lot of similar lines where just one number (and one variable name) is different.


texts:
I have a class that stores the data related to all employees in a particular department.
In this class, I am having a list of employees and other fields.
Also, I am having a property which returns a bool, indicating whether an employee exists or not.  I am a bit confused regarding the naming of this property.

class Employee_Details
{
  #region Private Fields
  private List<Employee> employees;
  #endregion

  #region Fields
  // Gets a value indicating whether an employee exists
  public bool DoesEmployeeExists  // what should be the name of this property?
  {
    get
    {
      return this.employees.Any();
    }
  }
  #endregion
}

Is the property name DoesEmployeeExists correct, or should I use any other name?


texts: Class to handle complex form using Angular ReactiveForms

texts:
I'm working with the ReactiveForms in Angular5 and trying to find a good way to do this.

So, in my use case, I have a FormGroup inside my example.component.ts and when I need to add some FormControl I have to do this:

ngOnInit() {
  this.form = new FormGroup({
    'myCompany': new FormControl(this.company, Validators.required),
    'myId': new FormControl(),
    'myDate': new FormControl(new Date().toISOString(), Validators.required),
    'mySotck': new FormControl('', Validators.required),
    'myItemsStock': new FormControl([], Validators.required)
  });

//[...] more codes

Well, so far everything is working well, not a big deal. But my example.component.ts has a little more fields and some of these fields have a special behavior, something like that:

ngOnInit() {

  // [...] more codes

  this.form.get('operation').valueChanges.subscribe(value => {

    if (!isNullOrUndefined(value)) {
       const operacao: MyModel = value;

      if (operacao.something) {
        this.limitDate = new Date();
      }

      if (!operacao.something) {

        this.service.search(this.company).subscribe(response => {
          const dateOffset = (24 * 60 * 60 * 1000) * response.days

          this.limitDate = new Date(new Date().getTime() - dateOffset);
        });
      }
    }

  });

  // [...] more codes

'cause this my component is getting a lot of lines code, more 400 lines. And I feel that it will be very hard to read, to understand and to maintenance.

To solve this problem I thought about creating a new class, extend the FormGroup and then set my FormControls, Validations, and behavior inside of this new class:

export class CustomFormGroup extends FormGroup {

  constructor() {
    super({
      'myCompany': new FormControl(this.company, Validators.required),
      'myId': new FormControl(),
      'myDate': new FormControl(new Date().toISOString(), Validators.required),
      'mySotck': new FormControl('', Validators.required),
      'myItemsStock': new FormControl([], Validators.required)
    });
  }

  registerListeners() {
    this.get('operation').valueChanges.subscribe(value => {

      if (!isNullOrUndefined(value)) {
        const operacao: MyModel = value;

        if (operacao.something) {
          this.limitDate = new Date();
        }

        if (!operacao.something) {

          this.service.search(this.company).subscribe(response => {
            const dateOffset = (24 * 60 * 60 * 1000) * response.days

            this.limitDate = new Date(new Date().getTime() - dateOffset);
          });
        }
      }
    }
  }

My intention with that is to reduce the complexity of my component and make it more cleary to read and understand.
And split the responsibility of managing the form to another class, so when I need to use the form, I can use it this way:

// example.component.ts
this.form = new CustomFormGroup();

With this approach, I don't need to have any form's behavior in my component, once it's contained by my custom FormGroup.
My question is whether this is the best way to separate concerns, and what would be better for doing that.

I'll be very glad if you give me some idea, share your experience or feedback about this approach. Feel entirely free to comment on this question.

I'm sorry if what I wrote was hard to understand, English is not my primary language and I am trying to improve that every day.


texts: Create thumbnail in the original ratio without empty space

texts:
I need to make thumbnails without empty space and in the original ratio. Please help me check this algorithm to improve it.

public function createThumbnail($imagePath, $thumbnailPath, $targetWidth, $targetHeight)
{
    list( $originalWidth, $originalHeight, $originalType ) = getimagesize($imagePath);
    $targetRatio = $targetWidth / $targetHeight;
    $originalRatio = $originalWidth / $originalHeight;

    if ( $originalRatio >= $targetRatio ) {
        if ( $originalRatio >= 1 ) {
            $sourceWidth = $originalHeight * $targetRatio;
            $sourceHeight = $originalHeight;
            $sourceX = ( $originalWidth - $sourceWidth ) / 2;
            $sourceY = 0;
        } else {
            $sourceWidth = $originalWidth / $originalRatio * $targetRatio;
            $sourceHeight = $originalHeight;
            $sourceX = ( $originalWidth - $sourceWidth ) / 2;
            $sourceY = 0;
        }
    } else {
        if ( $originalRatio >= 1 ) {
            $sourceWidth = $originalWidth * $originalRatio / $targetRatio;
            $sourceHeight = $originalHeight;
            $sourceX = ( $originalWidth - $sourceWidth ) / 2;
            $sourceY = 0;
        } else {
            $sourceWidth = $originalWidth;
            $sourceHeight = $originalHeight * $originalRatio / $targetRatio;
            $sourceX = 0;
            $sourceY = ( $originalHeight - $sourceHeight ) / 2;
        }
    }

    $originalImage = $this->imageCreateFromType( $originalType, $imagePath );
    $thumbnailImage = imagecreatetruecolor( $targetWidth, $targetHeight );

    imagecopyresampled( $thumbnailImage, $originalImage, 0, 0, $sourceX, $sourceY, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight );

    imagepng( $thumbnailImage, $thumbnailPath );
}


texts:
fairly new to playing around with proxy servers. Wrote a really simple one with Express to help keep some API keys secret so that my front-end app can query the GitHub API. Definitely feels a bit clunky, but is working so far. I really haven't done performance testing before but the way this is implemented it seems like > 1 second round trip. I was wondering if anyone wouldn't mind taking a look and giving me some hints at some basic ways I could improve the performance. One thing I saw come up a few times was piping he request from the endpoint directly back to the requester, but so far I haven't been able to get that to work. Granted I haven't made a huge effort at that.

The proxy server itself is set up as follows:

// Express: ^4.17.1

const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
require('dotenv').config();

// Initialize app
const app = express();
const port = process.env.PORT || 3000;

// Configuration
app.use(bodyParser.json({ type: 'application/json' }))

// Constants
const id = process.env.GITHUB_CLIENT_ID;
const secret = process.env.GITHUB_CLIENT_SECRET;
const params = `?client_id=${id}&client_secret=${secret}`

// Route(s)
app.post('/profile', (req, res) => {
  const { username } = req.body;
  const endpoint = `https://api.github.com/users/${username}${params}`;

  axios({
    method: 'get',
    url: endpoint,
  })
    .then(response => {
      res.status(200)
      res.send(response.data)
    })
    .catch(error => {
      console.log('Error with Axios profile res: ', error)
      res.send({ error })
    })

  return
})

app.post('/repos', (req, res) => {
  const { username } = req.body;
  const endpoint = `https://api.github.com/users/${username}/repos${params}&per_page=100`;

  axios({
    method: 'get',
    url: endpoint,
  })
    .then(response => {
      res.status(200)
      res.send(response.data)
    })
    .catch(error => {
      console.log('Error with Axios repos res: ', error)
      res.send({ error })
    })

  return
})

// App is initialized using app.listen

On the frontend we have React, making requests that are proxied tot my server, where they pick up the API keys, and then the server makes a request to the endpoint on the GitHub API. The front-end is responsible for passing a username along to the endpoint. The relevant front-end code is as follows:

function getProfile(username) {
  return fetch('api/profile', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ 'username': username })
  })
    .then(res => res.json())
    .then(profile => {
      if (profile.message) {
        throw new Error(getErrorMsg(profile.message, username))
      }

      return profile
    })
}

function getRepos(username) {
  return fetch('api/repos', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ 'username': username })
  })
    .then(res => res.json())
    .then(repos => {
      if (repos.message) {
        throw new Error(getErrorMsg(repos.message, username))
      }

      return repos
    })
}

I can post the React code as well if necessary but it seems like React is not where a bottleneck would be originating - but I'm pretty green at this so that might be mistaken thinking on my part.

There are two requests being fired from the React application simultaneously, the end goal being a general comparison of two GitHub users. I've done this without the proxy and things definitely felt snappier, and I haven't really refactored anything on the front-end aside from pointing the requests at the proxy instead of directly at the GitHub API.

Thanks in advance for any tips!


texts: Python function to find the next smaller number with same set of digits

texts:
Problem: Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits.

My solution:

def next_smaller(n):
    import itertools
    x = list(str(n)) #list of digits
    #permutates and joins digits
    x = [int(''.join(i)) for i in list(itertools.permutations(x))]
    x.sort() #sorts numerically
    #picks number previous to original in list
    r = [x[i-1] for i in range(0,len(x)) if x[i] == n][0]
    if r > n: return -1 #returns -1 if no solution
    else: return r #returns solution

My code works, however it is terribly inefficient with very large numbers. Any way to make this code more efficient and cut down the execution time?


texts: Using session wrapper for accessing session data

texts:
When users log in to our website, we store some information in a session to retrieve it across the site. We created a few wrappers to help with data retrieval/storage to lessen duplication of code.

I'm trying to redesign it as I don't like how the UserModel is written. I believe it's dangerous with the static properties, but so far it's been working.

However...

While we haven't noticed any issues, recently someone use something very similar to our code (slightly modified) for another project and had about 20+ people log in at the same time. Some users saw other user's information instead of their own. This brought a huge concern on the original code (below) and would like to get any feedback on how to make it "better" or avoid the same issue they ran into (if it even will happen).

I searched/read around Google/Stack Overflow about the possible issue being at our static method wrappers.

UserModel.cs

public class User {
    private const Boolean UseSessionAsDataStore = true;

    protected const String kUserId = "UserId";
    protected const String kUserName = "UserName";
    protected const String kUserEmail = "UserEmail";

    public static Int32 UserId {
        get { return GetInt32Value(kUserId); }
        set { SaveValue(kUserId, value.ToString()); }
    }

    public static String UserName {
        get { return GetStringValue(kUserName); }
        set { SaveValue(kUserName, value); }
    }

    public static String UserEmail {
        get { return GetStringValue(kUserEmail); }
        set { SaveValue(kUserEmail, value); }
    }

    protected static void SaveValue(String key, String value) {
        UseSessionAsDataStore ?
        SessionHelper.SaveSessionValue(key, value) :
        CookieHelper.SaveCookieValue(key, value);
    }

    protected static void GetStringValue(String key) {
        UseSessionAsDataStore ? SessionHelper.GetSessionStringValue(key) : CookieHelper.GetCookieStringValue(key);
    }

    protected static void GetInt32Value(String key) {
        UseSessionAsDataStore ? SessionHelper.GetSessionInt32Value(key) : CookieHelper.GetCookieInt32Value(key);
    }
}

UserLoginModel.cs

public class UserLoginModel {
    AssignUser (Int32 userId, String userName, String userEmail) {
        UserModel.UserId = userId;
        UserModel.UserName = userName;
        UserModel.UserEmail = userEmail;
    }
}

SessionHelper.cs

(won't provide CookieModel.cs as it's not the issue in question)

public class SessionHelper {
    public static void SaveSessionValue(String key, String value) {
        HttpContext.Current.Session.Add(key, value);
    }

    public static String GetSessionStringValue(String key) {
        if (HttpContext.Current.Session == null || HttpContext.Current.Session[key] == null) { return null; }
        return HttpContext.Current.Session[key] != null ? HttpContext.Current.Session[key].ToString() : String.Empty;
    }

    public static Int32 GetSessionInt32Value(String key) {
        if (HttpContext.Current.Session == null || HttpContext.Current.Session[key] == null) { return 0; }
        Int32 value;
        Int32.TryParse(HttpContext.Current.Session[key].ToString(), out value);
        return value;
    }
}

LoginPage

/* try to log in user and return user data */
...
if (loginSuccessful) {
    UserLoginModel.AssignUser(userId, userName, userEmail);
}
...

MainPage

<html>
    <body>
        Hello <%=UserModel.UserName %>!
    </body>
</html>
...

I have a feeling that this code has the potential to share session data between 2 users, although we have yet to realize it, even with about 5 simultaneous logins.


texts: Generate a set of random values based on seed

texts:
I am a novice when it comes to Python. I am working stuff related to Flowshop scheduling and so to generate benchmarks I used one by Taillard (Link to his homepage). The details are in the technical report.

Since I ported the code from C which I am not really good at please review my Python script:

# Format - random seed, number of jobs, number of machines
# Use a separate file and precede comments with a # symbol

from numpy import int32
import math

problem = list()

# Generate a random number uniformly between low and high
def unif(seed, low, high):
    """This function generates a random number between low\
            and high based on seed
    Seed is implemented as static for set of random values based on a series\
            of seed values"""

    if getattr(unif, "seed_value",0) == 0 or unif.seed_value is None:
        #create attribute seed_value which is static for method unif
        unif.seed_value = seed #inititalization if attribute does not exist

    # constants for random number
    a = 16807
    b = 127773
    c = 2836
    m = 2**(31) - 1

    k = math.floor(unif.seed_value / b)

    unif.seed_value = int32(a * (unif.seed_value % b) - k * c)
    # use numpy 32 bit int
    if unif.seed_value < 0: # 32 bit int overflow
        unif.seed_value = unif.seed_value + m

    value_0_1 = unif.seed_value/float(m)

    return int(low + math.floor(value_0_1 * (high - low + 1))) # random\
            # number generated

# generates a problem for given number of machines and jobs in problem tuple
def generate_flow_shop(p, output):
    """Generates a flow shop problem set for a set in problem tuple and\
            writes to file in output"""
    time_seed = int(problem[p][0])
    d = list() # list containing the problem

    for i in range( int(problem[p][2]) ):
        line = list()

        line = [ unif(time_seed, 1, 99) for j in range(int(problem[p][1])) ]

        # for j in range(0, int(problem[p][1])):
        #     line.append(unif(time_seed, 1, 99))
        # 99 - max duration of op.
        d.append(line)
    unif.seed_value = None

    for line in d:
        datum = ' '.join(map(str,line))
        output.write("%s\n" % (datum))

def main():
    name = input("Enter filename to write the generated values:\n> ")
    seedfile = input("Enter filename of the seed values:\n> ")

    with open(seedfile) as in_file:
        for i in in_file:
            if line[0] == '#':
                continue
            else:
                line = i.strip().split()
                problem.append(tuple( map(int,line) ) )

    with open("%s" % (name), "w") as out_file:
        for i in range(0, len(problem)):
            out_file.write("%s %04d %s %s\n" %\
                           ("p", i, problem[i][1], problem[i][2]))
            generate_flow_shop(i, out_file)

if __name__ == '__main__':
    main()

The link to the original C program is here.

This is the link to the output which is the expected output ie. the code is actually correct.

The main purpose of this module is to generate a set of values that can be used to test our implemented solutions ie. it is a generated problem set but not completely random but reproducible if the seeds entered are the same.

Note: The seedfile is a file that contains the values that are defined in the struct problem in the C program.

What I mainly need feedback on are:

Can the script be improved further with respect to use of Python idioms?
Since the generated file should again be parsed as input for testing, is writing to a file and then opening it again to test the scripts the best way? Is the written file format the best one for parsing again as input?


texts:
I've got a 64 bit bitboard, but instead of interpreting as an 8 by 8 binary matrix, as is usually the case, I've taken it to the third dimension, so to speak.

Now mirroring and even rotating by 180 degrees on any individual axis is, if I'm not mistaken, fairly simple, but rotating by 90 degrees, which is what I actually need, has given me a nasty headache.

I have of course come up with a solution, but I would like to ensure that there isn't a better way, because frankly it's a bit much.

Anyway, here an example function, rotating, I suppose, clockwise on the Y axis:

unsigned long long rotateLeft( unsigned long long bs )
{
     return ( ( bs & 0x0000000000001111 ) << 48 ) |
            ( ( bs & 0x0000000000002222 ) << 31 ) |
            ( ( bs & 0x0000000000004444 ) << 14 ) |
            ( ( bs & 0x0000000000008888 ) >>  3 ) |
            ( ( bs & 0x0000000011110000 ) << 33 ) |
            ( ( bs & 0x0000000022220000 ) << 16 ) |
            ( ( bs & 0x0000000044440000 ) >>  1 ) |
            ( ( bs & 0x0000000088880000 ) >> 18 ) |
            ( ( bs & 0x0000111100000000 ) << 18 ) |
            ( ( bs & 0x0000222200000000 ) <<  1 ) |
            ( ( bs & 0x0000444400000000 ) >> 16 ) |
            ( ( bs & 0x0000888800000000 ) >> 33 ) |
            ( ( bs & 0x1111000000000000 ) <<  3 ) |
            ( ( bs & 0x2222000000000000 ) >> 14 ) |
            ( ( bs & 0x4444000000000000 ) >> 31 ) |
            ( ( bs & 0x8888000000000000 ) >> 48 );
}

I suppose 16 shifts, 16 ANDs and 15 ORs is not actually that bad, but I cannot believe that this is the best option.

So is there another/better way? I need both direction for the X and Y axis, but I suppose the solution will be somewhat similar for all of them, assuming of course that there is a better way.

Come to think of it you could do something like:

unsigned long long rotateLeft( unsigned long long bs )
{
    //mirror in diagonal plane (x=z?)
    bs =   ( ( bs & 0x0000000000008888 ) << 45 ) | ( ( bs & 0x1111000000000000 ) >> 45 ) |
           ( ( bs & 0x0000000088884444 ) << 30 ) | ( ( bs & 0x2222111100000000 ) >> 30 ) |
           ( ( bs & 0x0000888844442222 ) << 15 ) | ( ( bs & 0x4444222211110000 ) >> 15 ) |
             ( bs & 0x8888444422221111 );
    //mirror in vertical plane (xy?)
    //I do apologize  for not knowing the correct terminology.
    bs =   ( ( bs & 0x00000000ffffffff ) << 32 ) | ( ( bs & 0xffffffff00000000 ) >> 32 );
    return ( ( bs & 0x0000ffff0000ffff ) << 16 ) | ( ( bs & 0xffff0000ffff0000 ) >> 16 ) |
}

I would even think that could be improved a bit without too much effort. Still, I'd be interested in any suggestions.

edit:
I've been informed that clarification is needed, so I'll do my best.
Firstly, structurally I'm talking about a 4 by 4 by 4 cube.
Line 1 of layer 1 consist of bits 0 through 3
Line 2 of layer 2 of bits 20 through 23
layer 3 of bits 32 through 47
and so on.
for each layer lsb is at the top left and msb is bottom right, counting line wise.

and example of rotating left could be:
layer 1-4:

1000 0000 0000 0000
0100 0000 0000 0000
0010 0000 0000 0000
0001 0000 0000 0000

to

0000 0000 0000 1000
0000 0000 1000 0000
0000 1000 0000 0000
1000 0000 0000 0000

or

0x0000 0000 0000 8421

to

0x1000 0100 0010 0001

I hope this clarifies matters a bit.

edit 2:
as request, here the implementation:

uint64_t board_with_exactly_one_bit_set(int x, int y, int z)
{
    return 1 << ( z*16 +y*4 +x );
}


texts: Simple class exercise using the "this" pointer

texts:
This is my solution for an exercise from a book.  It's a simple Golf class with member variables fullname and handicap. The constructor sets the variables to the provided name and handicap using values passed as arguments. The setgolf() function solicits name and handicap from user, creates a temporary Golf object and assigns it to the invoking object.

Is this a proper solution? I'm particularly interested in the setgolf() method.

golf.h:

#include <string>

class Golf
{
    private:
        std::string fullname;
        int handicap;
    public:
        Golf();
        Golf(const std::string name, int hc);
        int setgolf();
        void sethandicap(int hc);
        void showgolf();
};

golf.cpp:

#include "golf.h"
#include <cstring>
#include <iostream>

Golf::Golf(const std::string name, int hc)
{
    fullname = name;
    handicap = hc;
}

int Golf::setgolf()
{
    std::string name;
    int hc;
    std::cout << "Enter the name: ";
    getline(cin, name);
    if (name == "")
        return 0;
    std::cout << "Enter the handicap: ";
    std::cin >> hc;
    *this = Golf(name, hc);
    return 1;
}


texts: Leap year check in Haskell, using pattern matching or bind operator

texts:
One of the first Haskell puzzles on http://exercism.io/ is to implement a leap year check. I've done this twice.

Using pattern matching:

isLeapYear :: Integer -> Bool
isLeapYear year
  | year `mod` 400 == 0 = True
  | year `mod` 100 == 0 = False
  | year `mod` 4 == 0   = True
  | otherwise           = False

Using the bind operator >>=:

isLeapYear :: Integer -> Bool
isLeapYear year = head $
                  [(400, True), (100, False), (4, True), (1, False)]
                  >>= check year
  where check y (interval, isLeap) = [isLeap | y `mod` interval == 0]

I'd like to know which implementation is “better“ / more idiomatic in Haskell. I am unsure whether I might have misused a t0o powerful concept in the second try, and the first try might just be more readable.


texts: Python function to determine whether a given BST is valid

texts:
Here's a simple function I wrote using recursion. Does this run in \$O(n)\$ time and use \$O(n)\$ space, where \$n\$ is the number of nodes in the tree?

def is_valid(root, min, max):
    if not root:
        return True
    if min is None or max is None:
        return is_valid(root, float("-inf"), float("+inf"))
    print(root.value, min, max)
    if root.value <= min:
        return False
    if root.value >= max:
        return False
    return is_valid(root.left, min, root.value) and is_valid(root.right, root.value, max)


texts: Render elements from an array of objects

texts:
The goal is to list out some data, but the methods vary on options, and whether the user is on a touch device.

This is my current function declaration. Very non-DRY. Values of isTouch and headlinesOnly don't change during loop, so I don't want to make if tests inside the loop.

Edit: This is primarily meant for a memory-sensitive environment which, when not handled properly, reboots to safe mode, not a regular browser. (But I'm making it for both.)

var makeElement;

if (isTouch) {
    if (headlinesOnly) {
        makeElement = function(item, top, left) {
            var a = document.createElement("a");
            a.setAttribute('ontouchstart', 'itemTouchStart()');
            a.setAttribute('ontouchmove', 'itemTouchMove()');
            a.setAttribute('ontouchend', 'itemTouchEnd(\'' + item.link + '\')');
            a.style.top = top + 'px';
            a.style.left = left + 'px';
            a.innerHTML = '
' + item.title + '
';
            return a;
        };
    }
    else {
        makeElement = function(item, top, left) {
            var a = document.createElement("a");
            a.setAttribute('ontouchstart', 'itemTouchStart()');
            a.setAttribute('ontouchmove', 'itemTouchMove()');
            a.setAttribute('ontouchend', 'itemTouchEnd(\'' + item.link + '\')');
            a.style.top = top + 'px';
            a.style.left = left + 'px';
            a.innerHTML = '
' + item.title + '
'
                        + '
' + item.content + '
';
            return a;
        };
    }

    var dragging;

    window['itemTouchStart'] = function() {
        dragging = false;
    };

    window['itemTouchMove'] = function() {
        dragging = true;
    };

    window['itemTouchEnd'] = function(url) {
        if (dragging) return;

        if (cycript) {
            tryOpenUrl(url);
        }
        else {
            window.open(url, "_blank");
        }
    };
}
else {
    if (headlinesOnly) {
        makeElement = function(item, top, left) {
            var a = document.createElement("a");
            a.setAttribute('onmouseup', 'itemMouseUp(\'' + item.link + '\')');
            a.style.top = top + 'px';
            a.style.left = left + 'px';
            a.innerHTML = '
' + item.title + '
';
            return a;
        };
    }
    else {
        makeElement = function(item, top, left) {
            var a = document.createElement("a");
            a.setAttribute('onmouseup', 'itemMouseUp(\'' + item.link + '\')');
            a.style.top = top + 'px';
            a.style.left = left + 'px';
            a.innerHTML = '
' + item.title + '
'
                        + '
' + item.content + '
';
            return a;
        };
    }

    window['itemMouseUp'] = function(url) {
        window.open(url, "_blank");
    };
}

var item = myCollection.shift();

container.appendChild(makeElement(item));

var columnWidth = container.childNodes[0].offsetWidth;
var containerWidth = container.offsetWidth;
var numberOfColumns = containerWidth / columnWidth;
var columns = [];

for (var i = 0; i < numberOfColumns; i++) {
    this.columns.push(0);
}

while (item = myCollection.shift()) {
    var sh = getShortestColumn();
    var itemElement = makeElement(item, sh.height, sh.index * columnWidth);
    container.appendChild(itemElement);
    columns[sh.index] += itemElement.offsetHeight;
}


texts: Dynamic Bootstrap 4 modal using JavaScript OOP

texts:
I have created dynamic Bootstrap 4 modal using JavaScript OOP. Please verify and give your reviews how I can improve the code. I have passed four parameters to create a dynamic modal:

openPopup class (for click)
data-title (dynamic title)
data-href (dynamic load html in modal)
data-target (target id if i have multiple modal)

    class Modal{
          constructor(id,url,title){
             this.id = id;
             this.url = url;
             this.title = title;
         }
       }
        class UI{
             static addModal(){
             $('body').on('click', '.openPopup', function(e) {
             const id = $(this).attr('data-target'),
             url = $(this).attr('data-href'),
             title = $(this).attr('data-title')
             const modal = new Modal(id, url, title);
             console.log(modal)
             if($('#'+ modal.id).length){
              $('#'+ modal.id).modal({show:true});
             }
            else{
            let html = `

${modal.title}

          <button type="button" class="close" data-dismiss="modal" aria-
            label="Close">
              &times;
            </button>

            <button type="button" class="btn btn-secondary" data-
                dismiss="modal">Close</button>
            <button type="button" id="save" class="btn btn-primary">Save
       changes</button>

`;
        $('body').append(html);
        $('#'+ modal.id + 'body').load(modal.url,function(){
       $('#'+ modal.id).modal({show:true});
       });
         }
       })
       }}
        class ModalApp{
           static init(){
             console.log('App Started...');
            UI.addModal()
            }
        }
        ModalApp.init();
   <button type="button" class="btn btn-primary openPopup"  data-title="Test
  about" data-href="partial/about.html" data-toggle="modal" data-
  target="myModal1">
    Launch demo about
   </button>

See the fiddle below

JSfiddle


texts: Computing the standard deviation of a Number array in Java

texts:
(See the next iteration.)

I have this funky class method for computing standard deviation from an array of Number objects using the Stream API:

StandardDeviation.java:

package net.coderodde.util;

import java.util.Arrays;

public class StandardDeviation {

    public static double computeStandardDeviation(Number... collection) {
        if (collection.length == 0) {
            return Double.NaN;
        }

        final double average =
                Arrays.stream(collection)
                      .mapToDouble((x) -> x.doubleValue())
                      .summaryStatistics()
                      .getAverage();

        final double rawSum =
                Arrays.stream(collection)
                      .mapToDouble((x) -> Math.pow(x.doubleValue() - average,
                                                   2.0))
                      .sum();

        return Math.sqrt(rawSum / (collection.length - 1));
    }

    public static void main(String[] args) {
        // Mix 'em all!
        double sd = computeStandardDeviation((byte) 1,
                                             (short) 2,
                                             3,
                                             4L,
                                             5.0f,
                                             6.0);

        System.out.println(sd);
    }
}

Please, tell me anything that comes to mind.


texts: Making a dynamic parser to collect data from a javascript enabled webpage

texts:
I've written a scraper in VBA in combination with selenium to parse product names and prices from a javascript enabled webpage. The thing is that I just used selenium to get the page source (as it was not possible to get the response text without opening the page with selenium) and as soon as I get it I reverted back to usual VBA method to complete the operation.

Most importantly, it was hard to deal with parsing prices cause there are two types of class names for prices so if a particular class name is used in the script then it is noticed that, after scraping is done, some fields are blank in the price section in the spreadsheet.

However, I have handled the two class names effectively in my parser to get prices flawlessly. Now, it is working great and way faster than selenium alone. If there is any improvement I can make in this script, I would be very happy to comply. Thanks in advance.

Here is what I've written:

Sub RedmartScraper()
  Dim driver As New ChromeDriver, html As New HTMLDocument
  Dim post As HTMLHtmlElement

  With driver
    .Get "https://redmart.com/bakery"
    html.body.innerHTML = .ExecuteScript("return document.body.innerHTML;")
    .Quit
  End With

  For Each post In html.getElementsByClassName("productDescriptionAndPrice")
    With post.getElementsByTagName("h4")(0).getElementsByTagName("a")
      If .Length Then i = i + 1: Cells(i, 1) = .item(0).innerText
    End With

    With post.getElementsByClassName("ProductPrice__promo_price___3OWY9")
        If .Length Then Cells(i, 2) = .item(0).innerText
    End With

    With post.getElementsByClassName("ProductPrice__price___3BmxE")
        If .Length Then Cells(i, 2) = .item(0).innerText
    End With
  Next post
End Sub

Btw, libraries to add in the reference library:

Microsoft Html Object Library
Selenium Type Library


texts: Getting weather data from Open Weather Map API

texts:
I'm trying to make a simple app in C# that gets the weather data from http://openweathermap.org/api (OWM).

Here attached are two classes that I use to initialize WeatherData for selected City and to download and parse XML data from OWM API. I would like to know your opinion on the structure of the classes and the way I use them, because now I'm really not sure how should it work assuming that I would like to get/print more weather data in future.

I use them as follows:

WeatherData WarsawWeather = new WeatherData("Warsaw");
WarsawWeather.CheckWeather();
System.Console.WriteLine(WarsawWeather.Temp);

Classes:

using System.Net;
using System.Xml;

namespace WeatherApp
{
    class WeatherData
    {
        public WeatherData(string City)
        {
            city = City;
        }
        private string city;
        private float temp;
        private float tempMax;
        private float tempMin;

        public void CheckWeather()
        {
            WeatherAPI DataAPI = new WeatherAPI(City);
            temp = DataAPI.GetTemp();
        }

        public string City { get => city; set => city = value; }
        public float Temp { get => temp; set => temp = value; }
        public float TempMax { get => tempMax; set => tempMax = value; }
        public float TempMin { get => tempMin; set => tempMin = value; }
    }
    class WeatherAPI
    {
        public WeatherAPI(string city)
        {
            SetCurrentURL(city);
            xmlDocument = GetXML(CurrentURL);
        }

        public float GetTemp()
        {
            XmlNode temp_node = xmlDocument.SelectSingleNode("//temperature");
            XmlAttribute temp_value = temp_node.Attributes["value"];
            string temp_string = temp_value.Value;
            return float.Parse(temp_string);
        }

        private const string APIKEY = "API KEY HERE";
        private string CurrentURL;
        private XmlDocument xmlDocument;

        private void SetCurrentURL(string location)
        {
            CurrentURL = "http://api.openweathermap.org/data/2.5/weather?q="
                + location + "&mode=xml&units=metric&APPID=" + APIKEY;
        }

        private XmlDocument GetXML(string CurrentURL)
        {
            using (WebClient client = new WebClient())
            {
                string xmlContent = client.DownloadString(CurrentURL);
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(xmlContent);
                return xmlDocument;
            }
        }
    }
}

Example XML from OWM:

<current>
<city id="756135" name="Warsaw">
<coord lon="21.01" lat="52.23"/>
<country>PL</country>
<sun rise="2016-12-27T06:45:16" set="2016-12-27T14:30:06"/>
</city>
<temperature value="2" min="2" max="2" unit="metric"/>
<humidity value="80" unit="%"/>
<pressure value="1019" unit="hPa"/>
<wind>
<speed value="6.7" name="Moderate breeze"/>
<gusts/>
<direction value="310" code="NW" name="Northwest"/>
</wind>
<clouds value="40" name="scattered clouds"/>
<visibility value="10000"/>
<precipitation mode="no"/>
<weather number="802" value="scattered clouds" icon="03n"/>
<lastupdate value="2016-12-27T20:00:00"/>
</current>


texts:
As a beginner in Rust i am trying to practice Rust with some little programs
so here is my implementation of Decimal to Binary.

use std::io;

pub fn run() {
    let number = input("Enter an input");
    println!("{}", to_binary(number));
}

fn input(msg: &str) -> i32 {
    println!("{}", msg);
    let mut number = String::new();
    io::stdin()
        .read_line(&mut number)
        .expect("Failed to read input");

    match number.trim().parse() {
        Ok(num) => num,
        Err(_e) => panic!("Not a number"),
    }
}

fn to_binary(mut decimal: i32) -> i32 {
    if decimal == 0 {
        decimal
    } else {
        let mut bits = String::new();

        while decimal > 0 {
            if decimal % 2 == 0 {
                bits.push_str("0");
            } else {
                bits.push_str("1");
            }

            decimal /= 2;
        }

        // reverse the bits
        match bits.chars().rev().collect::<String>().parse() {
            Ok(num) => num,
            Err(_e) => panic!("Something went wrong"),
        }
    }
}

so feel free to advice anything you consider.
i just have three questions in particular

isn't it better to write input as a macro ?
how can i write to_binary as pure function ?
wouldn't be better to return binary type from to_binary instead i32


texts:
I want to implement a thread-safe singly linked list in C. Its nodes contain unique entries and I only need functions to add nodes (to head only), remove nodes and to locate a specific node.

I am reasonably confident of the linked-list logic (any performance tips would be greatly appreciated though), but I am more concerned with my thread-safety logic. This is my first real foray into coding a thread-safe data structure. Is it optimal? Is it overkill? Is there a more performant way to get thread-safety for this data structure?

Thread-safety definitions from header:

#define MY_SPINLOCK_INIT 0
typedef volatile int MYSpinLock;

__attribute__((always_inline))
static inline void MYSpinLockLock(MYSpinLock *lock) {
    while (__sync_lock_test_and_set(lock, 1))
        while (*lock)
            ;
}
__attribute__((always_inline))
static inline void MYSpinLockUnlock(MYSpinLock *lock) {
    __sync_lock_release(lock);
}

Struct definitions:

typedef struct {
    const void *_key;
    uintptr_t _value;
} MYEntry;

typedef struct __MYNode {
    MYEntry _entry;
    struct __MYNode *_next;
} MYNode;

typedef struct {
    MYNode *_head;
    MYSpinLock _lockLL;
} MYLinkedList;

Implementation:

#define MY_LISTLOCK_LOCK MYSpinLock *MY_macro_lock = &(list->_lockLL); MYSpinLockLock(MY_macro_lock)
#define MY_LISTLOCK_UNLOCK MYSpinLockUnlock(MY_macro_lock)

MYLinkedList *MYLinkedListConstruct() {
    MYLinkedList *list = malloc(sizeof(MYLinkedList));
    list->_head = NULL;
    list->_lockLL = MY_SPINLOCK_INIT;
    return list;
}

void MYLinkedListFree(MYLinkedList *list) {
    MY_LISTLOCK_LOCK;

    MYNode *node = list->_head;
    MYNode *next;
    while (node != NULL) {
        next = node->_next;
        free(node);
        node = next;
    }

    MY_LISTLOCK_UNLOCK;
    free(list);
}

void MYLinkedListAdd(MYLinkedList *list, MYEntry *entry) {
    MY_LISTLOCK_LOCK;

    MYNode *oldHead = list->_head;
    MYNode *newHead = malloc(sizeof(MYNode));
    newHead->_entry = *entry;
    newHead->_next = oldHead;
    list->_head = newHead;

    MY_LISTLOCK_UNLOCK;
}

MYBool MYLinkedListRemoveNodeWithEntryKey(MYLinkedList *list, void *keyOfNodeToRemove) {

    if (keyOfNodeToRemove == NULL) return MYFalse;
    MY_LISTLOCK_LOCK;

    MYNode *node = list->_head;
    MYNode *prev = NULL;
    while (node != NULL) {
        // We found it, break
        if (node->_entry._key == keyOfNodeToRemove) break;

        prev = node;
        node = node->_next;
    }

    // We never found it
    if (node == NULL) {
        MY_LISTLOCK_UNLOCK;
        return MYFalse;
    }

    // We found it
    if (prev == NULL) {
        list->_head = node->_next;
        free(node);
    }
    else {
        prev->_next = node->_next;
        free(node);
    }

    MY_LISTLOCK_UNLOCK;
    return MYTrue;
}

MYNode *MYLinkedListFindNodeWithKey(MYLinkedList *list, void *keyToFind) {

    if (keyToFind == NULL) return NULL;
    MY_LISTLOCK_LOCK;

    MYNode *node = list->_head;
    while (node != NULL) {
        if (node->_entry._key == keyToFind) {
            MY_LISTLOCK_UNLOCK;
            return node;
        }
        node = node->_next;
    }

    MY_LISTLOCK_UNLOCK;
    return NULL;
}


texts: Python word counter for all files in the current directory

texts:
I wrote a simple command-line script to count all words in all documents (of the supported formats) in the current directory. Currently it supports TXT, DOCX, XLSX, and PDF formats and has been satisfactorily tested with them. As a freelance translator and content writer, this script provides me with an excellent tool, to quickly evaluate the scope of large projects by simply "dropping" the script into a directory and running it from PowerShell/Terminal.

Currently tested in Windows 10 only.

What do you think of this script? What should I improve?

import os
import openpyxl
import platform
import docx2txt
import PyPDF2

def current_dir():
    if platform.system() == "Windows":
        directory = os.listdir(".\\")
    else:
        directory = os.getcwd()
    return directory

def excel_counter(filename):
    count = 0
    wb = openpyxl.load_workbook(filename)
    for sheet in wb:
        for row in sheet:
            for cell in row:
                text = str(cell.value)
                if text != "None":
                    word_list = text.split()
                    count += len(word_list)
    return count

def pdf_counter(filename):
    pdf_word_count = 0
    pdfFileObj = open(filename, "rb")
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
    number_of_pages = pdfReader.getNumPages() - 1
    for page in range(0, number_of_pages + 1):
        page_contents = pdfReader.getPage(page - 1)
        raw_text = page_contents.extractText()
        text = raw_text.encode('utf-8')
        page_word_count = len(text.split())
        pdf_word_count += page_word_count
    return pdf_word_count

def main():
    word_count = 0
    print(f"Current Directory: {os.getcwd()}")
    for file in current_dir():
        file_name_list = os.path.splitext(file)
        extension = file_name_list[1]
        if extension == ".xlsx":
            current_count = excel_counter(file)
            print(f"{file} {current_count}")
            word_count += current_count
        if extension == ".docx":
            text = docx2txt.process(file)
            current_count = len(text.split())
            print(f"{file} {current_count}")
            word_count += current_count
        if extension == ".txt":
            f = open(file, "r")
            text = f.read()
            current_count = len(text.split())
            print(f"{file} {current_count}")
            word_count += current_count
        if extension == ".pdf":
            pdf_word_count = pdf_counter(file)
            print(f"{file} {pdf_word_count}")
            word_count += pdf_word_count
        else:
            pass
    print(f"Total: {word_count}")

main()


texts: Recursive implementation of a zip function in F#

texts:
I'm learning F# from Tomas Petricek's "Real-World Functional Programming" book. As suggested at one point in the book, I started implementing a zip function using a recursive sequence expression. I'm not very happy with my implementation and I would like to know how F# devs would refactor my implementation. I know that the original zip function is implemented using map2 but I want to stick with the recursive sequence expression. Any suggestion would expand my horizon.

// Create the zip function
let zipRec first second =
  let rec loop r xs ys = seq {
    if Seq.isEmpty xs || Seq.isEmpty ys then yield r
    else
      let r = Seq.append r (Seq.singleton((Seq.item 0 xs, Seq.item 0 ys)))
      yield! loop r (Seq.tail xs) (Seq.tail ys) }
  loop Seq.empty first second

// test
zipRec [1;2;3;4] [|"one"; "two" |] |> List.ofSeq |> printfn "%A"

What I don't like about my code:

It feels too imperative
I'm using a lot of the functions in the Seq module. Can this be written more F# idiomatic (short, concise, using more functional programming style)?
Does the code perform fast enough for real world scenarios? (I've used tail recursion)
Is the code robust enough (in regards to exceptions)?


texts:
Background
We have to cater to large screens. So I created this portion of a grid system which is shown to users with screens larger than 1800px.

Solution
This grid is 1800px wide but can shrink down to 1200px, has 8 columns. I wanted 10px margin around the sides of each column. So I arrived at the number of 0.55555%.

To get to any column size i:

Divided the total width of 1800px by 8
Subtracted 20px
Divided the solution by 1800px

For example, to get the size of 3 columns:

1800 / 8 = 225
225 x 3 = 675
675 - 20 = 655
655 / 1800 = 0.3638888
3 columns = 36.38888%

Then I just plugged in the values.

.belt {
  width: 1800px;
  max-width: 100%;
  min-width: 1201px;
  margin: 0 auto;
}
.belt .m1 { width: 11.388888%; }
.belt .m2 { width: 23.88888%; }
.belt .m3 { width: 36.38888%; }
.belt .m4 { width: 48.888888%; }
.belt .m5 { width: 61.388888%; }
.belt .m6 { width: 73.88888%; }
.belt .m7 { width: 86.38888%; }
.belt .m8 { width: 98.88888%; }

.belt .m1,.belt .m2, .belt .m3, .belt .m4, .belt .m5, .belt .m6, .belt .m7, .belt .m8
{
  float: left;
  margin-left: 0.55555%;
  margin-right: 0.55555%;
}

Naming this the Saturn framework since Saturn is huge. And the wrapper is named a belt, which is equivalent to Skeleton's .container class.

The columns are prefixed by an m as in moon. (i.e. .m1, .m2, .m3, etc.)

Demo available on this CodePen


texts: C++17 enum macro with to_string operator

texts:
I created a simple enum macro that creates a to_string method for the enum.  This has been done before, but my version is designed to compile quickly.  From what I can tell, existing libraries use deep preprocessor macros and lots of template instantiations which is taxing for large enums.
Here is the code:
#include <array>
#include <string_view>

#define EnumWithUnderlying(Name, NTy, ... )\
enum class Name : NTy {__VA_ARGS__, End };\
namespace std {\
    std::string_view to_string(enum Name enumIn) noexcept {\
        constexpr static string_view fullstr = #__VA_ARGS__ ", End ";\
        struct BeginLen {\
            std::size_t begin;\
            std::size_t len;\
        };\
        using ArrIdxTy = std::array<BeginLen, NTy(Name::End)+1>;\
        constexpr static ArrIdxTy begins = [&]() {\
            ArrIdxTy ret = {};\
            std::size_t jbegin = 0;\
            std::size_t jend = 0;\
            enum ParserState {Before,In,After};\
            ParserState state = Before;\
            for (std::size_t i = 0; i < fullstr.size(); ++i) {\
                auto isSpace = [](char ch) -> bool {\
                    return ch == ' ' || ch == '\t' || ch == '\n';\
                };\
                switch (state) {\
                    case Before:\
                        if (!isSpace(fullstr[i])) {\
                            ret[jbegin].begin = i;\
                            jbegin++;\
                            state = In;\
                        } else {\
                            break;\
                        }\
                    case In:\
                        if (isSpace(fullstr[i]) || fullstr[i] == ',') {\
                            ret[jend].len = i - ret[jend].begin;\
                            jend++;\
                            state = fullstr[i] == ',' ? Before : After;\
                        } else {\
                            break;\
                        }\
                        break;\
                    case After:\
                        if (fullstr[i] == ',') {\
                            state = Before;\
                        }\
                        break;\
                }\
            }\
            return ret;\
        }();\
        using ArrStrTy = std::array<std::string_view, NTy(Name::End)+1>;\
        constexpr static ArrStrTy strs = [&]() {\
            ArrStrTy ret = {};\
            for (std::size_t i = 0; i < begins.size(); ++i) {\
                ret[i] = std::string_view(fullstr.begin() + begins[i].begin, begins[i].len);\
            }\
            return ret;\
        }();\
        return strs[NTy(enumIn)];\
    };\
}
#define Enum(Name,...) EnumWithUnderlying(Name, int, __VA_ARGS__)

Example usage:
#include <iostream>
#include "enum.h"

EnumWithUnderlying(Move, char,
  UP,
  DOWN,
  LEFT,
  RIGHT
);

Enum(Letter, A, B);

int main() {
std::cout <<
    std::to_string(Move::UP) << " " <<
    std::to_string(Move::DOWN) << " " <<
    std::to_string(Move::LEFT) << " " <<
    std::to_string(Move::RIGHT) << " " <<
    int(Move::End) << " " <<
    std::to_string(Letter::A) << " " <<
    std::to_string(Letter::B) << " " <<
    std::endl;
}

I'm open to any comments, but I don't want to do anything that makes it take longer to compile.
Also, I noticed that making to_string constexpr/getting rid of the static members seems to generate worse code.  I don't fully understand why that is since I'd expect a constexpr version to be strictly faster.
For the record this is also on github


texts:
I'm trying to test an elevator simulator program that runs in the console and requires user interaction. At the moment, my tests look like this:

gem 'minitest', '>= 5.0.0'
require 'minitest/spec'
require 'minitest/autorun'
require_relative 'elevator'

class SingleFloorElevator < Elevator
  @@moves = ["2", "N"].each
  def get_input; @@moves.next end
end

class MultiFloorElevator < Elevator
  @@moves = ["2", "Y", "7", "Y", "4", "N"].each
  def get_input; @@moves.next end
end

class InvalidElevetorOne < Elevator
  @@moves = ["-2", "2"].each
  def get_input; @@moves.next end
end

class InvalidElevatorTwo < Elevator
  @@moves = ["2000", "5"].each
  def get_input; @@moves.next end
end

class ElevatorTest < MiniTest::Test
  def test_can_accept_and_move_to_floor
    e = SingleFloorElevator.new
    e.run
    assert_equal(e.current_floor, 2)
  end

  def test_can_change_direction
    e = MultiFloorElevator.new
    e.run
    assert_equal(e.going_down, true)
    assert_equal(e.going_up, false)
  end

  describe "it can maintain a list of floor numbers" do
    it "cannot travel below the ground floor" do
      e = InvalidElevetorOne.new
      e.enter_floor
      assert_equal(e.floors.size, 1)
      assert_equal(e.floors, [2])
    end

    it "cannot travel higher than the top floor" do
      e = InvalidElevatorTwo.new
      e.enter_floor
      assert_equal(e.floors.size, 1)
      assert_equal(e.floors, [5])
    end
  end
end

As you can see, I'm overriding the Elevator class (more important the get_input method which grabs user input from the console) multiple times according to what I need to test. It all works perfectly fine but I was wondering if there was a tidier way of doing things?


texts: Discern and perform an operation on a list

texts:
I have some code that's meant to discern certain words in a list and then based on which word is in the list, do a mathematical operation on the numbers also found in the list. Here's my code:

  for (op in operations) {
    if (arrayses.letteros.indexOf(op) !== -1) {
      found = true;
      break;
    }
  }
  if (found) {
    var result = arrayses.numeros[0];
    while (i < arrayses.numeros.length) {
      if (i === 0) {
        result = arrayses.numeros[0];
      } else {
        result = operations[op](result, arrayses.numeros[i]);
      }
      i += 1;
    }

The part of the code I'm having trouble with is the very first line up there. My program has to pass JSLint based on the assumption I'm using a browser and tolerating multiple variables and whitespace mess. JSLint says the for in my for...in statement up there is unexpected; are there any alternatives to using that statement? It's used to look for the operations listed above my function in a global variable.

Here's where operations is defined, it's a global variable:

var operations = {
  add: function(a, b) {
  "use strict";
    return Number(a) + Number(b);
  },
  subtract: function(a, b) {
  "use strict";
    return a - b;
  },
  multiply: function(a, b) {
  "use strict";
    return a * b;
  },
  divide: function(a, b) {
  "use strict";
    return a / b;

  }
};


texts:
The "nasty implementation" I mentioned is within the void calculator() inside of calculator.cpp. Everything goes well as long as user don't type in the erroneous syntax. But I think this isn't the good idea to implement it this way.
Can I do it the other way around with more reasonable implementation without losing the functionality of being able to calculate infinitely(not really,I know).

main.cpp:

#include <iostream>
#include "calculator.h"

int main()
{
    calculator();
    return 0;
}

calculator.cpp:

#include <iostream>
#include <cassert>
#include "calculator.h"

int getIntInput()
{
    int x{};
    std::cin >> x;
    assert("Syntax Error!!" && !std::cin.fail());
    return x;
}

char getOperatorInput()
{
    char x{};
    std::cin >> x;
    bool b{x == '+' || x == '-' || x == '*' || x == '/' || x == '^'};
    assert("Syntax Error!!" && b);
    return x;
}

int calculate(int x)
{
    char op{getOperatorInput()};
    int tmp{getIntInput()};
    if(op == '+')
    {
        return x + tmp;
    }
    else if(op == '-')
    {
        return x - tmp;
    }
    else if(op == '*')
    {
        return x * tmp;
    }
    else if(op == '/')
    {
        return x / tmp;
    }
    return 0;
}

void calculator()
{
    std::cout << "Enter your expression : ";
    int64_t result{};
    int loopCount{0};
    do{
            if(loopCount == 0)
                result = getIntInput();
            result = calculate(result);
            loopCount++;
    }
    while(std::cin.peek() != '\n');
    std::cout << "Your result is : " << result << '\n';
}

calculator.h:

#ifndef CALCULATOR_H
#define CALCULATOR_H

int getIntInput();
char getOperatorInput();
void calculator();

#endif // CALCULATOR_H
```


texts: What's the fastest way to get the points I want out of a huge blob?

texts:
In MATLAB I have a set of 5393280 points in the form of a decimal-valued vector (x,y,z). How do I represent them in a way that I can quickly collect all the points within some rectangular x-y domain?

Right now I'm representing them as a 3-column matrix, sorted by x-values, and using the following code to extract a rectangular region:

mtx_region = mtx_pointList( dxLowerBound < mtx_pointList(:,1) & ...
                            dxUpperBound > mtx_pointList(:,1) & ...
                            dyLowerBound < mtx_pointList(:,2) & ...
                            dyUpperBound > mtx_pointList(:,2), : );

However, I suspect that this is slowing my code down considerably.

What is a better way?


texts: JS Stopwatch - Is this a good way to implement the observer pattern?

texts:
I'm learning oop and also trying to learn and implement some design patterns.
This question is a follow up of Stopwatch interface OOP (Vanilla JS)
The app is available in https://nacho-p5.github.io/
Here's the code:
Repo: https://github.com/nacho-p5/nacho-p5.github.io
Community gave me good feedback and I made the following changes to my first codebase:

Changed syntax to ES6
Methods added to prototype rather than instance
Vars, attrs and methods names changed to be descriptive
Replaced error handler logic when start/stop are clicked twice
Time tracker logic changed. Count is calculated using Date.now() rather than counting setInterval iterations
Script tag position changed to head using defer
Stopwatch class should not know about the DOM -> Observer pattern implemented

As I wrote in the last point, I refactored the code using the observer pattern. I had two goals doing that:

Implement the observer pattern
One class - One thing: separation of concerns in stopwatch, ui and controller class

I know that trying to implement design patterns in a simple problem like this seems like overwork. This is purely for learning purposes.
What do you think about the code? Any feedback will be appreciated :)
stopwatch.js
class Stopwatch {
    _timer = 0;
    isRunning = false;
    startTime = 0;
    elapsedTime = 0
    observers = []

    get timer() {
        return this._timer
    }

    set timer(val) {
        this._timer = val
        this.notifyController(val)
    }

    registerObserver(observer) {
        this.observers.push(observer);
    };

    notifyController(val) {
        this.observers.forEach(observer => {observer.update(val)})
    }

    updateTime() {
        const newTime = Date.now() - this.startTime + this.elapsedTime;
        this.timer = newTime;
    };

    start() {
        if (!this.isRunning) {
            this.isRunning = true;
            this.startTime = Date.now();
            this.setIntervalID = setInterval(this.updateTime.bind(this), 100);
        };
    };

    stop() {
        if (this.isRunning) {
            clearInterval(this.setIntervalID);
            this.isRunning = false;
            this.elapsedTime = this._timer;
        };
    };

    reset() {
        clearInterval(this.setIntervalID);
        this.isRunning = false
        this.elapsedTime = 0;
        this.startTime = 0;
        this.timer = 0;
    };
};

class UI {
    constructor(displayID, btnStartID, btnStopID, btnResetID) {
        // HTML Components
        this.buttons = {
            start: document.getElementById(btnStartID),
            stop: document.getElementById(btnStopID),
            reset: document.getElementById(btnResetID)
        },
        this.display = document.getElementById(displayID)
    };

    resetAllButtonsStyle() {
        Object.values(this.buttons).forEach(e => e.classList.remove('activeBtn'))
    };

    showButtonAsActive(btn) {
        this.resetAllButtonsStyle();
        btn.classList.add('activeBtn')
    };

    updateDisplay(value) {
        this.display.innerText = value;
    };
}

class Controller {
    constructor(sw, ui) {
        this.sw = sw;
        this.ui = ui;

        // Add event listeners
        this.ui.buttons.start.addEventListener('click', function() {
            sw.start();
            ui.showButtonAsActive(this);
        });
        this.ui.buttons.stop.addEventListener('click', function() {
            if (sw.isRunning) {
                sw.stop();
                ui.showButtonAsActive(this);
            };
        });
        this.ui.buttons.reset.addEventListener('click', function() {
            sw.reset();
            ui.resetAllButtonsStyle();
        });
    }

    update(val) {
        ui.updateDisplay((val/1000).toFixed(3))
    }
}

// Initialize classes

const ui = new UI('sw-display', 'btnStart', 'btnStop', 'btnReset');
const sw = new Stopwatch();
const controller = new Controller(sw, ui);

// Register controller in sw
sw.registerObserver(controller);

////////////////////////


texts:
I'm using meteor and angular. Since I can't add modules after the angular bootstrap, I made a workaround and somewhat not satisfied with the way it was coded.

How can I improve this?:

(function() {
    var controllers = ngMeteor.newControllers,
        filters     = ngMeteor.newFilters,
        directives  = ngMeteor.newDirectives,
        services    = ngMeteor.newServices

    ngMeteor.config(function($controllerProvider) {
        for (var prop in controllers) {
            if (controllers.hasOwnProperty(prop)) {
                $controllerProvider.register(prop, controllers[prop]);
            }
        }
    });

    ngMeteor.config(function($filterProvider) {
        for (var prop in controllers) {
            if (filters.hasOwnProperty(prop)) {
                $filterProvider.register(prop, filters[prop]);
            }
        }
    });

    for (var prop in directives) {
        if (directives.hasOwnProperty(prop)) {
            ngMeteor.directive(prop, directives[prop]);
        }
    }

    for (var prop in services) {
        if (services.hasOwnProperty(prop)) {
            ngMeteor.services(prop, services[prop]);
        }
    }
})();

The variables above will just have the same structure. For example:

/* Controllers */

ngMeteor.newControllers = {

    MainCtrl: function($scope) {
                // ...
    },

    SubCtrl: function($scope) {
                // ...
    }

};


texts: NULL-eating / elimination version of fgets() in C

texts:
I've come up with the following routine to read data from a file stream, but I don't want any NULLs in the stream to terminate the string early.  This function will read in a "line", and allow it to be processed with normal C string functions.  Does anyone see any inherent problems or potential bugs in this routine?

char *my_fgets(char *Buf, int iMaxCount, FILE *fp)
{
    // Handle basic failures.
    if(!Buf) return NULL;
    if(iMaxCount < 1) return NULL;
    if(!fp) return NULL;

    // Create a buffer on the heap for our data to be read in
    char *lbuf = (char*)malloc(iMaxCount);
    char *p = lbuf;

    // Zero out the buffer, no stray chars please.
    memset(Buf, 0x00, iMaxCount);

    // Where are we at in the file?
    int b = ftell(fp);

    // Read in the buffer, up to iMaxCount-1.  Leave one char for a final NULL.
    size_t read = fread((void*)&lbuf[0], sizeof(char), iMaxCount-1, fp);
    lbuf[iMaxCount-1] = NULL;

    // Failed.
    if(!read) {
        free(lbuf);
        return NULL;
    }
    // Walk the buffer, looking for a newline char.  Once we find it, we know we are at the end of the line,
    // but we don't want to read past the number of bytes we originally read, in case we did not hit a newline.
    size_t left = read;
    while((left) && *(p++) != '\n') left--;

    // Copy the data we read to the return Buffer, up to the newline char.
    memcpy(Buf, lbuf, p - lbuf);
    // Set the file pointer to the newline char + 1
    fseek(fp, b+(p - lbuf), SEEK_SET);

    // Setup how many bytes we have left in the buffer to look at.
    left = (p - lbuf);
    p = Buf;

    while(left)
    {
        // Walk the buffer, looking for NULL chars.
        if(*(p++) == NULL) {
            char *p1;
            // We hit a NULL, so shift the buffer left, eat the NULL, and continue our search.
            for(p1 = p-1;p1 < (Buf + (iMaxCount-1));p1++) p1[0] = p1[1];
            // We ate one char, so we need to step back one byte, and continue our search.  This handles a case where two NULLs may be back to back.
            p--;
        }
        left--;
    }

    // If our last char is not a NULL, we need to set it to NULL to properly terminate the string.
    if((p > Buf) && *(p-1) != 0x0a && *p != NULL) *(--p) = 0x00;

    // Free our work buffer, and return the new 'clean' data.
    free(lbuf);
    return Buf;
}

It might of importance to note that this code is called by a Kernel driver, and MUST be fast.  Speed is totally of the essence here, which is why this is all in one function, and uses calls like fread() over fgets() to get a chunk of data in one shot.  That might not matter in the final analysis, but I thought I would mention it.


texts: Updating WPF MainWindow from an async task

texts:
Is this an acceptable approach to update WPF MainWindow from an async task, using events thrown from a public static class?

In MainWindow.cs, I subscribe to  UI.TaskCompleted event
In UI.cs, I subscribe to AsyncTaskActions.TaskCompleted event

Using this pattern, AsyncTaskActions.TaskCompleted is raised when an async task is completed.  UI catch the event and raise UI.TaskCompleted.  This way, the event is caught in MainWindow where I can use Displacher.Invoke to refresh the displayed page.  The end result is I get a page refresh when a task is completed and the task still runs asychronously.

Application design summary:

MainWindow: main window which can have several different page classes in content area within the main window.
Common.cs  public static class contains a number of common methods through the UI in the application.
AsyncTaskActions.cs - class with a number of async common methods (i.e. download file)

Code snippets:

    public partial class MainWindow
        public MainWindow()
        {
           UI.TaskCompleted += UI_TaskCompleted;
        }

        void UI_TaskCompleted(EventArgs e)
        {
           Dispatcher.Invoke(new Action(this.PageRefresh));
        }

       public void PageRefresh()
       {
           var page = ((ContentArea)).Content;
           if (page == null) return;

            //if (page.GetType().Name == "")
            switch (page.GetType().Name)
            {
                case "SearchPage":
                    ((SearchPage) page).SearchParts();
                    break;
                case "LegoPartPage":
                    ((LegoPartPage) page).LoadData();
                    break;
                case "LegoSetPage":
                    ((LegoSetPage) page).LoadData();
                    break;
                case "MainPage":
                    ((MainPage) page).LoadData();
                    break;
                case "MiniFigPage":
                    ((MiniFigPage) page).LoadData();
                    break;
            }
        }
   }

    public static class UI
    {
       public delegate void TaskComplete(EventArgs e);
       public static event TaskComplete TaskCompleted;

        public static async Task<int> DownloadPriceSummaryAsync(String itemNo, Int64 colorId)
        {
            var wAsyncTaskClasses = new AsyncTaskClasses();
            wAsyncTaskClasses.TaskCompleted += wAsyncTaskClasses_TaskCompleted;
            Task<HtmlDocument> task = wAsyncTaskClasses.DownloadPriceGuide(string.Format(Common.BrickLinkPrice, itemNo, colorId), itemNo, colorId);
            return await  wAsyncTaskClasses.ParsePriceSummaryAsync(task, itemNo, colorId);
        }
 }

public class AsyncTaskActions
{
    public delegate void TaskComplete(object sender, EventArgs e);
    public event TaskComplete TaskCompleted;

    public async Task<int> ParsePriceSummaryAsync(Task<HtmlDocument> task, string itemNo, Int64 colorId)
    {
        return await Task.Run(() => ParsePriceSummary(task, itemNo, colorId));
    }

    public int ParsePriceSummary(Task<HtmlDocument> task, string itemNo, Int64 colorId)
    {

        if (null != TaskCompleted)
        {
            TaskCompleted(this, new EventArgs());
        }

        return recordCount;
    }


texts:
I am writing some tests that all follow the same pattern, I feel like repeating myself over and over again, how can I reduce the repetition? The (almost) repeating part is in constructor and the class level variables:

VariablesPage

public class VariablesPage extends LoadableComponent<VariablesPage> {

    private final TestHelpers helpers;
    private WebDriver driver;

    @FindBy(xpath = "//a[@title=\"Define new variable\"]")
    private WebElement btnAddNewVariable;

    public VariablesPage() throws Exception {
        helpers = new TestHelpers();
        driver = helpers.getWebDriver();
        helpers.setHar(VariablesPage.class.getSimpleName());
        PageFactory.initElements(driver, this);
        isLoaded();
        helpers.getHar();
    }

    @Override
    protected void load() {

    }

    @Override
    protected void isLoaded() throws Error {
        helpers.waitUntil(btnAddNewVariable);
    }
}

addStepsPage

public class AddStepsPage extends LoadableComponent<AddStepsPage> {

    private final TestHelpers helpers;
    private WebDriver driver;
    @FindBy(xpath = "//div[@class=\"body sequential\"]")
    private WebElement divStepsBody;

    public AddStepsPage() throws Exception {
        helpers = new TestHelpers();
        driver = helpers.getWebDriver();
        helpers.setHar(AddStepsPage.class.getSimpleName());
        PageFactory.initElements(driver, this);
        isLoaded();
        helpers.getHar();
    }

    @Override
    protected void load() {

    }

    @Override
    protected void isLoaded() throws Error {
        helpers.waitUntil(divStepsBody);
    }
}


texts: Number of interesting numbers between two given numbers

texts:
Please have a look into this problem:

  Little Dipu is a small kid and like all the other kids, he likes to
  play, but he plays with numbers (he is extraordinary you know).
  Nowadays Dipu has some extra interest in odd numbers. So, he says that
  a number N is interesting if it has odd number of divisors. Now Dipu
  turns to you and asks you to tell him how many interesting numbers are
  there between two given numbers, L and R (both inclusive).

  Input:

  First line of input contains the number of test cases T. Each of the
  next T lines contains two space separated integers L and R.

  Output:

  For each test case, output an integer, denoting the count of
  interesting numbers between L and R (both inclusive).

  Constraints:

  \$1 \le T \le 100000\$
  \$1 \le L \le R \le 1018\$

  Sample input:

2
1 3
6 10

  Sample output:

1
1

Below is a solution that I have come up with:

#include<stdio.h>
int main()
{

  long long int max,testcase,count,l,r;
  scanf("%lld",&testcase);

  while(testcase-->0)
  {
    max=0;
    scanf("%lld %lld",&l,&r);

    for(int i=l;i<=r;i++)
    {
      count=0;
      for(int j=1;j<=i;j++)
      {
        if(i%j==0)
        {
        count++;
        }
      }

      if(count%2!=0)
      {

          max=max+1;

      }
    }
    printf("%lld\n",max);

  }
}

The problem is the input constraint which is very large indeed, so my program will give the right outputs for some test cases but for larger inputs it will exceed the time allocated. Please help me to come up with another logic if possible which will make sure that the time allocated is not exceeded.

My program produces the right output but for larger inputs it takes more time than it should.


texts:
I had already solved this problem, but in an unnecessarily convoluted way that seems too specific. Can this be done better?

From a list:

(8 "layer-name" 10 x1 20 y1   10 x2 20 y2  10 x3 20 y3)

8, 10 and 20 are the "key-words" for layer-name, x-coord and y-coord respectively. The actual values follow the "key-words".

Return values should be --> '(("layer-name" x1 y1 x2 y2) ("layer-name" x2 y2 x3 y3))

#lang racket

(require srfi/1)

(define test-list '("multiple-lines" 8 "layer-name" 10 30 20 30   10 40 20 40   10 50 20 50))

(define (get-values lst lst2)
  (cond ((eq? lst2 '())
         '())
        (else
         (cons (cadr (member (car lst2) lst))
               (get-values lst (cdr lst2))))))

(define (get-multiple-values lst key key2) ; key is single values. key2 is repeatable values
  (define (splitter lst keyword) ; (splitter '(10 x1 20 y1 10 x2 20 y2 10 x3 20 y3) 10 20)  --->  '((x1 y1 x2 y2 x3 y3) (x2 y2 x3 y3) (x3 y3))
    (cond ((not (member keyword lst)) '())
          (else (cons (member keyword lst) (splitter (cddr (member keyword lst)) keyword)))))
  (define (joiner lst lst-of-lsts) ; (joiner '(1 2) '((a b) (c d)))  --->  '((1 2 a b) (1 2 c d))
    (cond ((empty? lst-of-lsts) '())
          (else (cons (append lst (car lst-of-lsts))
                      (joiner lst (rest lst-of-lsts))))))
  (define (trimmer size lst-of-lsts) ; (trimmer  '((x1 y1 x2 y2 x3 y3) (x2 y2 x3 y3) (x3 y3)))
    (cond ((empty? lst-of-lsts) '())
          ((> size (length (car lst-of-lsts)))
           (trimmer size (rest lst-of-lsts)))
          (else (cons (take (car lst-of-lsts) size)
                (trimmer size (rest lst-of-lsts))))))
  (joiner (get-values lst key)
          (trimmer 4 (map
                      (lambda (lst) (remq* key2 lst))
                      (splitter lst (first key2))))))

> '(("layer-name" 30 30 40 40) ("layer-name" 40 40 50 50))


texts: Getting the distance between various classes of shapes

texts:
Below I define a simple shape class with two derived classes: Point and Line which both implement the Distance interface that defines a getDistance(Shape) method.  This type of setup could be useful for calculating distances between shapes.  For this simple example, consider the distance to be in 1D space and don't consider the actual calculations.

package shape;

public interface Distance {
    public int getDistance(Shape other);
}

public abstract class Shape implements Distance {
    public abstract int getDistance(Shape shape);
    public abstract int getDistance(int num); //for point
    public abstract int getDistance(int start, int end); //for line
}

public class Line extends Shape {
    private int start;
    private int end;

    public Line(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public int getDistance(Shape other) {
        return other.getDistance(start, end);
    }

    //never gets called
    public int getPoint(Point other) {
        return getDistance(other.num);
    }

    @Override
    public int getDistance(int num) {
        return Math.min(Math.abs(num - start), Math.abs(num - end));
    }

    @Override
    public int getDistance(int start, int end) {
        int delta1 = Math.min(Math.abs(this.start - start), Math.abs(this.start - end));
        int delta2 = Math.min(Math.abs(this.end - start), Math.abs(this.end - end));
        return Math.min(delta1, delta2);
    }
}

public class Point extends Shape {
    protected int num;

    public Point(int num) {
        this.num = num;
    }

    @Override
    public int getDistance(Shape other) {
        return other.getDistance(num);
    }

    @Override
    public int getDistance(int num) {
        return Math.abs(this.num - num);
    }

    @Override
    public int getDistance(int start, int end) {
        return Math.min(Math.abs(num - start), Math.abs(num - end));
    }
}

public class ShapeTest {
    public static void main(String[] args) {
        Shape line = new Line(1, 2);
        Shape point = new Point(0);
        System.out.println(line.getDistance(point));
    }
}

My question is with the implementation above, there's a lot of indirection.  For example, in the Line and Point classes, for the following method: public int getDistance(Shape other), it's not known at compile time what Shape actually is.  So to avoid doing instanceof on Shape and handling each case in that function, I call getDistance on other and pass in the relevant coordinates -- this is the indirection that's a bit ugly, but it's a more object-oriented / polymorphic approach than casting and instanceof.

Question is: is there a cleaner way to implement this?  I'd like to define the required function int getDistance(Shape), leave it empty, and then define getDistance(Line) and getDistance(Point).  With those functions defined, it would be nice if Java just always called the most specific function prototype (so that getDistance(Shape) is never actually called), but that doesn't seem to happen.

Any advice on how to clean up the code above?


texts:
I'm loading my game's sound effects into an array to easily pick a random one and play it. Previously, I used a switch statement to select a random sound but it looks less verbose to just pick an array key.
Is it inefficient to use an array to store and play my sound effects? Is there a better way to do this or any improvements I can make to my implementation?
let sounds = [];

function loadSounds() {
  const sources = ['sound1.ogg', 'sound2.ogg', 'sound3.ogg', 'sound4.ogg', 'sound5.ogg', 'sound6.ogg'];

  for (let i = 0; i < sources.length; i++) {
      sounds[i] = new Audio(sources[i]);
  }
}

function playRandomSound() {
    const randomNumber = Math.floor(Math.random() * 6);

    sounds[randomNumber].play();
}


texts: LeetCode: Remove Duplicates from Sorted Array

texts:
Please review for performance

https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/727/

  Given a sorted array nums, remove the duplicates in-place such that
  each element appear only once and return the new length.

  Do not allocate extra space for another array, you must do this by
  modifying the input array in-place with O(1) extra memory.

  Example 1:

  Given nums = [1,1,2],

  Your function should return length = 2, with the first two elements of
  nums being 1 and 2 respectively.

  It doesn't matter what you leave beyond the returned length. Example
  2:

  Given nums = [0,0,1,1,1,2,2,3,3,4],

  Your function should return length = 5, with the first five elements
  of nums being modified to 0, 1, 2, 3, and 4 respectively.

  It doesn't matter what values are set beyond the returned length.

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// <summary>
    /// Remove Duplicates from Sorted Array
    /// https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/727/
    /// </summary>
    [TestClass]
    public class RemoveDuplicatesfromSortedArray
    {
        [TestMethod]
        public void RemoveDuplicates5()
        {
            int[] nums = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
            int[] excpected = {0, 1, 2, 3, 4};
            int res = RemoveDuplicates(nums);
            Assert.AreEqual(5,res);
            for (int i = 0; i < res; i++)
            {
                Assert.AreEqual(excpected[i], nums[i]);
            }
        }

        public int RemoveDuplicates(int[] nums)
        {
            if (nums.Length <= 1)
            {
                return nums.Length;
            }

            int current = nums[0];   //1
            int newLength = 1;          //2
            for (int i = 1; i < nums.Length; i++) // i = 5
            {
                if (nums[i] != current)
                {
                    nums[newLength] = nums[i];  //0,1,2
                    newLength++;
                    current = nums[i];
                }
                //else continue to next item
            }

            return newLength;
        }
    }
}


texts:
Following is the code I am using to find a separate count for alphabets and numeric characters in a given alphanumeric string:

   Public Sub alphaNumeric(ByVal input As String)
        'alphaNumeric("asd23fdg4556g67gh678zxc3xxx")
        'input.Count(Char.IsLetterOrDigit)
        Dim alphaCount As Integer = 0 '<-- initialize alphabet counter
        Dim numericCount As Integer = 0 '<-- initialize numeric counter
        For Each c As Char In input '<-- iterate through each character in the input
            If IsNumeric(c) = True Then numericCount += 1 '<--- check whether c is numeric? if then increment nunericCounter
            If Char.IsLetter(c) = True Then alphaCount += 1 '<--- check whether c is letter? if then increment alphaCount
        Next
        MsgBox("Number of alphabets : " & alphaCount) '<-- display the result
        MsgBox("Number of numerics : " & numericCount)
    End Sub

Everything works fine for me. Let me know how I can make this simpler.


texts: The optimized way to find the top k leading candidates from a unsorted hash map in python

texts:
I need to write a method that will accept a timestamp and takes an array of votes, I need to return the k leading candidates with that timestamp. I came up with the following solution,

Here is the input to the methods:

votes = [{'candidate':'a', 'timestamp':2},{'candidate':'c', 'timestamp': 5},{'candidate':'c', 'timestamp': 12}]

timestamp = 5

k = 5

And the method to solve the problem,

def leading_candidates(votes, timestamp,k):

    candidates = {}
    leading_candidates = []

    for vote in votes:
        if vote['timestamp'] <= timestamp:
            if vote['candidate'] not in candidates:
                candidates[vote['candidate']] = 1
            else:
                candidates[vote['candidate']] += 1

    sorted_votes = sorted(candidates.values())[:k]

    for candidate in candidates:
        if candidates[candidate] in sorted_votes:
            leading_candidates.append(candidate)

    return leading_candidates

print(leading_candidates(votes, timestamp, 2))

As you can see the second solution has a time complexity of \$O(k\,n)\$ where k is the time it takes to find the index in the leading candidates sorted array, In the worst case, it can be \$O(n^2)\$ and because of sorting it may be at least \$O(n\,\log n)\$.

Is there any way we can make it work with \$O(n)\$?


texts:
I wrote an EF browser to dynamically navigate through entities. Beside basic properties of system types, each entity can have several singular or plural navigation properties. In order to support all of these using a single batch of code, I come up with the following solution considering the following requirement:

Each entity has an integer ID primary key.

Sample query strings (Person is an entity (ID = 10) with Job and Cars navigation property):

Person/10/Job

Person/10/Cars

Solution:

public List<dynamic> LoadEntitiesByQuery(String query) {

    String[] parts = query.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
    String entityName = parts[0];
    int id = int.Parse(parts[1]);
    String subEntityName = parts[2];

    Type entityType = GetTypeFromEntityName(entityName);

    var tempObj = db.Set(entityType)
                    .AsQueryable()
                    .Where(String.Format("ID == {0}", id))
                    .FirstOrDefault();

    var propertyInfo = tempObj.GetType().GetProperty(subEntityName);

    List<dynamic> objects;

    if (propertyInfo.PropertyType.IsGenericType)
        objects = ((IEnumerable<dynamic>)propertyInfo.GetValue(tempObj, null)).ToList();
    else
    {
        var tr = propertyInfo.GetValue(tempObj, null);
        objects = new List<dynamic>();
        objects.Add(tr);
    }

    return objects;
}

internal static Type GetTypeFromEntityName(string entityName)
{
    Type entityType = null;
    switch (entityName)
    {
        case "Person":
            entityType = typeof(Person);
            break;
        case "Job":
            entityType = typeof(Job);
            break;

        ///  ....
    }
    return entityType;
}

I'm looking for faster ways of doing dynamic query instead of reflection.


texts:
I have an object, KbArticle, that originally in it's constructor, would try to return null if the SQL query that retrieves the data for its required properties came up with 0 rows. A friend told me that constructors shouldn't return null, and that I should look into the Factory Pattern. I did and I see the benefits, so I'm wondering how I can implement this better/"properly."

Quick overview: Knowledgebase.php is the page an end-user sees, it calls a function in  factory.php which calls the constructor in kb_fnc.php and then it ends up creating the object back on Knowledgebase.php if things all go well.

Knowledgebase.php

<?php
if ($kb = Factory::make('KbArticle', $_GET['a'])) {
    $kb->echoNavTrail();
} else {
    die('failed constructor');
}
?>

factory.php

Note: It disappoints me that apparently the functions in here have to be public instead of private, because my factory method is static? This seems not ideal, or am I incorrect?

<?php

require_once('kb/kb_fnc.php');

class Factory {
    public static function make($obj, $params) {
        $succ = false;
        switch($obj) {
            case('KbArticle'):
                return tryNewKnowledgebaseArticle($params);
                break;
        }
    }
}

function tryNewKnowledgebaseArticle($id) {
        try {
            $kb = new KbArticle($id);
        } catch (Exception $e) {
            return null;
        }
        return $kb;
    }
?>

kb_fnc.php

Note: Is throwing an exception here smart? In my quick tests yesterday, I couldn't access the custom string on the exception after it was chained back, so it seems not that useful—at least not without knowing how to log that string to console at the end or something, for debugging purposes.

class KbArticle {
    function __construct($id) {
        //do SQL
        if (odbc_num_rows($res) > 0) {
            //fill in properties with data from table
        } else {
            throw new Exception('KbA constructor failed SQL query');
        }
    }
}

My biggest questions are regarding:

Does this look sensible?
Can I access that custom exception string in my factory class, so I can ultimately encode it in JSON for a console.log for easier debugging if things go awry down the line?
The functions in my factory class being public instead of encapsulated as private bothers me.


texts:
What do you think about the following syntax for some very simple and intensively reusable validations?

Does this:

string name = (SomeText)"Hm…";

mean for you a none-safe cast to none-empty required text? How does it play with C# syntax/semantics? So these two should throw:

string name = (SomeText)null;
string name = (SomeText)"";

More examples:

int Age = (AdultAge)43; // OK
int Age = (AdultAge)10; // throws…

Basically, I am just looking for type alias with a guard constrain, but not so many things are possible in C#...

Let’s define the casts (yes, it is ugly):

class SomeText : Constrain<SomeText, string>
{
    public static implicit operator SomeText(string value) =>
        Create(value, !string.IsNullOrWhiteSpace(value));
}

class AdultAge : Constrain<AdultAge, int>
{
    public static implicit operator AdultAge(int value) =>
        Create(value, value >= 21);
}

Where library code is:

abstract class Constrain<TConstrain, TValue>
    where TConstrain : Constrain<TConstrain, TValue>, new()
{
    public static implicit operator TValue(Constrain<TConstrain, TValue> check) =>
        check.Value;

    protected static TConstrain Create(TValue value, bool satisfied, string message = null)
    {
        if (!satisfied)
            throw new ArgumentException(message ?? $"{typeof(TConstrain).Name} required.");
        else
            return new TConstrain() { Value = value };
    }

    TValue Value { get; set; }
}

P.S. More examples:

string email = (EMail)"test@example.com";
Stream stream = (InputStream)File.OpenText("c:\Autoexec.bat");
double weight = (Positive)160;

P.P.S. Even more examples:

class Adult
{
    public Adult(string name, int age)
    {
        Name = (SomeText)name;
        Age = (AdultAge)age;
    }

    public override string ToString() => $"{Name}, {Age}";
    string Name { get; }
    int Age { get; }
}