QuickSort for a List I want my QuickSort class to have a static sort method that sort any List for any object that extends Comparable. Have I coded my class correctly? Can I make the use of generics a bit cleaner or is this the only way to code the signatures of the methods?

import java.util.List;

public class QuickSort{

    private QuickSort() {
        // prevent instantiation
    }

    public static <T extends Comparable<? super T>> void sort(List<T> list) {
        quickSort(list, 0, list.size());
    }

    private static <T extends Comparable<? super T>> void quickSort(List<T> array, int start, int arrayLength){
        if(start < arrayLength){
            int q = partition(array, start, arrayLength);
            quickSort(array, start, q);
            quickSort(array, q+1, arrayLength);
        }
    }

    private static <T extends Comparable<? super T>> int partition(List<T> array, int end, int arrayLength){
        T last = array.get(arrayLength-1);
        int i = end-1;
        for(int j = end; j < arrayLength-1; j++){
            if(array.get(j).compareTo(last) <= -1 || array.get(j).compareTo(last) == 0){
                i = i+1;
                exchange(j, i, array);
            }
        }
        exchange(arrayLength-1, i+1, array);
        return i + 1;
    }

    private static <T extends Comparable<? super T>> void exchange(int j, int i, List<T> array){
        T temp = array.get(j);
        array.set(j, array.get(i));
        array.set(i, temp);
    }
}

Naming
QuickSort is not a simple algorithm, and naming things helps to make it more readable. Unfortunately, with descriptive names, if you name things wrong it makes it worse than if you you use cryptic names. Your recursive method is:

private static <T extends Comparable<? super T>> void quickSort(List<T> array, int start, int arrayLength){
    if(start < arrayLength){
        int q = partition(array, start, arrayLength);
        quickSort(array, start, q);
        quickSort(array, q+1, arrayLength);
    }
}

But, arrayLength does not mean array length, it means "end-exclusive", or "ignore-from" or something.
One of the common tricks in the quickSort is to use the actual index of the last element in the partition, instead of the length. For example, you call the method with:

quickSort(list, 0, list.size());

But, what if you called it with:
quickSort(list, 0, list.size() - 1);

Then named your parameters:
    private static <T extends Comparable<? super T>> void quickSort(
            List<T> array, int start, int end) {

Now you have start and end, and you do not need to do the immediate offset adjustment in the partition method.
Now, with that simple adjustment, the code becomes more readable simply because the variables do what they say, and don't lie to you.
Exchange
Your exchange method is good, no major problems there (with some caveats though... we will get to those...)
exchange is a decent name, but convention would call it swap...., give it decent index names, and common convention would be to put the indices after the reference:
private static <T extends Comparable<? super T>> void exchange(
        List<T> array, int left, int right) ....

Partitioning
Note, your current partition method is:

private static <T extends Comparable<? super T>> int partition(List<T> array, int end, int arrayLength){
    T last = array.get(arrayLength-1);
    int i = end-1;
    for(int j = end; j < arrayLength-1; j++){
        if(array.get(j).compareTo(last) <= -1 || array.get(j).compareTo(last) == 0){
            i = i+1;
            exchange(j, i, array);
        }
    }
    exchange(arrayLength-1, i+1, array);
    return i + 1;
}

Notice what happens if we give it decent variable names, and use the 'end' instead of the arrayLength
private static <T extends Comparable<? super T>> int partition(
        List<T> array, int first, int last) {
    T key = array.get(last);
    int smaller = first - 1;
    for (int test = first; test < last; test++) {
        if (array.get(test).compareTo(key) <= 0) {
            smaller++;
            exchange(smaller, test, array);
        }
    }
    smaller++;
    exchange(last, smaller, array);
    return smaller;
}

For a start, notice the condition:

if (array.get(test).compareTo(key) <= -1
        || array.get(test).compareTo(key) == 0) {

can be reduced to just:
if (array.get(test).compareTo(key) <= 0) {

All values up to smaller are smaller or equal to key.
Your code makes some sense to me now.
Note, the algorithm you use to partition the data is a little unconventional... though I can't see a real problem with it.
A conventional approach would have a left and right index that progress from the ends, and then swap values from each side, and meet in the middle somewhere. Your approach is OK, though.
Putting it together
With these changes, putting it all together, you will need to change the calling routines:
public static <T extends Comparable<? super T>> void sort(List<T> list) {
    quickSort(list, 0, list.size() - 1);
}

private static <T extends Comparable<? super T>> void quickSort(List<T> array, int left, int right){
    if(left  >= right) {
        return;
    }

    int q = partition(array, left, right);
    quickSort(array, left, q - 1);
    quickSort(array, q + 1, right);
}

private static <T extends Comparable<? super T>> int partition(
        List<T> array, int first, int last) {
    T key = array.get(last);
    int smaller = first - 1;
    for (int test = first; test < last; test++) {
        if (array.get(test).compareTo(key) <= 0) {
            smaller++;
            exchange(smaller, test, array);
        }
    }
    smaller++;
    exchange(last, smaller, array);
    return smaller;
}

private static <T extends Comparable<? super T>> void exchange(int j,
        int i, List<T> array) {
    T temp = array.get(j);
    array.set(j, array.get(i));
    array.set(i, temp);
}

public static void main(String[] args) {
    List<String> data = new ArrayList<String>(System.getProperties().stringPropertyNames());
    sort(data);
    for (String d : data) {
        System.out.println(d);
    }
}

Foot Notes
Note that your code has horrible performance on List instances that are not random-access... Consider someone who feeds your code a LinkedList... it will perform badly because each time you get or set with an index, it has to scan the data for the value.
RandomAccess is an interface available on collections that support fast and easy index-based access.
The Java implementation solves sorting non-RandomAccess Lists by dumping all the data in to a different RandomAccess list, sorting that, and then copying it back again, something like:
if (list instanceof RandomAccess) {
    sort(list);
} else {
    List<T> toSort = new ArrayList<>(list);
    sort(toSort);
    list.clear();
    list.addAll(toSort);
}


function access variable in module.exports file in nodeJs I would like to find the best way to access function variables that are being used as parameters in other functions in another module. The parsefile.js is a Node.js script that is exported as package module and two functions. getfirst and getsecond need to access the variables that are passed from index.js like 'a', 'b' from  parsefile('a', 'b', 'c'). Other than using global, do we have another way to do it?
// index.js from some application
const parsefile = require('./parsefile')
parsefile('a', 'b', 'c')

//parsefile.js exports about package module
function getfirst() {
  if (global.f && global.s) {
    return `i have totally 2 arguments: ${global.f}///${global.s}`
  }
  return `first arguments is ${global.f}`
}

function getsecond() {
  return `second arguments is ${global.s}`
}

module.exports = (...args) => {
  global.f = args[0];
  global.s = args[1];
  Promise.all([getfirst(), getsecond()]).then(([first, second]) => {
    console.log(`return from getfirst: ${first}`);
    console.log(`return from getsecond: ${second}`);
  });
}

Since getfirst() and getsecond() are called only within parsefile.js, you can just define an object inside this file (something like this const local = {} at the top of your file) and use it instead of global.


splitting multiple joined words, port from perl to PHP Though i have never worked on perl, not even once.
I have ported the perl code into PHP and it seems like giving a correct result. But as I am going to use it on production server.

I want this code to get it reviewed, please let me know if there is any problem in the porting from perl to PHP.

#!/usr/bin/perl

use strict;

my $WORD_FILE = '/usr/share/dict/words'; #Change as needed
my %words; # Hash of words in dictionary

# Open dictionary, load words into hash
open(WORDS, $WORD_FILE) or die "Failed to open dictionary: $!\n";
while (<WORDS>) {
  chomp;
  $words{lc($_)} = 1;
}
close(WORDS);

# Read one line at a time from stdin, break into words
while (<>) {
  chomp;
  my @words;
  find_words(lc($_));
}

sub find_words {
  # Print every way $string can be parsed into whole words
  my $string = shift;
  my @words = @_;
  my $length = length $string;

  foreach my $i ( 1 .. $length ) {
    my $word = substr $string, 0, $i;
    my $remainder = substr $string, $i, $length - $i;
    # Some dictionaries contain each letter as a word
    next if ($i == 1 && ($word ne "a" && $word ne "i"));

    if (defined($words{$word})) {
      push @words, $word;
      if ($remainder eq "") {
        print join(' ', @words), "\n";
        return;
      } else {
        find_words($remainder, @words);
      }
      pop @words;
    }
  }

  return;
}

The PHP code which I want a review on:

<?php

$WORD_FILE = file_get_contents ("word.txt") ;

$temp_arr = explode("\n", $WORD_FILE);

foreach ($temp_arr as $str)
{
    $words [$str] = 1 ;
}

$processed = Array () ;

find_words ($argv[1]) ;
print_r ($processed) ;

function find_words ($str)
{
    global $words ;
    global $processed ;

    $string = $str ;
    $length = strlen ($str) ;

    for ($i = 1 ; $i <= $length + 1; $i++)
    {
        $word = substr ($string, 0, $i) ;
        $remainder = substr ($string, $i, $length - $i) ;

        if ($i == 1 && ($word != "a" && $word != "i")) ;

        if (array_key_exists ($word, $words))
        {
            array_push($processed, $word) ;
            if ($remainder == "")
            {
                return ;
            }
            else
            {
                find_words ($remainder, $words) ;
            }
            echo "popping the word " . array_pop ($words) . "\n";
        }
    }

    return ;
}

?>

This should be find_words() php equivalent,
(note perl %words is here $Gwords as perl makes distinction between hashes/dictionaries and arrays)

function find_words() {
    global $Gwords;

    # Print every way $string can be parsed into whole words
    $words = func_get_args();
    $string = array_shift($words);
    $length = strlen($string);

    foreach (range(1, $length) as $i) {

        $word = substr($string, 0, $i);
        $remainder = substr($string, $i, $length - $i);
        # Some dictionaries contain each letter as a word
        if ($i == 1 && ($word !== "a" && $word !== "i")) continue;

        if (isset($Gwords[$word])) {
            $words[]= $word;
            if ($remainder === "") {
                echo join(' ', $words), "\n";
                return;
            }
            else {
                # find_words($remainder, @words);
                call_user_func_array(
                    "find_words",
                    array_merge((array)$remainder, $words)
                );
            }
            array_pop($words);
        }
    }

    return;
}


Extension method to format properties that are not null and not empty I'm trying to work with the following class, which is inside a library I currently cannot change:

// This class represents "external" code as far as my review
// request is concerned: I cannot change this, currently.
public class AddressDto
{
    public string Name { get; set; }
    public string Zip { get; set; }
    public string City { get; set; }
    public string AddressLine { get; set; }
    public string ExtraInfo { get; set; }
}

I'm writing an extension method with c# 5 and .NET 4.5.1 to represent instances of that class as a string for display purposes. I'm looking to get feedback on the inner workings of this method:

// Looking for feedback on this method:
public static string FormatForGui(this AddressDto Address)
{
    if (Address == null) throw new ArgumentNullException("Address");

    var parts = new[]
    {
        Address.Name,
        Address.AddressLine,
        Address.Zip,
        Address.City
    };

    return string.Join(" ", parts.Where(s => !String.IsNullOrEmpty(s)));
}

Can this method body be improved?

For your convenience, here's a condensed NUnit unit test to define the behavior:

// Not necessarily looking for feedback on these tests, my actual tests are more DAMP
// but for brevity I condensed them into one test:
[Test]
public void AllTests()
{
    Assert.Throws<ArgumentNullException>(() => ((AddressDto)null).FormatForGui());
    Assert.That(new AddressDto { }.FormatForGui(), Is.EqualTo(""));
    Assert.That(new AddressDto { Name = "" }.FormatForGui(), Is.EqualTo(""));
    Assert.That(new AddressDto { Name = "A" }.FormatForGui(), Is.EqualTo("A"));
    Assert.That(new AddressDto { Name = "A", AddressLine = "B" }.FormatForGui(), Is.EqualTo("A B"));
    Assert.That(new AddressDto { Name = "A", AddressLine = "B", Zip = "C" }.FormatForGui(), Is.EqualTo("A B C"));
    Assert.That(new AddressDto { Name = "A", AddressLine = "B", Zip = "C", City = "D" }.FormatForGui(), Is.EqualTo("A B C D"));
    Assert.That(new AddressDto { Name = "A", AddressLine = "B", City = "D" }.FormatForGui(), Is.EqualTo("A B D"));
}

You're asking for a review of a tiny amount of decent code, so there is not much to say.

return string.Join(" ", parts.Where(s => !String.IsNullOrEmpty(s)));

You're first using string and then String to call a static method. You should be consistent in which one you use.

throw new ArgumentNullException("Address");

If you're using C# 6.0, you could use nameof here:

throw new ArgumentNullException(nameof(Address));

(And Heslacher already mentioned in a comment that it should be address.)

Assert.That(new AddressDto { }.FormatForGui(), Is.EqualTo(""));

I think that Assert.AreEqual() is better, mostly since it's slightly shorter and doesn't use the weird Is pattern:

Assert.AreEqual("", new AddressDto { }.FormatForGui());


Making grandchild of root null , the right way in C++ I am trying to create a multiway tree with the following code in C++. As of now, it is more like a sample piece of code.

I wish to do the following with this piece of code(and I am able to get the desired result):

Create a struct Node of two members : value(of the node) and array of children of the node.
Make 'root's value = 5
Make the children's values equal to 10,20,30 & 40
Make the children of children's values equal to null(=0);

I am getting the desired output , but what I want to know is if I am doing it the right way.

Thanks, in advance.

//multinode tree
#include<iostream>
#define null 0

struct Node
{
    int value;
    Node *child[4];
};

void display(Node *root){
    if(root==null)
        return;
    else{

        std::cout<<root->value<<" ";
        if(root->child[0]!=null)
            for (int i=0;i<4;i++)
            {
                if(root->child[i]!=null)
                    display(root->child[i]);

            }
    }
}

int main()
{
    Node *root=new Node;
    Node *test=null;
    root->value=5;
    int values[]={10,20,30,40};
    int i=0;
    for (i=0;i<4;i++)
    {
        Node *temp=new Node;
        temp->value=values[i];
        root->child[i]=temp;
        for (int j=0;j<4;j++)
        {
            root->child[i]->child[j]=null;
        }
        std::cout<<"Root value "<<root->child[i]->value<<"\n\n ";
    }
    std::cout<<"\n\n\n\n\n";
    display(root);

}

This is a very C like approach and you are using C++ so take advantage of that fact.

Get rid of the #define and use nullptr keyword instead.
Name member variables something special such as m_ so Node *m_children[4];
Try use C++ data structures instead of arrays and char* so vector<Node*> children.
Make the Node struct into a class and write getters and setters to encapsulate the new vector structure you should use.
Encapsulate the void display(Node *root) function into a class such:

class Tree
{
    Tree(int depth);// create a tree with x depth
    etc...
    void display();
public:
    Node* m_root;
};

You could create some functionality to able to initialise the tree with some custom data structure.
Add the following code in main into the tree class

for (i=0;i<4;i++)
{
    Node *temp=new Node;
    temp->value=values[i];
    root->child[i]=temp;
    for (int j=0;j<4;j++)
    {
        root->child[i]->child[j]=null;
    }
    std::cout<<"Root value "<<root->child[i]->value<<"\n\n ";
}

PS. Sorry if the code doesn't work; I'm at work and have no way to check it!


ArXiV Technical Paper API Github Repo My name is Ethan and I am trying to build an API for scaping technical papers to use for developers. Right now it only works for ArXiV but I would greatly appreciate some mentoring or a code review of my repo. I am a new developer and want to get my code to professional quality.

Repo: https://github.com/evader110/ArXivPully

Source provided as well:

from falcon import API
from urllib import request
from bs4 import BeautifulSoup

class ArXivPully:
    # Removes rogue newline characters from the title and abstract
    def cleanText(self,text):
        return ' '.join(text.split('\n'))

    def pullFromArXiv(self,search_query, num_results=10):
        # Fix Input if it has spaces in it
        split_query = search_query.split(' ')
        if(len(split_query) > 1):
            search_query = '%20'.join(split_query)
        url = 'https://export.arxiv.org/api/query?search_query=all:'+search_query+'&start=0&max_results='+str(num_results)
        data = request.urlopen(url).read()
        output = []
        soup = BeautifulSoup(data, 'html.parser')
        titles = soup.find_all('title')

        # ArXiv populates the first title value as the search query
        titles.pop(0)

        bodies = soup.find_all('summary')
        links = soup.find_all('link', title='pdf')
        for i in range(len(titles)):
            title = self.cleanText(titles[i].text.strip())
            body = self.cleanText(bodies[i].text.strip())
            pdf_link = links[i]['href']
            output.append([pdf_link, title, body])
        return output

    def on_get(self, req, resp):
        """Handles GET requests"""
        output = []
        for item in req.params.items():
            output.append(self.pullFromArXiv(item[0],item[1]))
        resp.media = output

api = API()
api.add_route('/api/query', ArXivPully())

Some design explanations. I run this API through Google Cloud Platform using Falcon API because both options are free for me and were the simplest to implement. Some known issues are already posted in the repo but I want to better understand Software Development skills, best practices, etc. I greatly appreciate any tips big or small and I look forward to drastically changing this source code to make it more robust.

Python has an official style-guide, PEP8. It recommends using lower_case for variables, functions and methods.
I would encourage you to use requests.get instead of urllib.request. It can take care of urlencoding the parameters for you.
You can make pull_from_arxiv a generator to save a few lines.
BeautifulSoup can be sped up using the lxml parser.
on_get can be simplified a bit using a list comprehension.
Not sure if your cleanText is really needed. Anyways, I would use str.replace instead of str.split and str.join.

import requests
from bs4 import BeautifulSoup

class ArXivPully:
    def pull_from_arxiv(self, search_query, num_results=10):
        url = "https://export.arxiv.org/api/query"
        params = {"search_query": f"all:{search_query}",
                  "start": 0,
                  "max_results": num_results}
        data = requests.get(url, params=params).text
        soup = BeautifulSoup(data, 'lxml')
        # ArXiv populates the first title value as the search query
        titles = soup.find_all('title')[1:]
        bodies = soup.find_all('summary')
        links = soup.find_all('link', title='pdf')

        for title, body, link in zip(titles, bodies, links):
            yield (link['href'],
                   title.text.strip().replace("\n", " "),
                   body.text.strip().replace("\n", " "))

    def on_get(self, req, resp):
        """Handles GET requests"""
        resp.media = [list(self.pull_from_arxiv(*item))
                      for item in req.params.items()]

Side note: Using this returns completely different results compared to entering the search string on the arxiv website search field. Not sure why. Same is true for your queries, though (the only difference is that  gets encoded as + and : as %3a by requests.get).


Simple parenthesis removal - JavaScript I solved the following problem:

You will be given a mathematical string and your task will be to remove all braces as follows:
solve("x-(y+z)") = "x-y-z"`

solve("x-(y-z)") = "x-y+z"`

solve("u-(v-w-(x+y))-z") = "u-v+w+x+y-z"`

solve("x-(-y-z)") = "x+y+z"`

There are no spaces in the expression. Only two operators are given: "+" or "-".

This is the solution I came up with:
function removeAt(s, index) {
    if (index === s.length - 1) {
        return s.slice(0, -1)
    }
    return s.slice(0, index) + s.slice(index + 1);
}

function insertAt(s, index, str) {
    return s.slice(0, index) + str + s.slice(index);
}

function replaceAt(s, index, chr) {
    if (index > s.length - 1) return s;
    return s.slice(0, index) + chr + s.slice(index + 1);
}

function reverseSigns(s, start, end) {
    for (var i = start; i < end; i++) {
        if (s[i] === '-') {
            s = replaceAt(s, i, '+');
        } else if (s[i] === '+') {
            s = replaceAt(s, i, '-');
        }
    }
    return s;
}

function solve(s) {
    //Get the position of the parenthesis
    var Close = 0, Open = -1;
    while (s[Close] !== ')' && Close < s.length) {
        if (s[Close] === '(') {
            Open = Close;
        }
        Close++;
    }
    //Check to see if there is any parenthesis
    if (Open !== -1) {
        //Insert sign before if there is none
        if (s[Open + 1] !== '+' && s[Open + 1] !== '-') {
            s = insertAt(s, Open + 1, '+');
            //'Close' parenthesis has changed --> +1 right
            Close++;
        }
        //Check to see if a sign has to be replaced
        if (s[Open - 1] === '-') {
            s = reverseSigns(s, Open + 1, Close - 1);
        }
        //Remove the parenthesis
        s = removeAt(s, Close);
        s = removeAt(s, Open);
        //Remove the sign before paranthesis
        if (s[Open - 1] === '-' || s[Open - 1] === '+') {
            s = removeAt(s, Open - 1);
        }
        //Recursive call
        return solve(s);
        //return s;
    }
    //Remove unnecessary +
    if (s[0] === '+') {
        s = removeAt(s, 0);
    }
    return s;
}

I was wondering if my code could be improved.

I would do this by iterating through the tokens and keeping a stack of the current state (signStack) as parenthesis are opened.

function newSign(current, prev) {
  //treat blank as positive
  const currentNegative = current[0] == '-';
  const prevNegative    = prev[0]    == '-';
  return currentNegative == prevNegative ? '+' : '-';
}

function solve(input) {
  let signStack   = ['+']; // start by assuming positive
  let currentSign = '';

  const result = input.replace(/(\+|\-)\(?|\)|\w/g, (match) => {
    if (match==')') { // close parenthesis
      signStack.shift();
      currentSign = signStack[0];
      return '';
    }

    if (match[0] != '+' && match[0] != '-') { // variable
      const  sign = currentSign;
      currentSign = signStack[0];;
      return sign + match;
    }

    const sign     = newSign(match, currentSign);
    currentSign    = sign;
    if (match.length > 1) {// open parenthesis
      signStack.unshift(sign);
    }
    return '';
  });

  if (signStack.length != 1)
    throw 'unbalanced parenthesis';

  return result;
}

function test(input, expected) {
  const result = solve(input);
  if (result != expected)
    console.log(`Failed: input=${input}, result=${result}, expected=${expected}`);
}

test("x-(y+z)",        "x-y-z");
test("x-(y-z)",        "x-y+z");
test("u-(v-w-(x+y))-z", "u-v+w+x+y-z");
test("x-(-y-z)",        "x+y+z");


Finding the index of the character whose removal will make a palindrome Before I get into describing by problem I'd like to point out I found this question under c++ tag. But the solution of that question is already implemented in my code.
I am solving a problem from hackerrank. My code for that problem is logically correct but in some of the cases time limit exceeds.

Problem Statement
Given a string S , of lowercase letters, determine the index of the character whose removal will make a S palindrome. If is already a palindrome or no such character exists, then print -1 . There will always be a valid solution, and any correct answer is acceptable. For example, if S = "bcbc", we can either remove 'b' at index 0 or 'c' at index 3.
Input Format:
The first line contains an integer T , denoting the number of test cases.
Each line i of the T subsequent lines describes a test case in the form of a single string, Si.
Constraints:
Length of the string can be 100005.
Output Format:
Print an integer denoting the zero-indexed position of the character that makes S not a palindrome; if S is already a palindrome or no such character exists, print -1 .

As a solution my code is as following:
import java.io.*;
import java.util.*;

public class Solution {

public static boolean isPalindrom(String s){
    int n = s.length();
    for (int i=0;i<(n / 2);++i) {
        if (s.charAt(i) != s.charAt(n - i - 1)) {
         return false;
        }
    }

    return true;
}

public static void main(String[] args) throws IOException{
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    int t = Integer.parseInt(br.readLine());
    while(t-->0){
        int flag = 0;
        String sb = br.readLine().toString();
        if(isPalindrom(sb)){
            System.out.println("-1");
            flag = 1;
        }
        for(int i=0;i<sb.length()&&flag==0;i++){
            StringBuffer s = new StringBuffer(sb);
            s.deleteCharAt(i);
            if(isPalindrom(s.toString())){
                System.out.println(i);
                break;
            }
        }

    }
}}

I've used best palindrome checker algorithm as described here. and also used BufferedReader as described here. But time limit exceeds in some taste cases. How can I improve my code further?
Thanks in advance!

Code Style

As @coderodde also remarked, you should import specific classes.  Wildcard imports are for throw-away code and early development; no later than when your code is approaching completeness, you should replace any then-remaining wildcard imports with specific imports.  There are tools that can help you with that.

Also, format your code consistently.  Your indentation and placement of spaces are irregular.  I find code much easier to read when there are spaces on each side of every binary operator, but if you prefer not to use such spaces then at least be consistent!

I/O

For what it's worth, unlike @coderodde, I have no problem with BufferedReader for your input.  For input whose form is so simple, Scanner does not provide much advantage.

Performance

This is the main area of concern, and indeed I do not find it surprising that your code ...

        for(int i=0;i<sb.length()&&flag==0;i++){
            StringBuffer s = new StringBuffer(sb);
            s.deleteCharAt(i);
            if(isPalindrom(s.toString())){
                System.out.println(i);
                break;
            }
        }

... does not perform well.  Regardless of the details of the palindrome-checking algorithm, it is performing far more work than it needs to do when used this way.  In particular, it is very wasteful to test every deletion candidate, and it is slightly wasteful to test separately whether the full string is already a palindrome.  For each string it tests, your code may perform work proportional to the square of the length of the string.

Instead of testing every possible deletion, simply scan each test string from both ends until you find a pair of corresponding characters that differ.  If the string can be made a palindrome by deleting a single character, then that character will be one of those two.  They are the only candidates you need to consider.  By limiting yourself to considering only those as deletion candidates, the maximum amount work performed by your code is only linear in the length of the string.  (Also, if every corresponding pair of characters matches, then the string is already a palindrome, so you don't need to perform a separate check for that.)


Find all local maxima in a one-dimensional array I implemented the following class (it works) and I just want to hear your opinions about best practices and what can be improved. The idea was to do it using mostly arrays.

The class just finds the peak elements in an array with respect to their neighbors. The first element and the last element are ignored.

Example: {3, 15, 5, 20, 10}
Answer:  {15, 20}

package findpeak;

import java.util.ArrayList;
import java.util.List;

public class ArrayPeak
{
    private final int[] ARRAY;
    private final int LEN;
    private static final int IGNORE_FIRST_POSITION = 0;
    private final int IGNORE_LAST_POSITION;

    public ArrayPeak(int[] array)
    {
        this.ARRAY = array;
        this.LEN = this.ARRAY.length;
        this.IGNORE_LAST_POSITION = this.LEN - 1;
    }

    public List<Integer> findPeaks()
    {
        List<Integer> peaks = new ArrayList<>();
        for (int position = 0; position < LEN; position++)
        {
            int output = 0;
            if (position != IGNORE_FIRST_POSITION && position != IGNORE_LAST_POSITION)
            {
                int[] trippleArray =
                {
                    ARRAY[position - 1], ARRAY[position], ARRAY[position + 1]
                };
                output = checkPeak(trippleArray);
            }
            peaks.add(output);
        }

        return filterZeros(peaks);
    }

    private static int checkPeak(int[] inputArray)
    {
        int peak = 0;
        if (inputArray[1] > inputArray[0] && inputArray[1] > inputArray[2])
        {
            peak = inputArray[1];
        }
        return peak;
    }

    private static List<Integer> filterZeros(List<Integer> list)
    {
        List<Integer> filteredList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++)
        {
            if (list.get(i) != 0)
            {
                filteredList.add(list.get(i));
            }
        }
        return filteredList;
    }
}

This shouldn't involve an instance of a class: you can (and should) implement this as a standalone static method, which takes the input array as a parameter and returns the peaks. Introducing a class to record the state is just introducing complexity which will make the code harder to maintain without providing any benefit.

I would also like some documentation explaining exactly what the method does: for example, it doesn't return non-positive peaks, and (as Toby Speight's comment indicates) some might thing it would return plateaus. Basically you need a better specification, and that needs to appear as documentation, so that the intention of the code is completely unambiguous (for the benefit of the implementer, maintainer, and consumer). I would not expect a method like this to return the heights of peaks, rather than their position.

IGNORE_FIRST_POSITION sounds like the name of a boolean, not an int. You'd be better off, I think, changing the for loop to start at 1, end at array.Length - 1, and include a comment explaining why this is the case.

I like that CheckPeak is its own method because it puts the corresponding logic 'all in one place', but I don't like that you are creating a new array every time you check for a peak: I would much prefer you pass the array and candidate position as parameters, and it checks 'in-place'. This is a simpler API (the current one lacks any specification that it takes an array of three parameters), and will reduce the overhead from calling the method.

I also don't like that it returns the height of the peak, rather than whether or not a peak appears: this too is lacking documentation (though granted it is private, so it isn't as important as the public method). Much better to return true or false if it is a peak, then add the peak to the list of peaks if it returns true, otherwise do not (then you can remote the confusing filterZeros at the end).

This can also remove the unpleased output variable, which is defined too early. It only has meaning once it is assigned, and if it isn't assigned it just has a default value you will filter anyway, so you might as well declare and assign it in one.

Really tiny thing that is almost completely subjective: I'd prefer to write

if (inputArray[1] > inputArray[0] && inputArray[1] > inputArray[2])

as

if (inputArray[0] < inputArray[1] && inputArray[1] > inputArray[2])

It keeps them 'in order, and makes it a little easier to feel what is going on.

Your code only works with Integers: if I wanted to find peaks in a Double[], I would need to write a new class. You might want to make it generic on a type T that implements Comparable<T>. This can create some confusion with floating point types (i.e. NaNs), but by depending on a basic interface, your code will be reusable and harder to 'get wrong'.

You might also consider taking an abstract collection as a parameter; it's good that you return List<T> rathern than ArrayList<T>.

Example rewrite (disclaimer: untested, and I don't know Java, and I'm running out of time...):

public class ArrayPeak
{
    public static <T extends Comparable<T>> List<T> findPeaks(T[] array)
    {
        List<T> peaks = new ArrayList<>();

        // ignore first and last elements
        for (int position = 1; position < array.length - 1; position++)
        {
            if (checkPeak(array, position)
            {
                peaks.add(array[position]);
            }
        }

        return peaks;
    }

    private static <T extends Comparable<T>> int checkPeak(T[] array, int position)
    {
        if (inputArray[position - 1].compareTo(inputArray[position]) < 0 && inputArray[position].compareTo(inputArray[position + 1]) > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


Web crawler that filters out non diseases It is very messy and I lack the experience to make it eloquent so I wanted some help with it. The process time is also very slow.

Currently it goes into the first page and goes through the links in the index looking for the word "symptoms." If its not found it will look for a link inside that link named "faqs" and go to that link and look for 'symptoms'.

import requests
import string
from bs4 import BeautifulSoup, Tag
alpha = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'
alpha = alpha.split()
w = []
def disease_spider(maxpages):
    i = 0
    while i <= maxpages:

        url = 'http://www.cdc.gov/DiseasesConditions/az/'+ alpha[i]+'.html'
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)

        for l in soup.findAll('a', {'class':'noLinking'}):
            if l.text != "USA.gov" and l.text != 'Inspector General' and l.text != '':
                href = l.get('href')
                diseasechecker(href)
        i += 1
def diseasechecker(url2):
    source_code = requests.get(url2)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for y in soup.findAll('p'):
        x = str(y)
        txt = y.text
        if 'symptoms' in x and url2 not in w:
            w.append(url2)
        elif 'symptoms' in txt and url2 not in w:
            w.append(url2)
    for y in soup.findAll('li'):
        x = str(y)
        txt = y.text
        if 'symptoms' in x and url2 not in w:
            w.append(url2)
        elif 'symptoms' in txt and url2 not in w:
            w.append(url2)
    for y in soup.findAll('a'):
        href2 = y.get('href')

        try:
            s = str(href2)
            u = "http://www.cdc.gov"+s
        except UnicodeEncodeError:
            pass
        l3 = 0
        if 'faqs' in s:
            l3 = level3(u)
        if l3 == 1 and url2 not in w:
            w.append(url2)
def level3(url3):
    source_code = requests.get(url3)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for y in soup.findAll('p'):
        x = str(y)
        txt = y.text
        if 'symptoms' in x:
            return 1
        elif 'symptoms' in txt:
            return 1

disease_spider(0)
for i in range(len(w)):
    print w[i]

Here are some suggestions:

More comments and docstrings would be nice, so the reader/reviewer can see what you intend the code to do (why was the code written this way?). It makes it easier to follow, because your intention is clear, and also then I can spot bugs where the implementation doesn't match the indentation.
Add more whitespace! Particularly vertically; breaking up the functions with newlines will make it substantially easier to read/
At the top of the file, you construct a list of lowercase letters alpha. You’ve also imported, but not used, the string module. It would be better to use string.ascii_lowercase, which works as follows:

  string.ascii_lowercase

  The lowercase letters 'abcdefghijklmnopqrstuvwxyz'. This value is not locale-dependent and will not change.

Then you can get rid of the alpha variable, and just use this.
disease_spider()

You should use a for loop rather than a while loop:

for i in range(maxpages):
    # do some stuff

Rather than constructing the request URL using string concatenation, use new-style format strings:

url = 'http://www.cdc.gov/DiseasesConditions/az/{}.html'.format(
    string.lowercase[i]
)

I’m guessing that this function goes through the pages from A to Z, yes? But there’s no guard against the user calling this function with maxpages ≥ 26, which would throw an IndexError here. You should add some sort of check.

Use a better variable name than l in your soup.findAll loop. How about link?

Then I’d have a list of forbidden names, and just check than link.text isn’t in that list. For example:

forbidden_text = ['USA.gov', 'Inspector General', '']
if link.text not in forbidden_text:
    # do some more stuff

diseasechecker()

I noticed when reading this function that you use this block of code in all three functions:

source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)

You should consider pulling this out into its own function, that takes a URL and returns the corresponding BeautifulSoup object. It would slightly tidy up the code.

The variable names in this function are all short and undescriptive; pick something that tells me what the value of this variable represents.

This function mutates a global list w, although it’s the only function to do so. I think it would be better if you moved the definition of w inside this function, and returned it at the end. That makes the function more self-contained.

You loop over all p and li elements separately, but do the same thing with each. Why not combine the loops, so you only have to write out the body of the loop once:

for element in soup.findAll('p') + soup.findAll('li'):
     # do some stuff with elements

I believe you can also tidy up the if statement:

if (url2 not in w) and ('symptoms' in str(y) or 'symptoms' in y.text):
    w.append(url2)

The parens aren’t strictly necessary, but I think they’re useful here for readability. I also got rid of the x and txt variables, which I don’t think aid readability. This is more direct.
level3()

Again, pick some better variable names that x and y.

And you can tidy up the if statement:

if 'symptoms' in str(y) or 'symptoms' in y.text:
    return 1

In the final loop, you’re looping over the index:

for i in range(len(w)):
    print w[i]

It is far cleaner and more Pythonic to loop over the list directly; i.e.,

for word in w:
    print word


JSON for one column of a csv file? I wrote this to pull one column of data from a csv file, divide each of the results in 2, and then format it as JSON so I can do stuff with it in a web app.  It works, but it feels wonky and weird.  Is there a better way to do this?

$fname = "subjects.csv";

$half = array();
$otherkeys = array();
$records = array();

if (($handle = fopen($fname, "r")) === FALSE) {
    exit;
}

/* First line is header with keys */
$keys = fgetcsv($handle);

echo '[';  //added the '['. here to get a propoerly formatted JSON response, not sure why I needed to but I did
while (($data = fgetcsv($handle)) !== FALSE) {
    $half[] = ''.$data[0]/2;    //added the ''. here to get a propoerly formatted JSON response, not sure why I needed to but I did
    $otherkeys[] = $keys[0];
    $records = array_combine($otherkeys, $half);
    $response = json_encode($records);
    echo $response;
}
fclose($handle);
echo ']';  //added the ']'. here to get a properly formatted JSON response, not sure why I needed to but I did

Any thoughts are much appreciated.

The reason you needed the '[' and ']' was to put the array around the records.  A better way of doing it is building the array of records in php and then encoding that.  Here is what I would do:

$fname = "subjects.csv";

if (($handle = fopen($fname, "r")) === FALSE) {
    exit;
}

$records = array();

/* First line is header with keys */
$keys = fgetcsv($handle);

while (($data = fgetcsv($handle)) !== FALSE) {
   $data[0] /= 2;
   $records[] = array_combine($keys, $data);
}

fclose($handle);

echo json_encode($records);


Is there a method to add multiple properties to HtmlTextWriterStyle? I am creating new elements for a webpage at run-time and I have code like this:

      var dynDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("Div") {ID = "dynDiv"};
      dynDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Red");
      dynDiv.Style.Add(HtmlTextWriterStyle.Position, "absolute; left: 500px; top: 500px");
      dynDiv.Style.Add(HtmlTextWriterStyle.Height, "30px");
      dynDiv.Style.Add(HtmlTextWriterStyle.Width, "300px");
      dynDiv.InnerHtml = "New Object";
      PlaceHolder1.Controls.Add(dynDiv);

Is there a shorthand method to adding these value? I.e. something like:

dynDiv.Style.Add(HtmlTextWriterStyle {BackgroundColor = "Red", Position = "absolute; left: 500px; top: 500px", Height = "30px", Width="300px"});

Or any other easier way that anyone can suggest?

Under normal circumstances, you could use collection initializer to write your code this way:

var dynDiv = new HtmlGenericControl("Div")
{
    ID = "dynDiv",
    Style =
    {
        { HtmlTextWriterStyle.BackgroundColor, "Red" },
        { HtmlTextWriterStyle.Position, "absolute; left: 500px; top: 500px" },
        { HtmlTextWriterStyle.Height, "30px" },
        { HtmlTextWriterStyle.Width, "300px" }
    },
    InnerHtml = "New Object"
};

Unfortunately, this code won't compile, because CssStyleCollection doesn't implement IEnumerable, which is a requirement for collection initializers.


Comparing long lists of strings for the closest match What's the fastest (quality is important too, but a little less important) way to compare two strings?

I'm looking for the most efficient way to compare two strings. Some of the strings I'm comparing can be over 5000 characters long. I'm comparing a list of about 80 strings with another list of about 200 strings. It takes forever, even when I'm threading it.

I'm using the StringUtils.getLevenshteinDistance(String s, String t) method from Apache Commons. My method follows. Is there a better way to do this?

private void compareMe() {
  List<String> compareStrings = MainController.getInstance().getCompareStrings();
  for (String compare : compareStrings) {
    int levenshteinDistance = StringUtils.getLevenshteinDistance(me, compare, bestScore); //bestScore begins at 999999999 :)
    if (bestScore > levenshteinDistance
          && levenshteinDistance > -1) {
      bestScore = levenshteinDistance; //global variable
      bestString = compare; //global variable
    }
  }
}

Here's a sample of two strings which should have a good score:

String 1:

SELECT
CORP_VENDOR_NAME as "Corporate Vendor Name",
CORP_VENDOR_REF_ID as "Reference ID",
MERCHANT_ID as "Merchant ID",
VENDOR_CITY as "City",
VENDOR_STATE as "State",
VENDOR_ZIP as "Zip",
VENDOR_COUNTRY as "Country",
REMIT_VENDOR_NAME as "Remit Name",
REMIT_VENDOR_REF_ID as " Remit Reference ID",
VENDOR_PRI_UNSPSC_CODE as "Primary UNSPSC"
FROM DSS_FIN_USER.ACQ_VENDOR_DIM
WHERE VENDOR_REFERENCE_ID in
(SELECT distinct CORP_VENDOR_REF_ID
FROM DSS_FIN_USER.ACQ_VENDOR_DIM
WHERE CORP_VENDOR_REF_ID = '${request.corp_vendor_id};')

String 2:

SELECT
CORP_VENDOR_NAME as "Corporate Vendor Name",
CORP_VENDOR_REF_ID as "Reference ID",
MERCHANT_ID as "Merchant ID",
VENDOR_CITY as "City",
VENDOR_STATE as "State",
VENDOR_ZIP as "Zip",
VENDOR_COUNTRY as "Country",
REMIT_VENDOR_NAME as "Remit Name",
REMIT_VENDOR_REF_ID as " Remit Reference ID",
VENDOR_PRI_UNSPSC_CODE as "Primary UNSPSC"
FROM DSS_FIN_USER.ACQ_VENDOR_DIM
WHERE VENDOR_REFERENCE_ID in
(SELECT distinct CORP_VENDOR_REF_ID
FROM DSS_FIN_USER.ACQ_VENDOR_DIM
WHERE CORP_VENDOR_REF_ID = 'ACQ-169013')

You'll notice the only difference is the '${request.corp_vendor_id};' at the end of the string. This would cause it to have a score of 26.

The painless solutiuon is to use the fastest levenstein distance algorithm :) For example extracted from GWT! I've created two 5 KB strings using your example, load them and produce 16000 calculations. Done in 3 seconds only. The source:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {

private static String readString(String filename) throws IOException {
    StringBuilder result = new StringBuilder();
    String temp;
    BufferedReader in = new BufferedReader(new FileReader(filename));
    while ((temp = in.readLine()) != null) result.append(temp);
    return result.toString();
}

public static void main(String[] args) throws IOException {

    String line1 = readString(args[0]);
    String line2 = readString(args[1]);
    GeneralEditDistance ed = GeneralEditDistances.getLevenshteinDistance(line1);

    long time = System.currentTimeMillis();
    int best = Integer.MAX_VALUE;
    for (int i = 0; i < 80*200; i++) {
        best = Math.min(best, ed.getDistance(line2, best));
    }
    System.out.println("Best distance = " + best + " Total time (ms): " + (System.currentTimeMillis() - time));
}}

abstract class CharIndex {

static class FullHash extends CharIndex {

    static class Char {
        char c;

        @Override
        public boolean equals(Object x) {
            return (x != null) && (((Char) x).c == this.c);
        }

        @Override
        public int hashCode() {
            return c;
        }

        @Override
        public String toString() {
            return "'" + c + "'";
        }
    }

    static final int NULL_ELEMENT = 0;
    protected int lastUsed = NULL_ELEMENT;
    final java.util.HashMap<Char, Integer> map;

    FullHash(CharSequence s) {
        int len = s.length();
        int power = Integer.highestOneBit(len);

        map = new java.util.HashMap<Char, Integer>(
                power << ((power == len) ? 1 : 2));

        Char test = new Char();                   /* (re)used for lookup */
        for (int i = 0; i < s.length(); i++) {
            test.c = s.charAt(i);
            if (map.get(test) == null) {
                map.put(test, new Integer(++lastUsed));
                test = new Char();
            }
        }
    }

    @Override
    public int lookup(char c) {
        final Char lookupTest = new Char();
        lookupTest.c = c;
        Integer result = map.get(lookupTest);
        return (result != null) ? result.intValue() : 0;
    }

    @Override
    public int[] map(CharSequence s, int[] mapped) {
        /* Create one mutable Char, and reuse it for all lookups */
        final Char lookupTest = new Char();

        int len = s.length();
        if (mapped.length < len) {
            mapped = new int[len];
        }

        for (int i = 0; i < len; i++) {
            lookupTest.c = s.charAt(i);
            Integer result = map.get(lookupTest);
            mapped[i] = (result != null) ? result.intValue() : NULL_ELEMENT;
        }
        return mapped;
    }

    @Override
    public int nullElement() {
        return NULL_ELEMENT;
    }

    @Override
    public int size() {
        return lastUsed + 1;
    }
}

static class Masked extends CharIndex {
    static final int SIZE = 0x100;
    static final int MASK = (SIZE - 1);
    static final int NULL_ELEMENT = SIZE;

    static Masked generate(CharSequence s) {
        char[] contains = new char[SIZE];
        contains[0] = (char) 1;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int index = c & MASK;
            if (contains[index] != c) {
                if ((contains[index] & MASK) == index) {
                    return null;
                }
                contains[index] = c;
            }
        }
        return new Masked(contains);
    }

    final char[] contains;

    private Masked(char[] contains) {
        this.contains = contains;
    }

    @Override
    public int lookup(char c) {
        int index = c & MASK;
        return (c == contains[index]) ? index : NULL_ELEMENT;
    }

    @Override
    public int[] map(CharSequence s, int[] mapped) {
        int len = s.length();
        if (mapped.length < len) {
            mapped = new int[len];
        }
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            int index = c & MASK;
            mapped[i] = (c == contains[index]) ? index : NULL_ELEMENT;
        }
        return mapped;
    }

    @Override
    public int nullElement() {
        return NULL_ELEMENT;
    }

    @Override
    public int size() {
        return NULL_ELEMENT + 1;
    }
}

static class Straight extends CharIndex {
    static final int MAX = 0x80;
    static final int MASK = ~(MAX - 1);
    static final int NULL_ELEMENT = MAX;

    static Straight generate(CharSequence s) {
        for (int i = 0; i < s.length(); i++) {
            if ((s.charAt(i) & MASK) != 0) {
                return null;
            }
        }

        return new Straight();
    }

    private Straight() {
    }

    @Override
    public int lookup(char c) {
        return ((c & MASK) == 0) ? c : NULL_ELEMENT;
    }

    @Override
    public int[] map(CharSequence s, int[] mapped) {
        int len = s.length();
        if (mapped.length < len) {
            mapped = new int[len];
        }
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            mapped[i] = ((c & MASK) == 0) ? c : NULL_ELEMENT;
        }
        return mapped;
    }

    @Override
    public int nullElement() {
        return NULL_ELEMENT;
    }

    @Override
    public int size() {
        return NULL_ELEMENT + 1;
    }
}

public static CharIndex getInstance(CharSequence s) {
    CharIndex result;

    if ((result = Straight.generate(s)) != null) {
        return result;
    }

    if ((result = Masked.generate(s)) != null) {
        return result;
    }

    return new FullHash(s);
}

public abstract int lookup(char c);

public abstract int[] map(CharSequence s, int[] mapped);

public abstract int nullElement();

public abstract int size();
}

interface GeneralEditDistance {

GeneralEditDistance duplicate();

int getDistance(CharSequence target, int limit);

}

class GeneralEditDistances {

private static class Levenshtein implements GeneralEditDistance {
    private ModifiedBerghelRoachEditDistance berghel;
    private MyersBitParallelEditDistance myers;
    private final CharSequence pattern;
    private final int patternLength;

    private Levenshtein(CharSequence pattern) {
        this.pattern = pattern;
        this.patternLength = pattern.length();
    }

    public GeneralEditDistance duplicate() {
        Levenshtein dup = new Levenshtein(pattern);
        if (this.myers != null) {
            dup.myers = (MyersBitParallelEditDistance) this.myers.duplicate();
        }
        return dup;
    }

    public int getDistance(CharSequence target, int limit) {
        if (limit <= 1) {
            return limit == 0 ?
                    (pattern.equals(target) ? 0 : 1) :
                    atMostOneError(pattern, target);
        }
        if ((patternLength > 64)
                && (limit < (target.length() / 10))) {
            if (berghel == null) {
                berghel = ModifiedBerghelRoachEditDistance.getInstance(pattern);
            }
            return berghel.getDistance(target, limit);
        }

        if (myers == null) {
            myers = MyersBitParallelEditDistance.getInstance(pattern);
        }

        return myers.getDistance(target, limit);
    }
}

public static int atMostOneError(CharSequence s1, CharSequence s2) {
    int s1Length = s1.length();
    int s2Length = s2.length();
    int errors = 0;             /* running count of edits required */

    switch (s2Length - s1Length) {
        /*
        * Strings are the same length.  No single insert/delete is possible;
        * at most one substitution can be present.
        */
        case 0:
            for (int i = 0; i < s2Length; i++) {
                if ((s2.charAt(i) != s1.charAt(i)) && (errors++ != 0)) {
                    break;
                }
            }
            return errors;

        case 1: /* s2Length > s1Length */
            for (int i = 0; i < s1Length; i++) {
                if (s2.charAt(i) != s1.charAt(i)) {
                    for (; i < s1Length; i++) {
                        if (s2.charAt(i + 1) != s1.charAt(i)) {
                            return 2;
                        }
                    }
                    return 1;
                }
            }
            return 1;

        /* Same as above case, with strings reversed */
        case -1: /* s1Length > s2Length */
            for (int i = 0; i < s2Length; i++) {
                if (s2.charAt(i) != s1.charAt(i)) {
                    for (; i < s2Length; i++) {
                        if (s2.charAt(i) != s1.charAt(i + 1)) {
                            return 2;
                        }
                    }
                    return 1;
                }
            }
            return 1;

        /* Edit distance is at least difference in lengths; more than 1 here. */
        default:
            return 2;
    }
}

public static GeneralEditDistance
getLevenshteinDistance(CharSequence pattern) {
    return new Levenshtein(pattern);
}

private GeneralEditDistances() {
}
}

class ModifiedBerghelRoachEditDistance implements GeneralEditDistance {

private static final int[] EMPTY_INT_ARRAY = new int[0];

public static ModifiedBerghelRoachEditDistance
getInstance(CharSequence pattern) {
    return getInstance(pattern.toString());
}

public static ModifiedBerghelRoachEditDistance
getInstance(String pattern) {
    return new ModifiedBerghelRoachEditDistance(pattern.toCharArray());
}

private int[] currentLeft = EMPTY_INT_ARRAY;

private int[] currentRight = EMPTY_INT_ARRAY;

private int[] lastLeft = EMPTY_INT_ARRAY;

private int[] lastRight = EMPTY_INT_ARRAY;

private final char[] pattern;

private int[] priorLeft = EMPTY_INT_ARRAY;

private int[] priorRight = EMPTY_INT_ARRAY;

private ModifiedBerghelRoachEditDistance(char[] pattern) {
    this.pattern = pattern;
}

public ModifiedBerghelRoachEditDistance duplicate() {
    return new ModifiedBerghelRoachEditDistance(pattern);
}

public int getDistance(CharSequence targetSequence, int limit) {
    final int targetLength = targetSequence.length();

    final int main = pattern.length - targetLength;
    int distance = Math.abs(main);
    if (distance > limit) {
        /* More than we wanted.  Give up right away */
        return Integer.MAX_VALUE;
    }

    final char[] target = new char[targetLength];
    for (int i = 0; i < targetLength; i++) {
        target[i] = targetSequence.charAt(i);
    }
    if (main <= 0) {
        ensureCapacityRight(distance, false);
        for (int j = 0; j <= distance; j++) {
            lastRight[j] = distance - j - 1;  /* Make diagonal -k start in row k */
            priorRight[j] = -1;
        }
    } else {
        ensureCapacityLeft(distance, false);
        for (int j = 0; j <= distance; j++) {
            lastLeft[j] = -1;                 /* Make diagonal +k start in row 0 */
            priorLeft[j] = -1;
        }
    }

    boolean even = true;

    while (true) {

        int offDiagonal = (distance - main) / 2;
        ensureCapacityRight(offDiagonal, true);

        if (even) {
            lastRight[offDiagonal] = -1;
        }

        int immediateRight = -1;
        for (; offDiagonal > 0; offDiagonal--) {
            currentRight[offDiagonal] = immediateRight = computeRow(
                    (main + offDiagonal),
                    (distance - offDiagonal),
                    pattern,
                    target,
                    priorRight[offDiagonal - 1],
                    lastRight[offDiagonal],
                    immediateRight);
        }

        offDiagonal = (distance + main) / 2;
        ensureCapacityLeft(offDiagonal, true);

        if (even) {
            lastLeft[offDiagonal] = (distance - main) / 2 - 1;
        }

        int immediateLeft = even ? -1 : (distance - main) / 2;

        for (; offDiagonal > 0; offDiagonal--) {
            currentLeft[offDiagonal] = immediateLeft = computeRow(
                    (main - offDiagonal),
                    (distance - offDiagonal),
                    pattern, target,
                    immediateLeft,
                    lastLeft[offDiagonal],
                    priorLeft[offDiagonal - 1]);
        }

        int mainRow = computeRow(main, distance, pattern, target,
                immediateLeft, lastLeft[0], immediateRight);

        if ((mainRow == targetLength) || (++distance > limit) || (distance < 0)) {
            break;
        }

        /* The [0] element goes to both sides. */
        currentLeft[0] = currentRight[0] = mainRow;

        /* Rotate rows around for next round: current=>last=>prior (=>current) */
        int[] tmp = priorLeft;
        priorLeft = lastLeft;
        lastLeft = currentLeft;
        currentLeft = priorLeft;

        tmp = priorRight;
        priorRight = lastRight;
        lastRight = currentRight;
        currentRight = tmp;

        /* Update evenness, too */
        even = !even;
    }

    return distance;
}

private int computeRow(int k, int p, char[] a, char[] b,
                       int knownLeft, int knownAbove, int knownRight) {
    assert (Math.abs(k) <= p);
    assert (p >= 0);

    int t;
    if (p == 0) {
        t = 0;
    } else {
        t = Math.max(Math.max(knownAbove, knownRight) + 1, knownLeft);
    }

    int tmax = Math.min(b.length, (a.length - k));

    while ((t < tmax) && b[t] == a[t + k]) {
        t++;
    }

    return t;
}

private void ensureCapacityLeft(int index, boolean copy) {
    if (currentLeft.length <= index) {
        index++;
        priorLeft = resize(priorLeft, index, copy);
        lastLeft = resize(lastLeft, index, copy);
        currentLeft = resize(currentLeft, index, false);
    }
}

private void ensureCapacityRight(int index, boolean copy) {
    if (currentRight.length <= index) {
        index++;
        priorRight = resize(priorRight, index, copy);
        lastRight = resize(lastRight, index, copy);
        currentRight = resize(currentRight, index, false);
    }
}

private int[] resize(int[] array, int size, boolean copy) {
    int[] result = new int[size];
    if (copy) {
        System.arraycopy(array, 0, result, 0, array.length);
    }
    return result;
}
}

abstract class MyersBitParallelEditDistance
    implements GeneralEditDistance, Cloneable {

static class Empty extends MyersBitParallelEditDistance {
    Empty(CharSequence s) {
        super(s);
    }

    @Override
    public GeneralEditDistance duplicate() {
        return this;      /* thread-safe */
    }

    @Override
    public int getDistance(CharSequence s, int k) {
        return s.length();
    }
}

static class Multi extends MyersBitParallelEditDistance {
    int count;
    final int lastBitPosition;
    final int[][] positions;
    int[] verticalNegativesReusable;
    int[] verticalPositivesReusable;
    final int wordMask = (-1 >>> 1);
    final int wordSize = Integer.SIZE - 1;

    Multi(CharSequence s) {
        super(s);
        count = (m + wordSize - 1) / wordSize;
        positions = PatternBitmap.map(s, idx, new int[idx.size()][], wordSize);
        lastBitPosition = (1 << ((m - 1) % wordSize));
        perThreadInit();
    }

    @Override
    public int getDistance(CharSequence s, int k) {
        indices = idx.map(s, indices);

        int[] verticalPositives = verticalPositivesReusable;
        java.util.Arrays.fill(verticalPositives, wordMask);
        int[] verticalNegatives = verticalNegativesReusable;
        java.util.Arrays.fill(verticalNegatives, 0);

        int distance = m;
        int len = s.length();

        int maxMisses = k + len - m;
        if (maxMisses < 0) {
            maxMisses = Integer.MAX_VALUE;
        }

        outer:
        for (int j = 0; j < len; j++) {
            int[] position = positions[indices[j]];

            int sum = 0;
            int horizontalPositiveShift = 1;
            int horizontalNegativeShift = 0;

            for (int i = 0; i < count; i++) {
                int verticalNegative = verticalNegatives[i];
                int patternMatch = (position[i] | verticalNegative);
                int verticalPositive = verticalPositives[i];
                sum = (verticalPositive & patternMatch)
                        + (verticalPositive) + (sum >>> wordSize);
                int diagonalZero = ((sum & wordMask) ^ verticalPositive)
                        | patternMatch;
                int horizontalPositive = (verticalNegative
                        | ~(diagonalZero | verticalPositive));
                int horizontalNegative = diagonalZero & verticalPositive;

                if (i == (count - 1)) {            /* only last bit in last word */
                    if ((horizontalNegative & lastBitPosition) != 0) {
                        distance--;
                    } else if ((horizontalPositive & lastBitPosition) != 0) {
                        distance++;
                        if ((maxMisses -= 2) < 0) {
                            break outer;
                        }
                    } else if (--maxMisses < 0) {
                        break outer;
                    }
                }

                horizontalPositive = ((horizontalPositive << 1)
                        | horizontalPositiveShift);
                horizontalPositiveShift = (horizontalPositive >>> wordSize);

                horizontalNegative = ((horizontalNegative << 1)
                        | horizontalNegativeShift);
                horizontalNegativeShift = (horizontalNegative >>> wordSize);

                verticalPositives[i] = (horizontalNegative
                        | ~(diagonalZero | horizontalPositive))
                        & wordMask;
                verticalNegatives[i] = (diagonalZero & horizontalPositive) & wordMask;
            }
        }
        return distance;
    }

    @Override
    protected void perThreadInit() {
        super.perThreadInit();
        verticalPositivesReusable = new int[count];
        verticalNegativesReusable = new int[count];
    }
}

static class TYPEint/*WORD*/ extends MyersBitParallelEditDistance {
    final int/*WORD*/ lastBitPosition;
    final int/*WORD*/[] map;

    @SuppressWarnings("cast")
    TYPEint/*WORD*/(CharSequence s) {
        super(s);
        /* Precompute bitmaps for this pattern */
        map = PatternBitmap.map(s, idx, new int/*WORD*/[idx.size()]);
        /* Compute the bit that represents a change in the last row */
        lastBitPosition = (((int/*WORD*/) 1) << (m - 1));
    }

    @Override
    public int getDistance(CharSequence s, int k) {
        int len = s.length();

        /* Quick check based on length */
        if (((len - m) > k) || ((m - len) > k)) {
            return k + 1;
        }

        /* Map characters to their integer positions in the bitmap array */
        indices = idx.map(s, indices);

        /* Initially, vertical change is all positive (none negative) */
        int/*WORD*/ verticalPositive = -1;
        int/*WORD*/ verticalNegative = 0;
        int distance = m;

        /* We can only miss the "distance--" below this many times: */
        int maxMisses = k + len - m;
        if (maxMisses < 0) {
            maxMisses = Integer.MAX_VALUE;
        }

        for (int j = 0; j < len; j++) {
            /* Where is diagonal zero: matches, or prior VN; plus recursion */
            int/*WORD*/ diagonalZero = map[indices[j]] | verticalNegative;
            diagonalZero |= (((diagonalZero & verticalPositive) + verticalPositive)
                    ^ verticalPositive);

            /* Compute horizontal changes */
            int/*WORD*/ horizontalPositive = verticalNegative
                    | ~(diagonalZero | verticalPositive);
            int/*WORD*/ horizontalNegative = diagonalZero & verticalPositive;

            /* Update final distance based on horizontal changes */
            if ((horizontalNegative & lastBitPosition) != 0) {
                distance--;
            } else if ((horizontalPositive & lastBitPosition) != 0) {
                distance++;
                if ((maxMisses -= 2) < 0) {
                    break;
                }
            } else if (--maxMisses < 0) {
                break;
            }

            /* Shift Hs to next row, compute new Vs analagously to Hs above */
            horizontalPositive = (horizontalPositive << 1) | 1;
            verticalPositive = (horizontalNegative << 1)
                    | ~(diagonalZero | horizontalPositive);
            verticalNegative = diagonalZero & horizontalPositive;
        }
        return distance;
    }
}

static class TYPElong/*WORD*/ extends MyersBitParallelEditDistance {
    final long/*WORD*/ lastBitPosition;
    final long/*WORD*/[] map;

    TYPElong/*WORD*/(CharSequence s) {
        super(s);
        /* Precompute bitmaps for this pattern */
        map = PatternBitmap.map(s, idx, new long/*WORD*/[idx.size()]);
        /* Compute the bit that represents a change in the last row */
        lastBitPosition = (((long/*WORD*/) 1) << (m - 1));
    }

    @Override
    public int getDistance(CharSequence s, int k) {
        int len = s.length();

        /* Quick check based on length */
        if (((len - m) > k) || ((m - len) > k)) {
            return k + 1;
        }

        /* Map characters to their integer positions in the bitmap array */
        indices = idx.map(s, indices);

        /* Initially, vertical change is all positive (none negative) */
        long/*WORD*/ verticalPositive = -1;
        long/*WORD*/ verticalNegative = 0;
        int distance = m;

        /* We can only miss the "distance--" below this many times: */
        int maxMisses = k + len - m;
        if (maxMisses < 0) {
            maxMisses = Integer.MAX_VALUE;
        }

        for (int j = 0; j < len; j++) {
            /* Where is diagonal zero: matches, or prior VN; plus recursion */
            long/*WORD*/ diagonalZero = map[indices[j]] | verticalNegative;
            diagonalZero |= (((diagonalZero & verticalPositive) + verticalPositive)
                    ^ verticalPositive);

            /* Compute horizontal changes */
            long/*WORD*/ horizontalPositive = verticalNegative
                    | ~(diagonalZero | verticalPositive);
            long/*WORD*/ horizontalNegative = diagonalZero & verticalPositive;

            /* Update final distance based on horizontal changes */
            if ((horizontalNegative & lastBitPosition) != 0) {
                distance--;
            } else if ((horizontalPositive & lastBitPosition) != 0) {
                distance++;
                if ((maxMisses -= 2) < 0) {
                    break;
                }
            } else if (--maxMisses < 0) {
                break;
            }

            /* Shift Hs to next row, compute new Vs analagously to Hs above */
            horizontalPositive = (horizontalPositive << 1) | 1;
            verticalPositive = (horizontalNegative << 1)
                    | ~(diagonalZero | horizontalPositive);
            verticalNegative = diagonalZero & horizontalPositive;
        }
        return distance;
    }
}

public static MyersBitParallelEditDistance getInstance(CharSequence s) {
    int m = s.length();
    return (m <= Integer.SIZE) ?
            ((m == 0) ? new Empty(s) : new TYPEint(s)) :
            (s.length() <= Long.SIZE) ?
                    new TYPElong(s) :
                    new Multi(s);
}

final CharIndex idx;

int[] indices = new int[0];

final int m;

protected MyersBitParallelEditDistance(CharSequence s) {
    m = s.length();
    idx = CharIndex.getInstance(s);
}

public GeneralEditDistance duplicate() {
    try {
        return (MyersBitParallelEditDistance) clone();
    } catch (CloneNotSupportedException x) { /*IMPOSSIBLE */
        throw new IllegalStateException("Cloneable object would not clone");
    }
}

public abstract int getDistance(CharSequence s, int k);

@Override
protected Object clone() throws CloneNotSupportedException {
    Object obj = super.clone();

    /* Re-initialize any non-thread-safe parts */
    ((MyersBitParallelEditDistance) obj).perThreadInit();

    return obj;
}

protected void perThreadInit() {
    indices = new int[0];
}
}

class PatternBitmap {

public static int[] map(CharSequence s, CharIndex idx, int[] result) {
    int len = s.length();
    assert (len <= Integer.SIZE);
    for (int i = 0; i < len; i++) {
        result[idx.lookup(s.charAt(i))] |= (1 << i);
    }
    return result;
}

public static int[][] map(CharSequence s, CharIndex idx,
                          int[][] result, int width) {
    assert (width <= Integer.SIZE);
    int len = s.length();
    int rowSize = (len + width - 1) / width;

    /*
    * Use one zero-filled bitmap for alphabet characters not in the pattern
    */
    int[] nullElement = new int[rowSize];
    java.util.Arrays.fill(result, nullElement);

    int wordIndex = 0;          /* Which word we are on now */
    int bitWithinWord = 0;      /* Which bit within that word */

    for (int i = 0; i < s.length(); i++) {
        int[] r = result[idx.lookup(s.charAt(i))];
        if (r == nullElement) {

            /* Create a separate zero-filled bitmap for this alphabet character */
            r = result[idx.lookup(s.charAt(i))] = new int[rowSize];
        }
        r[wordIndex] |= (1 << bitWithinWord);

        /* Step to the next bit (and word if appropriate) */
        if (++bitWithinWord == width) {
            bitWithinWord = 0;
            wordIndex++;
        }
    }
    return result;
}

public static long[] map(CharSequence s, CharIndex idx, long[] result) {
    int len = s.length();
    assert (len <= Long.SIZE);
    for (int i = 0; i < len; i++) {
        result[idx.lookup(s.charAt(i))] |= (1L << i);
    }
    return result;
}

private PatternBitmap() { /* Prevent instantiation */ }
}


CRC 16 code with "unsafe features" I have the following CRC 16 code.  Is it possible to improve the performance of the code with unsafe constructs?  My knowledge about pointer arithmetic is rather limited.

public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 }

public class Crc16Ccitt
{
    static ushort[] table = new ushort[256];

    public ushort ComputeChecksum(params byte[] bytes)
    {
        ushort crc = 0;
        for (int i = 0; i < bytes.Length; ++i)
        {
            byte index = (byte)(crc ^ bytes[i]);
            crc = (ushort)((crc >> 8) ^ table[index]);
        }
        return crc;
    }

    public Crc16Ccitt(Crc16Mode mode)
    {
        ushort polynomial = (ushort)mode;
        ushort value;
        ushort temp;
        for (ushort i = 0; i < table.Length; ++i)
        {
            value = 0;
            temp = i;
            for (byte j = 0; j < 8; ++j)
            {
                if (((value ^ temp) & 0x0001) != 0)
                {
                    value = (ushort)((value >> 1) ^ polynomial);
                }
                else
                {
                    value >>= 1;
                }
                temp >>= 1;
            }
            table[i] = value;
        }
    }
}

Your code looks pretty good except for the static table. More about that later.

Unsafe code has a few things that can make code go faster, like pointers to arrays and arrays on the stack.

A pointer to array would make code only faster if the code is iterating through that array. ComputeChecksum does iterate trough data, so yes, this part could become a little bit faster. We are talking about microseconds.

You are also iterating through an the table array inside the constructor. So creation of this table could also become a littel bit faster.

Personally: I would not use unsafe code in your case.

About the static

You have a static table, but when you create a new instance of Crc16Ccitt it will recalculate all the (same) values. (Talking about performance loss!) If you have two instances of Crc16Ccitt with different polynomials, then one of your instances will calculate it CRC's wrong, because they both share the same table (since it is static).

How to solve this in a faster and safer way?

Use a static! (Huh?) Yes, a static but another one:

static private readonly Dictionary<Crc16Mode, ushort[]> _tables; This will store all calculated tables.

In your class use a local field: ushort[] _table; This one will hold the (already) calculated table. If the table was not calculated, it will be calculated and stored inside _tables.

You also use this mechanism to store hard coded calcaulated tables, as Jesse suggests. In that case you would assign your hard code table to the dictionary inside a static constructor.

Your code could become like this:

public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 }

public class Crc16Ccitt
{
    #region Static members

    static private readonly Dictionary<Crc16Mode, ushort[]> _tables = new Dictionary<Crc16Mode, ushort[]>();

    static private ushort[] GetTable(Crc16Mode mode)
    {
        lock (_tables)
        {
            ushort[] table;
            if (_tables.TryGetValue(mode, out table))
                return table;

            ushort polynomial = (ushort)mode;
            for (ushort i = 0; i < table.Length; ++i)
            {
                ushort value = 0;
                ushort temp = i;
                for (byte j = 0; j < 8; ++j)
                {
                    if (((value ^ temp) & 0x0001) != 0)
                        value = (ushort)((value >> 1) ^ polynomial);
                    else
                        value >>= 1;
                    temp >>= 1;
                }
                table[i] = value;
            }
            _tables[mode] = table;
            return table;
        }
    }

    #endregion

    private readonly ushort[] _table = new ushort[256];

    public Crc16Ccitt(Crc16Mode mode)
    {
        _table = GetTable(mode);
    }

    public ushort ComputeChecksum(params byte[] bytes)
    {
        ushort crc = 0;
        for (int i = 0; i < bytes.Length; ++i)
        {
            byte index = (byte)(crc ^ bytes[i]);
            crc = (ushort)((crc >> 8) ^ _table[index]);
        }
        return crc;
    }
}


Adding a specific list of numbers to an array I need to add a range of numbers to a list based on specific conditions. The method recieves a String, and based on value of the String, specific list of values should be added to the list.

Name variable has name of the selected product and numbers are serial number of products that are similar to the selected product.

I am wondering if there is any better approach to do it.

ArrayList numbers = new ArrayList<Integer>();
switch (name) {
 case "A":
    for (int i = 1; i <= 100; i++) {
        if ((i >= 46 && i <= 50) || (i >= 60 && i <= 73) || i == 91
                || i == 96 || i == 97) {
            continue;
        } else {
            numbers.add(i);
        }
    }
    break;
 case "B":
    for (int i = 1; i <= 100; i++) {
        if ((i >= 50 && i <= 55) || (i >= 65 && i <= 88) || i == 90
                || i == 98 || i == 99) {
            continue;
        } else {
            numbers.add(i);
        }
    }
    break;

}

  return numbers;

It's always good to ask questions and try to find potentially better ways to do things. You've come to the right place.

So here's what I'm thinking regarding your question:

Yes, I think there is a better way to handle this that will benefit you in the long term, especially with respect to maintenance efforts. Right now you've hard-coded all the various ranges and values that you're excluding from your results. Let me first suggest that this kind of task is better probably handled by a database and a query to that database rather than coding rules in this manner. If you have all of your products and serial numbers in a database you can maintain the data in one place using a system that is designed for data management and you won't have to update your code every time your number scheme changes.

The basic idea is that you're coding data rather than generic logic and structures to support the use of the data. In order to illustrate this I have put together some Java code, but did not implement any database queries as that would take additional time and you can probably research this more on your own without too much difficulty.

So, the first thing I notice is you have very complex if statements that contain hard-coded ranges. If you create a generic Range class and use it to create Range objects to represent the various ranges of values you need you can make your code more generalized, reliable, and maintainable. Here is the Range class I created:

public class Range {
    private boolean isUpperBoundExclusive = true, isLowerBoundExclusive = true;
    private int upperBound, lowerBound;

    public Range(int value){
        isUpperBoundExclusive = false;
        isLowerBoundExclusive = false;
        upperBound = value;
        lowerBound = value;
    }

    public Range(int lower, int upper){
        lowerBound = lower;
        upperBound = upper;
    }

    public void setUpperBoundExclusive(boolean isUpperBoundStrict) {
        this.isUpperBoundExclusive = isUpperBoundStrict;
    }

    public void setLowerBoundExclusive(boolean isLowerBoundStrict) {
        this.isLowerBoundExclusive = isLowerBoundStrict;
    }

    public boolean isWithinRange(int check){
        return (isLowerBoundExclusive ? lowerBound < check : lowerBound <= check)
                && (isUpperBoundExclusive ? upperBound > check : upperBound >= check);
    }
}

Notice how this class represents data, but does not hard-code any data within it. I can configure an instance of this class to represent a single value using the first constructor or a range of values that is inclusive or exclusive at either end.  Notice there is also a method to determine whether a value is within the range called isWithinRange(int check). Please forgive the lack of Javadoc comments, but this is something I just created and I'm preparing to go to bed soon.

By using the Range class we can test the general logic and then we can have some certainty that it works as expected and that if we see errors while using it we're probably using it wrong in some way. So I wrote a quick JUnit test class to test the Range class, here it is:

import static org.junit.Assert.*;

import org.junit.Test;

public class RangeTests {

    @Test
    public void test() {
        Range range = new Range(10,20);
        assertFalse(range.isWithinRange(21));
        assertFalse(range.isWithinRange(9));
        assertFalse(range.isWithinRange(-1));
        assertFalse(range.isWithinRange(0));
        assertFalse(range.isWithinRange(10));
        assertFalse(range.isWithinRange(20));
        assertTrue(range.isWithinRange(11));
        assertTrue(range.isWithinRange(19));
        assertTrue(range.isWithinRange(15));
    }

    @Test
    public void test2() {
        Range range = new Range(10,20);
        range.setLowerBoundExclusive(false);
        assertTrue(range.isWithinRange(10));

        assertFalse(range.isWithinRange(21));
        assertFalse(range.isWithinRange(9));
        assertFalse(range.isWithinRange(-1));
        assertFalse(range.isWithinRange(0));

        assertFalse(range.isWithinRange(20));
        assertTrue(range.isWithinRange(11));
        assertTrue(range.isWithinRange(19));
        assertTrue(range.isWithinRange(15));
    }

    @Test
    public void test3() {
        Range range = new Range(10,20);
        range.setLowerBoundExclusive(false);
        range.setUpperBoundExclusive(false);
        assertTrue(range.isWithinRange(10));
        assertTrue(range.isWithinRange(20));

        assertFalse(range.isWithinRange(21));
        assertFalse(range.isWithinRange(9));
        assertFalse(range.isWithinRange(-1));
        assertFalse(range.isWithinRange(0));

        assertTrue(range.isWithinRange(11));
        assertTrue(range.isWithinRange(19));
        assertTrue(range.isWithinRange(15));
    }

    @Test
    public void test4() {
        Range range = new Range(10,20);
        range.setUpperBoundExclusive(false);
        assertFalse(range.isWithinRange(10));
        assertTrue(range.isWithinRange(20));

        assertFalse(range.isWithinRange(21));
        assertFalse(range.isWithinRange(9));
        assertFalse(range.isWithinRange(-1));
        assertFalse(range.isWithinRange(0));

        assertTrue(range.isWithinRange(11));
        assertTrue(range.isWithinRange(19));
        assertTrue(range.isWithinRange(15));
    }

    @Test
    public void test5() {
        Range range = new Range(10);
        assertFalse(range.isWithinRange(11));
        assertFalse(range.isWithinRange(9));
        assertTrue(range.isWithinRange(10));
    }
}

Next, if we had a list of products we could use inside our main logic it would help simplify the code. I'm not sure whether that's possible since you didn't really specify what sort of data and objects you have to work with, but here is what I'm thinking:

import java.util.ArrayList;
import java.util.List;

public class Product {
    private String name;
    private List<Range> serialNumExcludedRanges;

    public Product(String name){
        this.name = name;
        serialNumExcludedRanges = new ArrayList<Range>();
    }

    public String getName(){
        return name;
    }

    public void addExcludedSerialNumRange(Range rangeToAdd){
        serialNumExcludedRanges.add(rangeToAdd);
    }

    public boolean isSerialNumExcluded(int check){
        for(Range excludedRange: serialNumExcludedRanges){
            if(excludedRange.isWithinRange(check))
                return true;
        }
        return false;
    }
}

Notice how the Product itself contains a list of excluded ranges that it then uses when the isSerialNumExcluded method is called. At that time it uses these ranges in order to determine whether the given input is excluded or not and returns a boolean value accordingly.

Finally, going back to the main logic here's what we're now able to write:

public static List<Integer> getSerialNums(String name) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    for (Product product : productList) {
        // Note: should handle possible null here - what if the "name" param
        // is null?
        if (name.equals(product.getName())) {
            for (int i = 1; i <= 100; i++) {
                if (!product.isSerialNumExcluded(i)) {
                    numbers.add(i);
                }
            }
        }
    }
    return numbers;
}

Remember, this assumes that we have already defined our list of products prior to calling this method. In this example I created a static variable and added a simple main method to initialize them, but this is where a database query would really become useful. Rather than initialize them by hard-coding the values (for completeness I have provided the initialization logic below) you could store the data in a database then query for the values you want and populate your data structures.

private static List<Product> productList = new ArrayList<Product>();

public static void main(String[] args) {
    //Define product A below:
    Product productA = new Product("A");
    Range r1 = new Range(46, 50);
    r1.setLowerBoundExclusive(false);
    r1.setUpperBoundExclusive(false);
    productA.addExcludedSerialNumRange(r1);

    Range r2 = new Range(60, 73);
    r2.setLowerBoundExclusive(false);
    r2.setUpperBoundExclusive(false);
    productA.addExcludedSerialNumRange(r2);

    Range r3 = new Range(91);
    productA.addExcludedSerialNumRange(r3);
    Range r4 = new Range(96);
    productA.addExcludedSerialNumRange(r4);
    Range r5 = new Range(97);
    productA.addExcludedSerialNumRange(r5);
    productList.add(productA);

    //Define product B below:
    Product productB = new Product("B");
    Range r6 = new Range(50, 55);
    r6.setLowerBoundExclusive(false);
    r6.setUpperBoundExclusive(false);
    productB.addExcludedSerialNumRange(r6);

    Range r7 = new Range(65, 88);
    r7.setLowerBoundExclusive(false);
    r7.setUpperBoundExclusive(false);
    productB.addExcludedSerialNumRange(r7);

    Range r8 = new Range(90);
    productB.addExcludedSerialNumRange(r8);
    Range r9 = new Range(98);
    productB.addExcludedSerialNumRange(r9);
    Range r10 = new Range(99);
    productB.addExcludedSerialNumRange(r10);
    productList.add(productB);
}

I hope my code has helped to illustrate the difference between data, business logic, and data structure. Consider what happens when you need to update your code - you risk introducing bugs every time you change something. Keeping the data separate from the logic allows you to isolate the cause of problems. If the code didn't change, odds are it's a data problem. Once again, I just want to restate that I'm not really suggesting you store the ranges of values and so forth in a database - I suggest you store the product information itself and then use that data rather than generate a list of it with a loop.  Hope this helps and best of luck!


Reading MultiPart From Data with descriptors I am new to C# and I have a simple /upload controller to upload an image to S3.   Everything seems to work, just fine but it seems messy.

The function:

Takes multipart form data
Reads it async
Picks out the image
Picks out the associated identity of the image
Reads the identity as a stream
Gets a stream of the image by reading the byte array.
sends the image on its way.

Seems pretty ugly.  Anything I can do to make it more efficient with less code?

Sample payload

------WebKitFormBoundaryRmgsjwjP3nVPh7C7
Content-Disposition: form-data; name="file"; filename="10385095.jpeg"
Content-Type: image/jpeg

------WebKitFormBoundaryRmgsjwjP3nVPh7C7
Content-Disposition: form-data; name="ident"

someguid

------WebKitFormBoundaryRmgsjwjP3nVPh7C7--

Code

    [HttpPost, Route("api/aws/upload")]
    public async Task<IHttpActionResult> Upload()
    {
        if (!Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

        var provider = new MultipartMemoryStreamProvider();
        await Request.Content.ReadAsMultipartAsync(provider);
        var file = provider.Contents[0];
        var identity = provider.Contents[1];
        Stream _id = postId.ReadAsStreamAsync().Result;
        StreamReader reader = new StreamReader(_id);
        string identity = reader.ReadToEnd();
        string filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            var buffer = await file.ReadAsByteArrayAsync();
            string mime = file.Headers.ContentType.ToString();
            Stream stream = new MemoryStream(buffer);
            AwsStore store = new AwsStore();
            object response = store.UploadMultiple(stream, filename, mime, identity);

        return Ok(response);
    }

The naming and variable conventions in your method look like it was written by at least three different persons:

var provider ..
Stream _id ..
StreamReader reader ..

You really should pick just one style and stick to it for the entire application. It's very hard to read.

But the variables are not the only thing that is extremely incosistent.

Stream _id = postId.ReadAsStreamAsync().Result;

Why are you not awaiting this result like you do with the other ..Async methods?

All streams need to be disposed.

Overall I've got the impression that you put this method together just for the sake of this question and mixed variables and fields which would explain why some of them are prefixed with the underscore.


Faster way to copy rows of data to different sheets by column value I'm trying to find a faster way to copy specific rows of a sheet to different sheets. Iterating through them as done in code below takes too much time it leads to timeout.
Some information about origin sheet:

Has already a blocked header
Has around 5000 rows
Column A has a header "Project"
Sheet is sorted by Column A

Goal is to copy range of all rows for each project from origin sheet to a blank sheet that is named from specific project - so all rows that has in column e.g. "ProjectA" in column A are in a sheet called "ProjectA".
Here is a code that is working, but it is using very slow iteration, so I'm waiting around 20 minutes or even get a timeout when I'm processing it:
 var sheet = SpreadsheetApp.getActiveSheet();
    var columnRoom = sheet.getRange("A:A").getValues();
    var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
    var header = rows[0];
    var completedRooms = []
    var last = columnRoom[1][0]
    for (var i = 1; i < columnRoom.length; i++) {
        if (!completedRooms.includes(columnRoom[i][0])) {
            if (columnRoom[i][0] === "") {
                var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet("No Room");
            } else {
                var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(columnRoom[i][0]);
            }
            currentSheet.appendRow(header);
            currentSheet.appendRow(rows[i]);
            completedRooms.push(columnRoom[i][0])
            last = columnRoom[i][0]
        } else if (last == columnRoom[i][0]) {
            var currentSheet = SpreadsheetApp.getActiveSpreadsheet()
            currentSheet.appendRow(rows[i]);
        }
    }

Is there a way to do it faster? I'm thinking about appending specific rows to a range and use copyTo but I can't arrange it, maybe use map function?

Your for () loop is unnecessarily calling SpreadsheetApp.getActiveSpreadsheet() in every single iteration. You can define a varible outside of the loop for chaining:
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
for (let i = 1; i < columnRoom.length; i++) {
  // something...
  spreadsheet.insertSheet("No Room")
}


Python - Input Filtering, Calculating with a Variable Amount of Inputs I've been working on an Aerodynamics calculator using python (which I'm relatively new at), In this program, a value can be calculated based on multiple different inputs ie. a calculates b, b calculates c, or c can find b and b can find a.
To elaborate on the function of this program it will loop through it's logic until it has found all the things it could with the given input(s). The code is pretty long for it's function and that's why I'd like to see if it could be optimized or if I could do anything better. For the input method, the input is a string. The code is as follows:
def Find_Pressure(temp):
    pressure = (101.29 * (((temp + 273.1) / 288.08) ** 5.256))
    return pressure

def Find_Temp_Alt(alt, ground_temp):
    Temp = ground_temp - (0.00649 * alt)
    return Temp

def Find_Density(pressure, temp):
    density = (pressure / (0.2869 * (temp + 273.1)))
    return density

def Find_Alt_Temp(temp, ground_temp):
    Alt = ((ground_temp - temp) / 0.00649)
    return Alt

def is_Valid(x):
    try:
        float(x)
        return True
    except ValueError:
        return False

def Parser(ground_temp, temp, alt, pressure, density):
    a = t = p = d = False
    run = True
    Alt = Temp = Pressure = Density = "N/A"
    if is_Valid(alt):
        Alt = float(alt)
        a = True
    if is_Valid(temp):
        Temp = float(temp)
        if Temp <= -273.1:
            t = False
        else:
            t = True
    if is_Valid(pressure):
        Pressure = float(pressure)
        p = True
    if is_Valid(density):
        Density = float(density)
        d = True

    if not is_Valid(ground_temp):
        print('Enter Ground Temp')
    else:
        G_T = float(ground_temp)
        while run:
            run = False
            if a and not t:
                Temp = Find_Temp_Alt(Alt, G_T)
                t = True
                run = True

            if t and not a:
                Alt = Find_Alt_Temp(Temp, G_T)
                a = True
                run = True

            if p and not t:
                Temp = ((288.08 * ((Pressure / 101.29) ** (1 / 5.256))) - 273.1)
                t = True
                run = True

            if t and not p:
                Pressure = Find_Pressure(Temp)
                p = True
                run = True

            if (p and t) and not d:
                Density = Find_Density(Pressure, Temp)
                d = True
                run = True
            if (d and t) and not p:
                Pressure = (Density * 0.2869 * (Temp + 273.1))
                p = True
                run = True

            if (d and p) and not t:
                Temp = ((Pressure / Density * 0.2869) - 273.1)
                t = True
                run = True
        return Alt, Temp, Pressure, Density

I apricate any help/feedback, thanks in advance!

Welcome to Code Review! I'll be adding onto what @Linny has already said about type hints and variable naming. Variable naming is part of python's PEP-8 guidelines (see bottom).
Magic numbers
You have a lot of magic numbers in your code, which are really conversion constants, but appear with no such explanation.
Variable names
Since you're writing an aerodynamics calculator, it'd help if you use full names for various variables in your code. For eg. altitude instead of alt, temperature instead of just temp (temp is generally used as a temporary variable in code).
Ground temperature
Based on the flow of program, I assume that ground_temperature is essential for any calculations. Perhaps check for it at the very beginning and break early in case of invalid checks.
Optional arguments
From the above, only ground_temperature is needed to call the calculator. Everything else is optional, and can be computed. Perhaps a function which defaults other values to None might suit you better:
def aerodynamic_calculator(
    ground_temperature: float,
    temperature: float = None,
    altitude: float = None,
    pressure: float = None,
    density: float = None,
):

Booleans for each parameter
With the above approach, you can just validate for the value itself, without having to keep track of a boolean for those values.
if temperature and not altitude:
    altitude = compute_altitude_from_temperature(temperature, ground_temperature)

PEP-8
In python, it is common (and recommended) to follow the PEP-8 style guide for writing clean, maintainable and consistent code.
Functions and variables should be named in a lower_snake_case, classes as UpperCamelCase, and constants as UPPER_SNAKE_CASE.