texts: Factory hierarchy for creating GoogleMap and its elements

texts:
The purpose of this code is to create a GoogleMap using PHP, add markers to it according to Place objects from database, add infoWindows for these markers. While reading about Factory pattern I came up with the following solution. What are the parts that can be improved. Thank you.

Factory for creating markers:

class MarkerFactory
{
    public function create(Coordinate $position, array $options = [])
    {
        $marker = new Marker($position);
        $marker->setOptions($options);

        return $marker;
    }
}

Factory for creating infoWindows. Isn't it violating any principles because of injected dependency?

class InfoWindowFactory
{
    private $twig;

    public function __construct(\Twig_Environment $twig)
    {
        $this->twig = $twig;
    }

    public function create(Place $place, $editable = false)
    {
        return new InfoWindow($this->renderWindowContent($place, $editable));
    }

    protected function renderWindowContent(Place $place, $editable)
    {
        if ($editable) {
            $template = 'editable_infowindow.html.twig';
        } else {
            $template = 'static_infowindow.html.twig';
        }

        return $this->twig->render($template, ['place' => $place]);
    }
}

MapFactory that uses MarkerFactory and InfoWindowFactory:

class MapFactory
{
    private $markerFactory;

    private $infoWindowFactory;

    public function __construct(MarkerFactory $markerFactory, InfoWindowFactory $infoWindowFactory)
    {
        $this->markerFactory = $markerFactory;
        $this->infoWindowFactory = $infoWindowFactory;
    }

    public function create(Coordinate $mapCenter, array $places = [], array $mapOptions = [], $isEditableMap = false)
    {
        $map = new Map();

        $map->setCenter($mapCenter);
        $map->setMapOptions($mapOptions);

        $markers = [];

        foreach ($places as $place) {
            $position = new Coordinate($place->getLatitude(), $place->getLongitude());

            $marker = $this->markerFactory->create($position);
            $infoWindow = $this->infoWindowFactory->create($place, $isEditableMap);

            $marker->setInfoWindow($infoWindow);

            $markers[] = $marker;
        }

        $map->getOverlayManager()->setMarkers($markers);

        return $map;
    }
}

And the code example of usage:

$markerFactory = new MarkerFactory();
$infoWindowFactory = new InfoWindowFactory($this->get('twig'));
$mapFactory = new MapFactory($markerFactory, $infoWindowFactory);

$center = new Coordinate(55.117100, 23.940332);
$options = ['zoom' => 7];
$map = $mapFactory->create($center, $places, $options);


texts:
I have implemented the maximum path sum of a triangle of integers (problem 18 in project euler) and I am wondering how I can improve my solution. My solution is below:

def problem18(triangle, height):
    return dp_triangle(triangle, height, 0, 0, dict())

def dp_triangle(triangle, height, row, col, maxs):
    if row == height - 1:
        return int(triangle[row][col])

    keyLeft = str(row + 1) + "," + str(col)
    keyRight = str(row + 1) + "," + str(col + 1)

    if keyLeft in maxs:
        maxLeft = maxs[keyLeft]
    else:
        maxLeft = dp_triangle(triangle, height, row + 1, col, maxs)
        maxs[keyLeft] = maxLeft

    if keyRight in maxs:
        maxRight = maxs[keyRight]
    else:
        maxRight = dp_triangle(triangle, height, row + 1, col + 1, maxs)
        maxs[keyRight] = maxRight

    return max(maxLeft, maxRight) + int(triangle[row][col])

To call this function I have the following:

def main(argv):
    with open(argv[1], 'r') as f:
        triangle = f.readlines()

    height = len(triangle)

    triangle = [x.strip().split() for x in triangle]

    print(problem18(triangle, height))

I just pass a text file with the triangle of numbers to the program. These numbers are separated by whitespace.


texts: Efficient loop over a integer range in Python

texts:
I want to search for positions inside a range of integers. How to improve the code in terms of efficiency, since both my search list and the ranges are very big:
#Range list with ids
range_lst = [(121000, 122000, 'foo'), (123456, 124557, 'bar'), (156789, 163659, 'egg')]
# Positions which we want to scan
pos = [123456, 369369]
# Neighbouring windows size
window_size = 10000

for p in pos:
    for r in range_lst:
        range_area = range(r[0], r[1])
        range_area_window = range(r[0]-window_size, r[1]+window_size)
        id = r[2]
        if p in range_area:
            print (p, id, 'exact hit!')
        else:
            # If we don't find an exact hit, we check the neighbouring region +- 10000
            if p in range_area_window:
                print (p, id, 'neighbour hit!')


texts: Choosing a Color based on an int for a 2048 clone in Java

texts:
Is it possible to make this cleaner / more efficient? I know that this is probably not the best way to do this and probably could be made better but I cannot figure out how I do that.

Basically, a number is given which is then compared to the numbers in Num[] and then returns a color based on that comparison.

private Color chooseColor(int i){
    Color Emerald = new Color(231, 223, 134); //2
    Color BelizeHole = new Color(151, 206, 104); // 4
    Color Carrot = new Color(240, 79, 3);// 8
    Color MidnightBlue = new Color(116, 116, 204); // 16
    Color SunFlower = new Color(89, 188, 251);// 32
    Color Alizarin = new Color(245, 213, 69);// 64
    Color Wisteria = new Color(46, 204, 113); // 128
    Color Silver = new Color(254, 198, 6); //256
    Color Concrete = new Color(151, 206, 104); //512
    Color Orange = new Color(136, 112, 255); //1024
    Color Amethyst = new Color(255, 215, 0); //2048
    Color[] RECT_COLORS = {Emerald, BelizeHole, Carrot, Amethyst, SunFlower, Alizarin, Wisteria, Silver, Concrete, Orange, Amethyst};
    int[] Num = {2,4,8,16,32,64,128,256,512,1024,2048};

    for(int j = 0 ; j < Num.length ; j++){
        if(i == Num[j]){
            return RECT_COLORS[j];
        } else if ( j == Num.length - 1 ){
            return RECT_COLORS[Num.length-1];
        }
    }

    return RECT_COLORS[Num.length-1];
}

This compiles and runs fine.

Outside of the method, it is called when painting a string on Canvas and returns a color based on the string value which is what color the string is then painted as.

Basically:

String is about to to be painted. What color should it be?
chooseColor(4);
chooseColor(4) = BelizeHole. Let's paint it with that color.


texts:
This is a question about some code I've written that works, but I'm not sure it's good code.

I would like to get some comments on this or if possible hints to build a better solution.

Background:

This is a small program to calculate some data, connect these to a participant and store it in a JSON file.

Here the already working solution:

menu_entries = (
                    ('Order Pizza', order_pizza),
                    ('Order Burger', order_burger),
                    ('Order Coke', order_coke, '0.5')
               )

def menu(menu_title, menu_entries):

    while True:
        mpoint = 0

        print(menu_title)

        # Build the menu entries plus one to close
        for entry in menu_entries:
            mpoint += 1
            print(str(mpoint) + '.', entry[0])

        print(str(mpoint + 1) + '.', 'Ende')

        # Get value and validate
        try:
            task = int(input('> '))
        except ValueError:
            task = None

        if task is None or task > mpoint + 1:
            task = None
            continue

        if task == mpoint + 1:
            print('Done')
            break

        # Build a function call
        get_task = menu_entries[task - 1][1]
        try:
            get_task(menu_entries[task - 1][2])
        except IndexError:
            get_task()

def order_pizza(size=None):
    if size is None:
        size = ''
    print('Bring me a Pizza!')

def order_burger(size=None):
    if size is None:
        size = ''
    print('One {} Burger please.'.format(size))

def order_coke(size=None):
    if size is None:
        size = ''
    print('A {} Coke please.'.format(size))

menu('Main menu', menu_entries)

As you can see the menu function gets a main title and a tuple of menu entries.

In these menu entries I could define the menu point title, a function name and one parameter.

All these other functions are only examples and are of no interest (they are ugly, I know).

Please have a look, criticize and if possible show me a better solution.


texts:
I'd like to improve this bubble sort code

 package com.arun.sort;

 import java.util.Arrays;

 public class BubbleSort {

public static void main(String[] args) {

    int[] arr={2,5,1,8,12,3,7};
    int n=arr.length;

    for(int k=0;k<n-1;k++){
        for(int i=0;i<n-k-1;i++){
            if(arr[i]>arr[i+1]){
                int temp=arr[i];
                arr[i]=arr[i+1];
                arr[i+1]=temp;
            }
        }
    }

    System.out.println("Sorted array" +Arrays.toString(arr));

  }

   }


texts:
Example that could be turned into a button to view user's public ftp where initial page is "http://user.school.edu/":

javascript:(function( {
   var h,i,t;
   h=window.location.hostname;i=h.IndexOf('.school.edu');t=h.substring(0,i);
   window.location.assign("ftp://ftp.school.edu/public/"+t
});

Help me refine this idea, please.


texts: Generate line chart from SQL database output using Morris

texts:
<script>
<?php
unset($data0);
unset($data1);
unset($data2);

$sth = $dbh->prepare("
SELECT a, b, c
FROM   t
");
$sth->execute();
?>

Morris.Line({
  element: 'morris-line-chart',
  data: [
  <?php
  while ($row = $sth->fetch()) { ?>
    { m: '<?php echo $row['0']; ?>', a: <?php echo $row['1']; ?>, b: <?php echo $row['2']; ?> },
  <?php } ?>
  ],
  xkey: 'm',
  xLabels: 'month',
  ykeys: ['a', 'b'],
  labels: ['2014', '2015']
});
</script>

Is there a cleaner way to write it, especially the PHP echoing to create the JavaScript?


texts: Implementation of merge sort that takes sublinear extra space

texts:
I implemented an algorithm that takes only sublinear extra space as required in the exercise description:

  Develop a merge implementation that reduces the extra space
  requirement to max(M, N/M). (dividing the array into N/M blocks of
  size M).

def insert_sort(a, lo, hi):
    for i in range(lo+1, hi):
        j = i
        while(j>lo and a[j]<a[j-1]):
            a[j], a[j-1] = a[j-1], a[j]
            j -= 1

def in_place_merge(a, lo, mi, hi):
    aux_hi = a[mi:hi]

    for i in reversed(range(lo, hi)):
        if aux_hi:
            last_a = i - len(aux_hi)
            if (last_a < lo or aux_hi[-1] > a[last_a]):
                a[i] = aux_hi.pop()
            else:
                a[i] = a[last_a]
        else:
            break

def block_insertion_sort(a):
    M = 5
    for i in range(0, len(a), M):
        insert_sort(a, i, min(i+M, len(a)))
        if i > 0:
            in_place_merge(a, 0, i, min(i+M, len(a)))

In addition, I don't understand the max(M, N/M) part, then I don't know if I have made it. Any suggestions are highly appreciated.


texts:
I'm not sure whether I should be throwing exceptions in the below model code (and rescuing in the controller - rescues not implemented below) or returning nil (in both or one of the exception cases). Also, should the model method be identify, or is identify proper?

My line of thinking is if the title is not set when identify is called, something is wrong or it is being used incorrectly.  Regarding the second exception, if there are no results, then the movie in question can not be scraped, thus making all operations later (which depend on the scraped data) useless.

I guess this comes down to return nil vs throw exception - I have been reading quite a few arguments on this subject and to me it seems proper to throw in both cases, thoughts?  Perhaps i'm missing a "rails way" of doing this too?  I'm fairly new to Rails.  If it matters, I am using Rails 3.2.

Movie model

validates :title, :presence => true

def identify
  raise "No Title" if self.title.nil?

  search_content = Nokogiri::HTML open("http://akas.imdb.com/find?q=#{CGI::escape(self.title)};s=tt")

  top_result = search_content.xpath("//div[@id='main']/p[1]/b/a").first

  raise "No Results" if top_result.nil?

  self.title = top_result.content

  self.imdb_id = top_result["href"].split("/")[2][2..-1].to_i

end

def populate_data
  identify if self.imdb_id.nil?

  # ...scrape imdb and save content to model attributes...
end

MovieController

def create
  @movie = Movie.new :title => params[:movie][:title]

  @movie.populate_data

  if @movie.save
    # ...the usual set flash, else recover kinda thing...


texts: Deque implemented using a circular array

texts:
I found a tutorial on implementing a deque using a circular array. I changed the implementation but I am not sure if it is correct or not.

So I have one question:

I wrote code that uses an addCount field to record whether there are any additions, but I'm not sure if it's correct? If not, please tell me where I made an error.

class Deque {
    static final int MAX = 100;
    int arr[];
    int front;
    int rear;
    int size;
    int addCount;

    public Deque(int size) {
        arr = new int[size];
        front = 0;
        rear = 0;
        this.size = size;
        addCount = 0;
    }

    // Checks whether Deque is full or not.
    boolean isFull() {

        return front == rear && !isEmpty();
    }

    // Checks whether Deque is empty or not.
    boolean isEmpty() {
        return front == rear && addCount == 0;
    }

    // Inserts an element at front
    void insertfront(int key) {
        if (isFull())
            return;

        addCount++;
        arr[front] = key;
        front = front + 1;
        front %= this.size;
    }

    // function to inset element at rear end
    // of Deque.
    void insertrear(int key) {
        if (isFull())
            return;
        addCount++;
        rear = (rear - 1) % this.size;
        arr[rear + this.size] = key;

    }

    // Deletes element at front end of Deque
    void deletefront() {
        if (isEmpty())
            return;
        addCount--;
        front = (front - 1) % this.size;
    }

    // Delete element at rear end of Deque
    void deleterear() {
        if (isEmpty())
            return;
        addCount--;
        rear = (rear + 1) % this.size;
    }

    // Returns front element of Deque
    int getFront() {
        int getFront = front-1;

        if (getFront < 0)
            getFront += this.size;
        return arr[getFront % this.size];
    }

    // function return rear element of Deque
    int getRear() {
        int getRearIndex = rear + this.size;
        return arr[getRearIndex % this.size];
    }

    // Driver program to test above function
    public static void main(String[] args) {
        Deque dq = new Deque(5);
        System.out.println("Insert element at rear end : 5 ");
        dq.insertrear(5);

        System.out.println("insert element at rear end : 10 ");
        dq.insertrear(10);

        System.out.println("get rear element : " + dq.getRear());

        dq.deleterear();
        System.out.println("After delete rear element new rear become : " + dq.getRear());

        System.out.println("inserting element at front end");
        dq.insertfront(15);

        System.out.println("get front element: " + dq.getFront());

        dq.deletefront();

        System.out.println("After delete front element new front become : " + +dq.getFront());

    }
}


texts: How to avoid echoing JavaScript from PHP?

texts:
I want to use some constant in both server side and client side.

Currently, I use PHP reflection in order to synchronize PHP constants and Javascript constants. But for the maintainable reason, it's not a best practise.

For example:

interface IType{
//...
const ID_TYPE_TEXT      = 1000;
const ID_TYPE_NUMBER    = 2000;
const ID_TYPE_IMAGE     = 3000;
const ID_TYPE_VIDEO     = 4000;
//...
}

In view

$r   = new ReflectionClass('IType');
foreach( $r->getConstants() as $const => $value)
{
     echo "var $const = $value;"
}

How can I avoid doing that?


texts: Redefine count-leaves as an accumulation

texts:
Exercise 2.35.  Redefine count-leaves
  from section 2.2.2 as an accumulation:

(define (count-leaves t) (accumulate <??> <??> (map <??> <??>)))

I wrote the following:

(define (accumulate op initial sequence)
  (if (null? sequence)
      initial
      (op (car sequence)
          (accumulate op initial (cdr sequence)))))

(define (count-leaves t)
  (accumulate +
              0
              (map (lambda (subtree)
                     (if (pair? subtree)
                         (count-leaves subtree)
                         1))
                   t)))

(define a (list 1 2 (list 1) (list 1 2 (list 2 (list 1 2)))))

What do you think?


texts: Query an array at intervals and getting the highest number of values


texts: Finding the number of longest contiguous increasing subsequences in a given array

texts:
This is different from classic LIS problem. Here I want number of contiguous longest increasing subsequences!

For example:

INPUT: arr[] = { 3, 6, 10, 8, 11, 17, 16, 100 }
OUTPUT: 2

Explanation: There are 2 longest contiguous subsequences: { 3, 6, 10 } and { 8, 11, 17 }.

Here is a function that I have made to achieve the task. But is there any optimized way instead of this brute force approach?

#define ll long long int
ll longestIncSeq(vector<ll> temp, ll n)
{
    ll count=0,mymax = -1,flag=0,dummy=0;

    while( (flag==0) && (!(temp.empty())) )
    {
        ll max = 1, len = 1, maxIndex = 0;

        for (ll i=1; i<n; i++)
        {
            if (temp[i] > temp[i-1])
                len++;
            else
            {
                if (max < len)
                {
                    max = len;
                    maxIndex = i - max;
                }
                len = 1;
            }
        }
        if (max < len)
        {
            max = len;
            maxIndex = n - max;
        }
        if( max == 1 )
        {
            return count;
        }
        if( (mymax == max) || (dummy==0) )
        {
            count++;
            dummy++;
        }
        else
        {
            flag = 1;
        }
        temp.erase(temp.begin()+maxIndex , temp.begin()+maxIndex+max);

        mymax = max;
        n = temp.size();
    }
    return count;
}


texts:
I need to add some characters to a String before using it for an API call. The idea is to add a " char both at the beginning and at the end of the String, to make sure the API does an exact search for the input string.

Version 1:

StringBuilder(escapeJava(query))
                .insert(0, DOUBLE_QUOTE_CHAR)
                .append(DOUBLE_QUOTE_CHAR)
                .toString();

Version 2:

String.format("%c" + escapeJava(query) + "%c", DOUBLE_QUOTE_CHAR, DOUBLE_QUOTE_CHAR)

I prefer the readability of the first one, but I don't think it will be as quick as the second version, and might look like overkill.


texts: Is this file I/O utility efficient or is there a lot of fat?

texts:
This is a class/method that manages files being written to and read from. I have a lot of code, and it grew as I tried to get it to work properly. Is there a better way to write this (i.e. trim the fat) or is it written properly?

import java.io.*;

public class DataBase {
public static String getExtension(File f) {
    String ext = null;
    String s = f.getName();
    int i = s.lastIndexOf('.');

    if (i > 0 && i < s.length() - 1) {
        ext = s.substring(i + 1).toLowerCase();
    }
    return ext;
}

public static String readFile(String file) {
    String data = "";
    if (!new java.io.File(file).exists()) {
        return data;
    }
    File f = new File(file);
    FileInputStream fStream = null;
    BufferedInputStream bStream = null;
    BufferedReader bReader = null;
    StringBuffer buff = new StringBuffer();

    try {
        fStream = new FileInputStream(f);
        bStream = new BufferedInputStream(fStream);
        bReader = new BufferedReader(new InputStreamReader(bStream));
        String line = null;

        while ((line = bReader.readLine())!=null) {
            //line = bReader.readLine();

            if (line.length() > 0) {
                if (line.contains("
")) {
                    line = line.replaceAll("
", " ");
                    String tempLine = "";
                    while ((tempLine.trim().length() < 1)
                            && bStream.available() != 0) {
                        tempLine = bReader.readLine();
                    }
                    line = line + tempLine;
                }
                buff.append(line += "\n");

            }
        }

        fStream.close();
        bStream.close();
        bReader.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return buff.toString();

}

public static boolean writeToFile(String fileName, String data,
        boolean append) {
    boolean isWrite = false;
    int dirIndex = fileName.lastIndexOf(getPathSeparator());
    if (dirIndex != -1) {
        String dir = fileName.substring(0, dirIndex) + getPathSeparator();
        java.io.File fDir = new java.io.File(dir);
        if (!fDir.exists()) {
            if (!fDir.mkdirs()) {
                return false;
            }
        }
    }
    try {
        java.io.FileOutputStream fout = new java.io.FileOutputStream(
                fileName, append);
        java.nio.channels.FileChannel fChannelWriter = fout.getChannel();
        byte[] bytesToWrite = data.getBytes();
        java.nio.ByteBuffer bBuffW = java.nio.ByteBuffer.wrap(bytesToWrite);
        fChannelWriter.write(bBuffW);
        fChannelWriter.close();
        fout.close();
        isWrite = true;
    } catch (java.io.IOException ex) {
        System.out.println("Error Occured: Unable to write to file ("
                + fileName + ")");
        isWrite = false;
    }
    return isWrite;
}

public static String getPathSeparator() {
    return java.io.File.separator;
}
}


texts:
I'm pretty new to ASP/MVC but have had some prior programming experience.

I am trying to retrieve statistics about URL clicks - total clicks and unique clicks by IP address. I started with:

ViewBag.ClicksToday = context.EmailLinkClicks
     .Where(c => c.CreatedOn == DateTime.Today).Count();

ViewBag.ClicksWeek = context.EmailLinkClicks
     .Where(c => c.CreatedOn > System.Data.Entity.DbFunctions.AddDays(c.CreatedOn, -7)).Count();

ViewBag.ClicksMonth = context.EmailLinkClicks
     .Where(c => c.CreatedOn.Month == DateTime.Today.Month).Count();

ViewBag.UniqueClicksToday = context.EmailLinkClicks.Where(c => c.CreatedOn == DateTime.Today)
     .Select(c => c.IPAddress).Distinct().Count();

ViewBag.UniqueClicksWeek = context.EmailLinkClicks.Where(c => c.CreatedOn > System.Data.Entity.DbFunctions.AddDays(c.CreatedOn, -7))
     .Select(c => c.IPAddress).Distinct().Count();

ViewBag.UniqueClicksMonth = context.EmailLinkClicks.Where(c => c.CreatedOn.Month == DateTime.Today.Month)
     .Select(c => c.IPAddress).Distinct().Count();

Then I thought why not make it a function:

private static int GetClicks(AppContext context, string period, bool unique)
{
    int Clicks = 0;
    switch (period)
    {
        case "today":
            var ClicksToday = context.EmailLinkClicks
                .Where(c => c.CreatedOn == DateTime.Today);
            Clicks = unique ? ClicksToday.Select(c => c.IPAddress).Distinct().Count()
                : ClicksToday.Count();
            break;
        case "week":
            var ClicksWeek = context.EmailLinkClicks
                .Where(c => c.CreatedOn > System.Data.Entity.DbFunctions.AddDays(c.CreatedOn, -7));
            Clicks = unique ? ClicksWeek.Select(c => c.IPAddress).Distinct().Count()
                : ClicksWeek.Count();
            break;
        case "month":
            var ClicksMonth = context.EmailLinkClicks
                .Where(c => c.CreatedOn.Month == DateTime.Today.Month);
            Clicks = unique ? ClicksMonth.Select(c => c.IPAddress).Distinct().Count()
                : ClicksMonth.Count();
            break;
    }
    return Clicks;
}

But I still have to call quite a lot of code:

ViewBag.ClicksToday = GetClicks(context, "today", false);
ViewBag.ClicksWeek = GetClicks(context, "week", false);
ViewBag.ClicksMonth = GetClicks(context, "month", false);

ViewBag.UniqueClicksToday = GetClicks(context, "today", true);
ViewBag.UniqueClicksWeek = GetClicks(context, "week", true);
ViewBag.UniqueClicksMonth = GetClicks(context, "month", true);

My questions:

Is there any way to further simplify/reduce this code?

perhaps have the total & unique in one value? [total],[unique]

Is it poor practice to pass period as a string and then interrogate it?
Where should you store these kind of database queries? It currently resides in my controller and then returned to the view.


texts:
I wrote a tokenizer/lexer (difference?) for Python in Haskell: this is my code on GitHub.

I already tested it out with some of CPython's standard library scripts, and it doesn't fail. However, it probably outputs non-conforming output. But I don't care about this right now.

What I'm looking for is a general (functional) style review. This is my first time using Parsec and Haskell for something relatively big, so I expect my functional style to be suboptimal.

Significant code snippets:

parseTokens :: LexemeParser [PositionedToken]
parseTokens = do
  P.skipMany ignorable
  tokens <- concat <$> P.many parseLogicalLine
  P.eof
  endIndents <- length . filter (>0) <$> getIndentLevels
  dedents <- mapM position $ replicate endIndents Dedent
  endMarker <- position EndMarker
  return (tokens ++ dedents ++ [endMarker])

parseIndentation :: LexemeParser [PositionedToken]
parseIndentation = mapM position =<< go
  where
    go = do
      curr <- length <$> P.many (P.char ' ')
      prev <- getIndentLevel
      case curr `compare` prev of
        EQ -> return []
        GT -> return [Indent] <* pushIndentLevel curr
        LT -> do
          levels <- getIndentLevels
          when (not $ elem curr levels) (fail $ "indentation must be: " ++ show levels)
          let (pop, levels') = span (> curr) levels
          putIndentLevels levels'
          return $ replicate (length pop) Dedent

parseLogicalLine :: LexemeParser [PositionedToken]
parseLogicalLine = do
  P.skipMany ignorable
  indentation <- parseIndentation
  (indentation ++) <$> begin
  where
    begin = do
      tokens <- P.many1 parsePositionedToken
      let continue = (tokens ++) <$> begin

      implicitJoin <- (> 0) <$> getOpenBraces
      if implicitJoin then do
        whitespace
        parseComment <|> (P.optional backslash *> eol)
        P.skipMany ignorable
        whitespace
        continue
      else do
        whitespace
        explicitJoin <- P.optionMaybe (backslash *> eol)
        case explicitJoin of
          Nothing   -> ((\t -> tokens ++ [t]) <$> position NewLine) <* P.optional eol
          otherwise -> whitespace *> continue

(I was largely inspired by PureScript's lexer, though I probably ended up with something a lot worse.)


texts: Caesar and Vigenère ciphers in Haskell the simple way

texts:
There are two ciphers, Caesar and Vigenère, both with an encoder and a decoder. Both work with spaces and can be passed any case (the output will be always lowercased, though).
I'm a complete Haskell beginner and so my implementations are quite ugly and wordy. I'd welcome any help which would help me refactor the code, making it simpler, elegant and more readable.

I think it could be possible to more reuse and reduce this code. I can't think of any way to do that, though.

EDIT: Zeta's answer is great. I've refactored the following code according to his advice and added a new 'cipher' function which allows the user to create new ciphers. I raised a new question with the updated code, you can see it here.

import Data.Char (toLower, ord, chr)

caesar :: Int -> String -> String
caesar n s = unwords $ map (map chr) coded
  where
    coded = map (map helper) $ words s
    helper = (+) base . flip mod 26 . (+) n . flip (-) base . ord . toLower
    base = ord 'a'

unCaesar :: Int -> String -> String
unCaesar n s = unwords $ map (map chr) decoded
  where
    decoded = map (map helper) $ words s
    helper = (-) base . flip mod 26 . (+) n . (-) base . ord . toLower
    base = ord 'z'

I feel there should be a way to not handle the spaces like this, manually. Maybe zipping over a cycled key, somehow?

import Data.Char (toLower, ord, chr)

vigenere :: String -> String -> String
vigenere k s = unwords $ map (map chr) coded
  where
    coded = zipWith (zipWith helper) (words s) (words $ assign s 0)
    helper x y = base + mod (diff (toLower x) + diff (toLower y)) 26
    base = ord 'a'
    diff = flip (-) base . ord
    assign str i
        | null str = ""
        | head str == ' ' = ' ' : assign (tail str) i
        | otherwise = (k !! i) : assign (tail str) (mod (i + 1) (length k))

unVigenere :: String -> String -> String
unVigenere k s = unwords $ map (map chr) decoded
  where
    decoded = zipWith (zipWith helper) (words s) (words $ assign s 0)
    helper x y = base - mod (base - ord (toLower x) + diff (toLower y)) 26
    base = ord 'z'
    diff = flip (-) (ord 'a') . ord
    assign str i
        | null str = ""
        | head str == ' ' = ' ' : assign (tail str) i
        | otherwise = (k !! i) : assign (tail str) (mod (i + 1) (length k))


texts:
Working on an example from Functional Programming in Scala, I'm working on Option#map2:

override def map2[A, B, C](fa: Option[A],fb: Option[B])(f: (A, B) => C): Option[C] = {
  (fa, fb) match {
    case (None, _) => None
    case (_, None) => None
    case (_, _) => Some(f(fa.get, fb.get)) // runtime-safe get calls
  }
}

Is the above implementation reasonable? I presumed that, if either fa or fb were None, then so should be the returned value. Pattern matching seemed the most clean to me, but perhaps there's a cleaner or more concise way to write this method?


texts:
I have a piece of code that works but, as I start learning OCaml, I am not confortable with the "functionnal style" to write code.

The following code create two threads. One for a tcp server that accepts one client and sends him the "test" string. In the other thread, there is a client that reads in a socket after 2 seconds of wait.

open Sys
open Unix
open Lwt

let host = Unix.inet_addr_loopback (* 127.0.0.1 *)
let port = 6600
let max_pending_request = 10

let () = Lwt_log.add_rule "*" Lwt_log.Info

let send_message oc =
  Lwt_io.write_line oc "test"

let accept_connection conn =
  let fd, _ = conn in
    let oc = Lwt_io.of_fd Lwt_io.Output fd in
    Lwt.on_failure (send_message oc ) (fun e -> Lwt_log.ign_error (Printexc.to_string e));
    Lwt_log.info "New connection" >>= return

let create_server sock =
  Lwt_unix.setsockopt sock SO_REUSEADDR true;
  Lwt_unix.bind sock @@ ADDR_INET(host, port);
  Lwt_unix.listen sock max_pending_request;
  Lwt_unix.accept sock >>= fun conn ->
    accept_connection conn >>= fun () ->
      Lwt.return (Lwt_unix.shutdown sock SHUTDOWN_SEND)

let sock_recv sock maxlen =
  let str = Bytes.create maxlen in
  Lwt_unix.recv sock str 0 maxlen [] >>= fun recvlen ->
    return (String.sub str 0 recvlen)

let sock_read sock =
    Lwt_unix.sleep 2.0 >>= fun () ->
     ignore(Lwt_unix.connect sock @@ ADDR_INET(host, port));
      sock_recv sock 1024 >>= fun answer ->
        Lwt_io.write_line Lwt_io.stdout answer

let () =
  let create_socket () = Lwt_unix.socket PF_INET SOCK_STREAM 0 in
    let server_sock = create_socket () in
    let client_sock = create_socket () in
      let threads = Lwt.join [create_server server_sock;
                              sock_read client_sock] in
        Lwt_main.run threads

I use a lot of ";" and I have the feeling that it indicates that my code is not good (based on the code of others people I have read).

Is there anything in my code that I should avoid or some parts that could be improved?


texts: Elegant way to add a value to a member variable inside a vector

texts:
I need to add an offset to a time variable inside my class.
The code below works, how do i make it more efficient, and elegant.

#include <array>
#include <iostream>
#include <string>
#include <vector>

class Pressure
{
    public:

    Pressure(int date, int time):m_date(date),m_time(time)
    {

    }

    int GetDate()
    {
        return m_date;
    }

    int GetTime()
    {
        return m_time;
    }

    void AddTime(int val)
    {
        m_time += val;
    }

    private:
    int m_date;
    int m_time;

};

int main()
{
  std::vector<Pressure> p;

  // populate the vector with values.
  for(int i=0; i < 10; i++)
  {
    Pressure x(i,i);
    p.push_back(x);
  }

  int offset = 20000;

  // add the offset
  for(int i=0; i < 10; i++)
  {
      p[i].AddTime(offset);
  }

  // display the data
  for(int i=0; i < 10; i++)
  {
    std::cout << p[i].GetDate() << " "  << p[i].GetTime() << "\n";
  }

}


texts:
I'm finding names then going to the corresponding column to get the number, then search for the number in column A. If I find the number then go to the corresponding column, copy and paste it to a different worksheet.

How can I make this code faster and more efficient? I found several examples in here, someone suggested to use Variants as well as UBound() and LBound(). I used it but the performance is still the same: It's taking more than 5 mins to loop through 1 million rows.

 Dim wsheet1 as Worksheet, wsheet2 as Worksheet, lastrow as long, correspondingValue1 as Object, correspondingOffset as Object, searchNum as Object, data1, data1Range as Range, x as Long, y as Long

   Set wsheet1 = ActiveWorkbook.Worksheets("Sheet1")
   Set wsheet2 = ActiveWorkbook.Worksheets("Sheet2")
   Set data1Range =  wsheet2.Range(wsheet2.Range("C1"), wsheet2.Cells(Rows.Count, 1).End(xlUp))
   data1 = data1Range.Value

       For i = 1 To UBound(data1, 1)
            If wsheet2.Cells(i, 3).Value = "Mike" Or wsheet2.Cells(i, 3) = "Sam" Or wsheet2.Cells(i, 3) = "George" Or wsheet2.Cells(i, 3) = "Abrahim" Then
              Set correspondingValue1 = wsheet2.Cells(i, 3)
              Set correspondingOffset = corespondingValue1.Offset(columnoffset:=7)

                If InStr(1, xoffset, "1.") <> 0 Then
                    With wsheet2.Range("a1:a" & lastrow)
                    Set searchNum = .Find(wsheet2.Range("J" & i).Value, LookIn:=xlValues)

               If Not searchNum Is Nothing Then
                    firstAddress = searchNum.Address

                  Do
                     searchNum.Offset(columnoffset:=3).Copy
                       wsheet1.Range("B" & x).PasteSpecial
                  Loop While Not searchNum Is Nothing And searchNum.Address <> firstAddress
             x = x + 1
            End If
        End With
    End If
    End If


texts:
I've got a VARCHAR variable of this kind:

@string = "BLABLA10;GOGOGO30;RES777;ANOTHER;"

(several keyword + number separated by ;)

I need to get the INT value after "RES" in a T-SQL query (using SYBASE).

I thought it would be always 3 characters, so I did:

SELECT @val = CONVERT(INT, LTRIM(RTRIM(SUBSTRING(@string, CHARINDEX(";RES", @string)+4, 3))))

But now, it can be 2 characters (or more) for example... so I need to get the value between RES and the next ;

I've done a complicated query:

CONVERT(INT, LTRIM(RTRIM(SUBSTRING(@string, CHARINDEX(";RES", @string)+4, -4 + CHARINDEX(";", SUBSTRING(@string, CHARINDEX(";RES", @string)+1, 70) )))))

It works but it's horrible to read.

Has anyone an idea for a more readable way than this?

I know that the real problem is that we should not use value in concatenated string, but well it was done that way and I can't change it.


texts:
I have a Calculation class. It is persisted in the DB and users can modify it.

The aim of the CompareWith function is to display to the users which parameters have been changed.

A good part of the function is just the same code duplicated. I have been thinking about a way to abstract it out in a function, but have not been able to figure it out.

How can I improve this function?

Public Class Calculation
    Public Property ValueCalculation As String
    Public Property LowLowLowLimitCalculation As String
    Public Property LowLowLimitCalculation As String
    Public Property LowLimitCalculation As String
    Public Property TargetCalculation As String
    Public Property HighLimitCalculation As String
    Public Property HighHighLimitCalculation As String
    Public Property HighHighHighLimitCalculation As String

    Public Function CompareWith(comparedCalculation As Calculation) As CalculationError
        Dim resultStatus As New CalculationError
        If comparedCalculation Is Nothing Then
            Return CalculationError.NotCreated
        End If

        If Not (ValueCalculation = comparedCalculation.ValueCalculation) Then
            resultStatus = resultStatus Or CalculationError.Value
        End If
        If Not (LowLowLowLimitCalculation = comparedCalculation.LowLowLowLimitCalculation) Then
            resultStatus = resultStatus Or CalculationError.LowLowLowLimit
        End If
        If Not (LowLowLowLimitCalculation = comparedCalculation.LowLowLowLimitCalculation) Then
            resultStatus = resultStatus Or CalculationError.LowLowLimit
        End If
        If Not (LowLimitCalculation = comparedCalculation.LowLimitCalculation) Then
            resultStatus = resultStatus Or CalculationError.LowLimit
        End If
        If Not (TargetCalculation = comparedCalculation.TargetCalculation) Then
            resultStatus = resultStatus Or CalculationError.Target
        End If
        If Not (HighHighHighLimitCalculation = comparedCalculation.HighHighHighLimitCalculation) Then
            resultStatus = resultStatus Or CalculationError.HighHighHighLimit
        End If
        If Not (HighHighLimitCalculation = comparedCalculation.HighHighLimitCalculation) Then
            resultStatus = resultStatus Or CalculationError.HighHighLimit
        End If
        If Not (HighLimitCalculation = comparedCalculation.HighLimitCalculation) Then
            resultStatus = resultStatus Or CalculationError.HighLimit
        End If
        Return resultStatus
    End Function
End Class

<Flags>
Public Enum CalculationError
    NotCreated = 1
    Value = 2
    LowLowLowLimit = 4
    LowLowLimit = 8
    LowLimit = 16
    HighLimit = 32
    HighHighLimit = 64
    HighHighHighLimit = 128
    Target = 256
End Enum

Example of use:

Public Sub Main()
    Dim foo As New Calculation() With {.ValueCalculation = "1+1"}
    Dim bar As new Calculation() With {.ValueCalculation = "2+2"}
    Console.WriteLine(foo.CompareWith(bar).ToString())
    'Output: Value
End Sub


texts: PHP Script - Converting string of calculations to result

texts:
So I am making a little script to convert a string of a basic maths calculation eg:

"2+3+4-2+2-12+42"

and it should return the total.

What I have so far :

<?php

function my_operator($a, $b, $char) {
    switch($char) {
        case '-': return $a - $b;
        case '+': return $a + $b;
        default: return $a;
    }
}

$string = "1+41-3+5-12+5+10";
//Ans = 47

$Arr = str_split($string);
$total = 0;
$cache1 = "";
$cache2 = "";
$lastOperator ="";

foreach ($Arr as $char) {
    if ($char == "+") {
        if ($cache2 == "") {
            $total = $cache1;
        }
        $cache2 = $cache1;
        $cache1 = "";
        $total = my_operator($total, (int)$cache2, $lastOperator);
        $lastOperator = "+";
    } else if ($char == "-") {
        if ($cache2 == "") {
            $total = $cache1;
        }
        $cache2 = $cache1;
        $cache1 = "";
        $total = my_operator($total, (int)$cache2, $lastOperator);
        $lastOperator = "-";
    } else {
        $cache1 = $cache1.$char;
    }
}

$total = my_operator($total, (int)$cache1, $lastOperator);

echo $total;

What are some improvements I can make? Thanks.


texts:
How can I optimize this?

<cfftp connection = "myConnection"
   username = "#username#"
   password = "#password#"
   server = "#server#"

   action = "open"
   timeout = "500"
   stopOnError = "Yes">

<cfloop index="i" from="1" to="#ArrayLen(ImagesArray)#">

    <cfset slocal = "temp\" & ImagesArray[i] >
    <cfset sremoteFile = "Images\" & ImagesArray[i]>

    <cftry>
        <cfftp
            connection = "myConnection"
            action = "getFile"
            name = "uploadFile"
            transferMode = "binary"
            failIfExists = "false"
            localFile = "#slocal#"
            remoteFile = "#sremoteFile#" />
    <cfcatch>
        <cfabort>
    </cfcatch>
    </cftry>

    <cfset files = files & "|" & slocalFile>
    <cfset fileliste = fileliste & arFiles[i] & "|">
</cfloop>

<cfftp connection = "myConnection"
    action = "close"
    stopOnError = "Yes">


texts:
How should I improve my solution for Dining Philosopher's problem?

#include "stdafx.h"
#include "iostream"
#include "vector"
#include "algorithm"
#include "mutex"
#include "chrono"
using namespace std;

class Dining {
public:
    static int starved_threads;
private:
    std::recursive_mutex arbit;
    std::vector<int> chopsticks;
    int count;
public:
    Dining()
    {
        vector<int> v = { 1,2,3,4,5 };
        chopsticks = v;
        count = 0;
    }
private:
    int acquire()
    {
        arbit.lock();
        int x = chopsticks[count%chopsticks.size()];
        chopsticks[count%chopsticks.size()] = 0;
        count++;
        arbit.unlock();
        return x;

    }
    void release(int i)
    {
        arbit.lock();
        chopsticks[i - 1] = i;
        arbit.unlock();
    }

public:
    void eatThink() {
        while (true) {
            int left = 0, right = 0;
            left = acquire();
            if (left != 0)
                right = acquire();
            else {
                if (left != 0)
                    release(left);
            }
            arbit.lock();
            if (left && right)
            {
                cout << "Thread " << std::this_thread::get_id() << "Eating" << endl;
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
                cout << "Thread " << std::this_thread::get_id() << "Releasing" << endl;
            }
            arbit.unlock();

            if (left > 0)
            {
                release(left);
            }

            if (right > 0)
            {
                release(right);
                arbit.lock();
                starved_threads++;
                cout << starved_threads;
                arbit.unlock();
                return;
            }
        }
    }
};

int Dining::starved_threads = 0;

int main()
{

    Dining* philosophers = new Dining();
    int size = 20;
    std::vector<std::thread> threads(size);
    for (int i = 0; i < 5; i++) {
        for (int i = 0; i < size; i++) {
            threads[i] = std::thread(&Dining::eatThink, philosophers);
        }
        for (int i = 0; i < threads.size(); i++) {
            threads[i].join();
        }
    }
    return 0;
}


texts: Monitoring (i.e. loading updates) to log files

texts:
I wrote a simple little script, designed to load some log file. Clearing lines and loading updates is done by double clicking on the log line to clear.

    <meta charset="utf-8">
    <title></title>


texts:
I have a place where i have to include a HTML template.
The HTML is written by employees only but i dont wanna be an idiot and include it without masking|checks :)

It should allow HTML tags only without any attributes.

So no <a href... links and no <div style=... divs or w/e.

My test script:

$string
    = '

    Foo

Bar

    Baz&nbsp;Mmmpf

someting

someting more

even more

    Foo

Foo BarBaz

';

$htmlWhitelist = [
    'u',
    'i',
    'p',
    'strong',
    'ul',
    'li',
];
// replace allowed tags with placeholders
// that not get changed by htmlspecialchars()
foreach ($htmlWhitelist as $tag) {
    $string = str_replace(
        ["<{$tag}>", "</{$tag}>"],
        ["{OPEN}{$tag}{OPEN}", "{CLOSE}{$tag}{CLOSE}"],
        $string
    );
}
// htmlspecialchars() on everything
$string = htmlspecialchars($string);
// put back the allowed tags
foreach ($htmlWhitelist as $tag) {
    $string = str_replace(
        ["{OPEN}{$tag}{OPEN}", "{CLOSE}{$tag}{CLOSE}"],
        ["<{$tag}>", "</{$tag}>"],
        $string
    );
}

I cannot imagine anything could go wrong with this but would like to ask you guys if i missed someting.


texts: Python command line tool for compiling py files to exec files on Mac

texts:
When I used to use a PC I was familiar with py2exe, the mac equivalent I saw most people talking about was py2app — which compiles python to .app files, not .exec files. I was familiar with compiling C files to execs on mac, and I had heard of cython (but I had never used it before), so I figured I could write something to go from python to cython to an exec. I initially did not write this for anyone else to use — but now I'm thinking about packaging it as a pip module.

This is my first time building a command line tool for executing shell commands and messing with files and directories.

"""(PYCX) PYthon to Cython to eXec, a unix command line util
Usage:
  pycx FILES... [-o DIR --show --delete --run]
  pycx --help

Options:
  FILES              one or more python files to compile
  -o --output=DIR    output directory
  -s --show          show output from exec compiling
  -d --delete        delete the c file after compiling exec
  -r --run           run the exec after compiling
  -h --help          show this screen.
"""
import os, re
from docopt import docopt

args = docopt(__doc__)

# the two pathnames below tell gcc where python is so that cython can be compiled to an exec
INCLUDES = '/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/include/python3.7m'
LIBRARY  = '/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib'
HIDEDATA = '&>/dev/null'  # this is used to hide output while compiling C files

for pyFILE in args['FILES']:
    if pyFILE.endswith('.py'):  # file must be a python file
        path, name = os.path.split(pyFILE)  # split full path to seperate path & filename

        cFILE  = re.sub('\.py$', '.c', pyFILE)  # name of the file with .c extension & path
        FILE   = re.sub('\.py$', '', name)  # name of the file with no extension or path

        PATH   = path + '/' if path is not '' else '.'  # if in current directory, path = '.'
        OUTPUT = args['--output'] + '/' if args['--output'] else ''  # blank if no arg given
        SHOW   = HIDEDATA if not args['--show'] else ''  # will hide gcc output if SHOW is false
        # this command will be used to delete the C file
        DELETE = f'find {PATH} -name "{FILE}.c" -type f|xargs rm -f' if args['--delete'] else ''
        RUN    = f'./{OUTPUT}{FILE}' if args['--run'] else ''  # command to run the exec

        commands = [  # cython to make C file, gcc to compile to exec, and some options
            f"cython --embed -o {cFILE} {pyFILE}",  # convert python to cython C file
            # compile cython C file to exec file
            f"gcc -v -Os -I {INCLUDES} -L {LIBRARY} {cFILE} -o {OUTPUT}{FILE} " + \
            # source python & other options -- hide or show, delete C file, run exec
            f"-lpython3.7 -lpthread -lm -lutil -ldl {SHOW}", f"{DELETE}", f"{RUN}"
        ]
        for command in commands:
            os.system(command)  # execute commands above, excluding blank commands
    else:
        print(__doc__)  # show the help menu if user doesn't put a python file

Besides modifying  INCLUDES and LIBRARY to work with varying path locations, are there any other major problems preventing this from working as a python module? Does this even seem like a tool some people might use?


texts:
I wrote this bit of C that prints a half-pyramid,

   *
  **
 ***
****

Here's the main body:

#include <stdio.h>
#define SIZE 4

void printrow(int threshold);

int main()
{
    int i, threshold;

    for (i = 0; i < SIZE; i++) {
        // threshold slides to the left with each iteration:
        // ===|
        // ==|=
        // =|==
        // |===
        threshold = SIZE - (i+1);

        printrow(threshold);
    }

    return 0;
}

And here are two different implementations of printrow. I'm not sure which is the better of the two.

Version one uses the threshold as a slider that divides the row into two smaller loops:

void printrow(int threshold)
{
    int j;

    for (j = 0; j < threshold; j++)
        printf(" ");

    for (j = threshold; j < SIZE; j++)
        printf("*");

    printf("\n");
}

Version two runs a single loop and each iteration checks its position relative to the threshold when determining which character to print:

void printrow(int threshold)
{
    int j;
    char c;

    for (j = 0; j < SIZE; j++) {
        c = (j < threshold) ? ' ' : '*';
        printf("%c", c);
    }

    printf("\n");
}

This is a very small, simple program, but I'm curious which is the better approach, as I'm sure the same scenario can arise on a larger scale.


texts:
Chandan got bored playing with the arrays all the time. Therefore he has decided to buy a string \$S\$ consists of \$N\$ lower case letters. Once he purchased the string, He starts formulating his own terminologies over his string \$S\$. Chandan calls a string str A Balanced String if and only if the characters of the string str can be paritioned into two multisets \$M_1\$ and \$M_2\$ such that \$M_1=M_2\$ .

For example:

Strings like "abccba" , "abaccb" , "aabbcc" are all balanced strings as their characters can be partitioned in the two multisets \$M_1\$ and \$M2\$ such that \$M_1=M_2\$.

$$M1 = {a,b,c} \\
M2 = {c,b,a}$$

whereas strings like ababab , abcabb are not balanced at all.

Chandan wonders how many substrings of his string \$S\$ are Balanced Strings? Chandan is a little guy and do not know how to calculate the count of such substrings.

For input "abccba" Balanced substring are "cc" , "bccb" , "abccba" ie count=3 (Provided as per problem statement discussion) But I guess "aa", "bb", "cc", "abba", "acca", "cbbc" are also balanced sub string for the same input which makes count=6 Any wrong in my interpretation ?

Program

 import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.Scanner;
 import java.util.Set;

    public class BalancedStrings {
    static int  returnbalance(String input){
    HashMap<Character, Integer> characters=new LinkedHashMap<>();
    int count=0;
    Character c=null;
    for(int i=0;i<input.length();i++){
        c=input.charAt(i);
        if(characters.containsKey(c)==true){
            count=characters.get(c);
            characters.put(c, count+1);
        }
        else
            characters.put(c,1);
    }
    int countunique=0;
    Set<Character> s=characters.keySet();
    for(Character cc:s){
        count=characters.get(cc);
        if(count%2==0)
            countunique++;
    }
    if(countunique!=s.size())
        return 0;
    Object[] sar= s.toArray();
    int len=0;
    for(int i=sar.length-1;i>=0;i--){
        len=len+i;
    }

    return len+countunique;

}
public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    int numberOfInputs=in.nextInt();
    in.nextLine();
    for(int i=0;i<numberOfInputs;i++){
        System.out.println(BalancedStrings.returnbalance(in.nextLine()));
    }

}

}


texts:
I am reading the "Clean Code" book and trying refactoring my source code according to the principles "single level of abstraction"/"separation of concerns".

How would you refactor the following code? I am interested in the details like:

How would you separate the abstraction levels?
How many classes would you create?
How would you name the new classes?
How would maybe rename the existing class?
Other things...?

TConditionsUtils = class(TObject)
public
  function GetPolungType(const APolung: String): TPolung;
  function GetPolungTypeName(const APolungType: TPolung): String;
  function GetPolungTypeOfCondition(const AConditionName: String; const AConditions: IGenericList<ICondition>): TPolung;
  function GetPolungTypeNameOfCondition(const AConditionName: String; const AConditions: IGenericList<ICondition>): String;

  function GetBoardType(const ABoardType: String): TBoardType;
  function GetBoardTypeName(const ABoardType: TBoardType): String;
  function GetBoardTypeOfCondition(const AConditionName: String; const AConditions: IGenericList<ICondition>): TBoardType;
  function GetBoardTypeNameOfCondition(const AConditionName: String; const AConditions: IGenericList<ICondition>): String;
end;

For more understanding what the functions do you can check the following code:

literals beginning with c_ are text constants
TBoardType and TPolung are enumerated types
The defined functions are doing nothing else determining from a text a datatype and vice versa
The function GetPolungTypeNameOfCondition and GetBoardTypeOfCondition search for a conditionname in the list and return either a name of the type or an enumarated type

TBoardType = (bt_Unknown = 0, bt_D = 1, bt_K = 2, bt_L = 3, bt_HP = 4);
TPolung = (pUnknown = 0, pCommon_N = 1, pCommon_P = 2);

function TConditionsUtils.GetPolungType(const APolung: String): TPolung;
begin
  if SameText(APolung, c_Polung_commonN) then
    Result := pCommon_N
  else if SameText(APolung, c_Polung_commonP) then
    Result := pCommon_P
  else
    Result := pUnknown;
end;

function TConditionsUtils.GetPolungTypeName(const APolungType: TPolung): String;
begin
  case APolungType of
    pCommon_N: Result := c_Polung_commonN;
    pCommon_P: Result := c_Polung_commonP;
  else
    Result := c_Unknown;
  end;
end;

function TConditionsUtils.GetBoardType(const ABoardType: String): TBoardType;
begin
  if SameText(ABoardType, c_BoardType_D) then
    Result := bt_D
  else if SameText(ABoardType, c_BoardType_K) then
    Result := bt_K
  else if SameText(ABoardType, c_BoardType_L) then
    Result := bt_L
  else if SameText(ABoardType, c_BoardType_HP) then
    Result := bt_HP
  else
    Result := bt_Unknown;
end;

function TConditionsUtils.GetBoardTypeName(const ABoardType: TBoardType): String;
begin
  case ABoardType of
    bt_D: Result := c_BoardType_D;
    bt_K: Result := c_BoardType_K;
    bt_L: Result := c_BoardType_L;
    bt_HP: Result := c_BoardType_HP;
  else
    Result := '';
  end;
end;


texts:
I have the following logic:

bool a;
bool b;
int v = 0;

//code here to set the values of a and b...

if(b)
{
    v = a ? 1 : 2;
}
else
{
     v = a ? 0 : 1;
}

I believe that there may be a way to minimize this logic (or rewrite it in a more clever way) that I am not thinking of.


texts: Is device mounted? Both UUID and device names accepted

texts:
I am trying to write is_device_mounted script, which in turn will serve a greater purpose in my home Linux system.

It does not even have an error reporting function included and as you can see, I have made it clean for readers. My intention here is to review the code for general Linux. But if you are on a *BSD, I would appreciate your feedback too!

The first version of the script follows:

#!/bin/sh

set -eu

is_empty_string() { [ -z "${1}" ]; }
sanitize_device_string() { printf '%s' "${1}" | grep '^/dev/' | head -n 1; }
is_block_device() { [ -b "${1}" ]; }
is_device_uuid_identified() { printf '%s' "${1}" | grep -F '/by-uuid/'; }
translate_uuid_to_device_name() { readlink -f -n /dev/disk/by-uuid/"${1}"; }

is_device_mounted()
{
    if [ -n "${device_name}" ]; then
        # 1. basic regex should be working across platfotms
        #    tested on FreeBSD, OpenBSD, NetBSD with success
        #    I prefer the starting with (^) rather than filtering throung all text
        # 2. /proc/mounts is not available on all *BSDs, needs revision
        proc_mounts=$( grep "^${device_name} " /proc/mounts )
        [ -n "${proc_mounts}" ]
    fi
}

[ "${#}" -ne 1 ] && { echo "Invalid number of arguments."; exit 1; }
readonly raw_input_string=${1}

is_empty_string "${raw_input_string}" && { echo "The given argument is empty."; exit 1; }
readonly device_string=$( sanitize_device_string "${raw_input_string}" )

is_empty_string "${device_string}" && { echo "The given argument is not a device path."; exit 1; }
! is_block_device "${device_string}" && { echo "The given argument is not a block device."; exit 1; }
readonly block_device=${device_string}

if is_device_uuid_identified "${block_device}"
then
    readonly device_name=$( translate_uuid_to_device_name "${block_device}" )
else
    readonly device_name=${block_device}
fi

if is_device_mounted "${device_name}"
then
    echo "The device: ${block_device} IS mounted."
else
    echo "The device: ${block_device} IS NOT mounted."
fi


texts: Text-based menu to manipulate a database text file

texts:
I am making a program that lets a user manipulate a database (a text file).

In the code I am posting, I show only 2 of the menu choices, namely "createdb" and "deletedb", and a few functions I made to desperately make the functions more compact. But my problem is that the pattern is similiar for all the other menu options. I ask the user to either enter the name of the database or "b" to return to the menu, and then check if the file exists.

Is there a way I can easily separate this to make my code more compact? I tried to do this part in the menu and have the choice functions be of type

FilePath -> IO ()

But then my menu looked really terrible. Here is a small part of the code:

type Choice = (String, String, IO ())

choices :: [Choice]
choices =
    [("a", "create a database", createdb),
    ("b", "delete a database", deletedb),
    ("c", "insert an entry to a database", insert),
    ("d", "print a database", selectall),
    ("e", "select entries from a database", select),
    -- more similiar choices

menu :: IO ()
menu = do
    (mapM_ putStrLn . map showChoice) choices
    c <- get "Enter the letter corresonding to the action of choice:"
    case filter ((== c) . fst3) choices of
    [] -> back "Not a valid choice. Try again"
    (_, _, f) : _ -> f

createdb :: IO ()
createdb = do
    n <- maybeName
    if isNothing n then menu else do
    let name = fromJust n
    fp <- maybeFile name
    if isJust fp
    then back $ "Error: \"" ++ name ++ "\" already exist."
    else do
        cols <- get "Enter unique column names in the form n1,n2,...,n (No spaces):"
        let spl = (splitOnComma . toLower') cols
        case filter (== True) (hasDuplicates spl : map (elem ' ') spl) of
            [] -> writeFile (name ++ ".txt") (cols ++ "\n")
            _  -> back "Error: Column names must be unique and have no spaces."

deletedb :: IO ()
deletedb = do
    n <- maybeName
    if isNothing n then menu else do
        let name = fromJust n
        fp <- maybeFile name
        if isJust fp
        then removeFile (fromJust fp)
        else back $ "Error: Could not find " ++ name

maybeName :: IO (Maybe String)
maybeName = do
    input <- get "Enter database name or 'b' to go back to the menu."
    return $ case input of
        "b" -> Nothing
        _   -> Just input

maybeFile :: String -> IO (Maybe FilePath)
maybeFile name = do
    let fn = name ++ ".txt"
    exists <- doesFileExist fn
    return $ if exists then Just fn else Nothing

back :: String -> IO ()
back msg = do
    putStrLn msg
    menu

get :: String -> IO String
get msg = do
    putStrLn msg
    getLine


texts: Production-ready comparison between byte-array and ByteBuffer

texts:
I want to compare the performance difference between using byte[] and ByteBuffer in Java, which approach I should use in my production code. I wrote the following Java sandbox code:

public native int MD_GetHsmInfo(int hsmIndex, int infoType, byte[] value);
public native int MD_TestByteBuffer(int hsmIndex, int infoType, ByteBuffer buf);

//inside main()
byte[] arr = new byte[64];
h.MD_GetHsmInfo(2, 0, arr);
System.out.println(">" + new String(arr) + "<");

ByteBuffer buf = ByteBuffer.allocateDirect(64);
h.MD_TestByteBuffer(2, 1, buf);
System.out.println(">" + StandardCharsets.UTF_8.decode(buf).toString() + "<");

And then I have my C code - this is the one I need help with:

JNIEXPORT jint JNICALL Java_com_sprint_jni_JNISandbox_MD_1GetHsmInfo
    (JNIEnv *env, jobject obj, jint hsmIndex, jint infoType, jbyteArray array)
{
    //printf("This is MD_GetHsmInfo()\n");
    jboolean isCopy;
    jsize len = (*env)->GetArrayLength(env, array);
    jbyte* bp = (*env)->GetByteArrayElements(env, array, &isCopy);
    if (!bp) {
        // exception handling here
        return 0;
    }

    jint ret = MD_GetHsmInfo(hsmIndex, infoType, bp, len);
    int mode = 0;
    // if error code is returned then do not save changes
    if(ret != 0) {
        mode = JNI_ABORT;
    }
    (*env)->ReleaseByteArrayElements(env, array, bp, mode);

    return ret;
}

JNIEXPORT jint JNICALL Java_com_sprint_jni_JNISandbox_MD_1TestByteBuffer
    (JNIEnv *env, jobject obj, jint hsmIndex, jint infoType, jobject buf)
{
    jbyte *bp = (*env)->GetDirectBufferAddress(env, buf);
    jint len = (*env)->GetDirectBufferCapacity(env, buf);
    //printf("length of buffer = %d", len);
    jint ret = MD_GetHsmInfo(hsmIndex, infoType, bp, len);
    return ret;
}

Both functions seem to work fine, but I would like to make both functions production-ready, so that I can demonstrate without bias which approach to use. As I am not too familiar with JNI, it is likely that my code is not written optimally, so I would appreciate any feedback on that too.

Background

In the above snippet, MD_GetHsmInfo is a C function which my Java code needs to call.

MD_RV MD_GetHsmInfo(uint32_t hsmIndex, MD_Info_t infoType, void *pValue, uint32_t valueLen);

pValue is described as such:

  The address of the buffer to hold the information value. The buffer
  must have been allocated by the caller. The size of the buffer is
  determined by the infoType that is being obtained.

MD_RV and MD_Info_t are enums defined as follows:

typedef enum {
    MDI_HSM_DESCRIPTION = 1,
    //...so on
} MD_Info_t;

// similar implementation for MD_RV

The actual implementation of the function resides within a DLL file, but I do not have access to it yet. For now I have written a dummy implementation as follows:

int MD_GetHsmInfo(int hsmIndex, int infoType, void *pValue, int valueLen) {
    //printf("This is dummy implementation of MD_GetHsmInfo()\n");
    char *str;
    if(infoType == 1) {
        str = "info = 1";
    } else if(infoType == 2) {
        str = "info = 2";
    } else {
        str = "no info";
    }

    jbyte *jb = (jbyte*)pValue;
    while(*str) {
        *jb++ = *str++;
    }
    *jb = 0;
    valueLen = strlen(str);

    return 0;
}


texts: Program to find megaPrime numbers between 2 given integers

texts:
A number is said to be megaPrime if it is prime, and all its digits are also prime.

Example:
53 is megaPrime, but 35 is not as it is divisible by 5 and 7.
13 is not a megaPrime number as it contains 1, which is non-prime.
INPUT
Two integer numbers, first and last are entered.
OUTPUT
Display the number of megaPrimes in the inteval between first and last, both inclusive.
CONSTRAINTS
1 <= first <= last <= 10^15
last - first <=  10^9
/* PROGRAM TO FIND MEGA PRIME NUMBERS BETWEEN TWO GIVEN INTEGERS */

#include<stdio.h>
int isPrime(int);
int isMegaPrime(int);

int main(void)
{
int i=0,st,sp,count=0;
    scanf("%d%d",&st,&sp);
    for(i=st;i<=sp;i++){
        if((i%2)!=0 && isMegaPrime(i)==1)
            count++;
    }

    printf("%d",count);
    return 0;
}

int isPrime(int n)
{
    int i=0,flag=0;
    if(n==1)
        return 0;
    else
    {
        int t=sqrt(n);
        for(i=2;i<=t;i++){
            if((n%i)==0){
                flag=1;
                break;
            }
        }
    }
    if(flag==1)
        return 0;
    else
        return 1;
}

int isMegaPrime( int n)
{
    int i=0,flag=0,temp=0;
    if(isPrime(n)==0)
        return 0;
    else{
        while (n!=0){
            temp=n%10;
            flag=isPrime(temp);
            if(flag==0)
                return 0;
            n/=10;

        }
    }
    if(flag==1)
        return 1;
    else
        return 0;
}

Please suggest the possible optimizations.


texts: Asking a user for the capital city of Peru, South America

texts:
Can this Python code be written in a more Pythonic way?

'''
This scripts ask a user for the capital city of Peru, South America
'''

question = 'What is the capital city of Peru?'
answer = 'Lima'

# Ask question
print question

# Game continues as long as question is not answered
# Game ends after 3 failed attempts
end_game = False

# User has 2 attempts after entering the first wrong answer
attempts = 2

while end_game == False:
    # Get user answer
    user_answer = raw_input('Enter your answer: ').capitalize()

    # Validate users anser
    if user_answer == answer:
        print 'You got it right'
        end_game = True
    else:
        if attempts > 0:
            print 'Wrong! Try again. You have %d attempts left' %(attempts)
            attempts -= 1
        else:
            print 'You have no more attempts remaining'
            print 'The correct answer is %s' %(answer)
            print 'Oops!!! Game ended'
            end_game = True


texts:
I am trying to do a self-join.  I generated this migration to make a
correct primary.  This code works, but I'm not sure if this is the best way to do things.

class CreateFeedstocks < ActiveRecord::Migration[5.0]
  def change
    create_table :feedstocks do |t|
      t.string :code
      t.float :measure_one
      t.float :measure_two
      t.float :measure_three
      t.string :description
      t.integer :primary_feedstock_id, index: true

      t.timestamps
    end
    add_foreign_key :feedstocks, :feedstocks,
                     column: :primary_feedstock_id,
                     primary_key: :id
  end
end

One feedstock has one primary_feedstock and one primary_feedstock has
many feedstocks.


texts:
This script checks if parentheses are balanced. I wonder if there is something that can be improved here including ES6 features.

function isBalanced(str) {
    var stack = [];
    const allowedSymbols = '()[]<>';

    for(let i = 0, l = str.length; i < l; i++) {
        var c = str[i];
        var isOpen;
        var symbolPosition = allowedSymbols.indexOf(c);

        if(!~symbolPosition) {
            continue;
        }

        isOpen = symbolPosition % 2 ? false : true;

        if(isOpen) {
            stack.push(c);
        } else {
            if(stack.length < 1 || allowedSymbols.indexOf(stack.pop()) !== symbolPosition - 1) {
                return false;
            }
        }
    }

    return stack.length < 1;
}

console.log('()', isBalanced('()')); //true
console.log(')(', isBalanced(')(')); //false


texts: Forming error messages from a multidimensional associative array

texts:
I'm working with an input array, which is 3 levels deep, and creating error message strings accordingly in a separate output array.  Below is the code.

$e['invalid']['key'][] = 'a123';
$e['invalid']['key'][] = 'a456';
$e['invalid']['color'][] = 'red';
$e['missing']['key'][] = 'b72';
$e['missing']['color'][] = 'blue';
$e['missing']['color'][] = 'green';
echo '
' . print_r($e, 1) . '
';

function generateErrorMessages($e)
{
    $errors;
    foreach ($e as $type => $array)
    {
        foreach ($array as $key => $values)
        {
            foreach ($values as $v)
            {
                switch($type)
                {
                    case 'invalid':
                                    $errors[$type][$key][] = $v . ' is not a valid ' . $key;
                                    break;
                    case 'missing':
                                    $errors[$type][$key][] = $v . ' is a required ' . $key . ' - other functions have dependencies on it';
                                    break;
                    default:
                                    // do nothing
                }
            }
        }
    }
    return $errors;
}

$msgs = generateErrorMessages($e);
echo '
' . print_r($msgs, 1) . '
';

While this achieves the desired outcome, the nested foreach loops in the generateErrorMessages() method seem onerous and difficult to read.  Is there a more concise way to generate the error messages?

Here is a screenshot of the input array:

Here is a screenshot of the output array:


texts: Best way to catch API errors and log responses when calling via helper function

texts:
I'm trying to add error handling and response logging for API calls. The way I have my application (chatbot) set up is that a helper function is called from the main dialog, and that helper function calls the API. I believe this is standard practice. What I'm not sure on is how I should be catching errors in the process and where the appropriate point to do various logging is. I've considered the approach of putting all error catching in the helper, but if the API call fails, I still need an exception path in my main dialog. So what I've settled on is a try/catch block to call the function, which will catch API call failure in the helper. If the API call is successful, I'm logging the result from the helper. If the API call fails, I'm logging the failure from the main dialog. Here are the appropriate code snippets:

statusDialog.js

try {
    const orderResponse = await orderStatusHelper.getStatus(orderNumber);
} catch(err) {
    appInsightsClient.trackTrace({
        message: `API Response - ${path.basename(__filename)}`,
        severity: 3,
        properties: {'error':err.message,'callStack':err.stack}
    });
}

orderStatusHelper.js

let response = await request ({
    url:url,
    method: 'POST',
    headers: headers,
    json: postData
});

// If call fails, main function goes to catch block
// If call succeeds, log response and return result
appInsightsClient.trackTrace({
    message: `API Response - ${path.basename(__filename)}`,
    severity: 1,
    properties: {response}
});
return response;

I would appreciate feedback on

If this is the proper method to catch errors when I'm calling a function that's calling an API
If I am logging the response (or lack thereof) in the right spot


texts: Swift iOS app for showing motivational quotes, with multiple screens

texts:
I'm one month into self-learning Swift, and I would like some advice to improve my coding skills.

I have listed 2 situations that I think I need to improve. I'd like some feedback focusing on my use of static variables for changing data between ViewControllers and subviews.

1.0 Image 1 shows the app flow (Left = HomeController), middle = MenuController, Right = FavouritesController)

Image 1

In HomeController there is a UIView subview. From this subview the current quote (HomeController.homeControllerCurrentQuote) displayed can be saved to favourites array. This is a static array defined in FavouritesController.

The functions below are called from the subview within HomeController. I made HomeController.homeControllerCurrentQuote static because the subview needs access to it. Likewise for FavouritesController.favourites.

In FavouritesController the data contained in FavouritesController.favourites array is used to populate a tableVIew.

// FavouritesController.favourites is static variable!
// HomeController.homeControllerCurrentQuote is static variable! updated as user scrolls

func handleFavourite() {
    let favourites = FavouritesController.favourites
    if favourites.contains(HomeController.homeControllerCurrentQuote) {
    removeFromFavourites()
    } else { FavouritesController.favourites.append(HomeController.homeControllerCurrentQuote)
        UserDefaults.standard.set(try? PropertyListEncoder().encode(FavouritesController.favourites), forKey:"myKey")
    }
}

func removeFromFavourites() {
    var tempArray: [Quote] = [.init(category: "", quote: "", author: "")]
    tempArray = FavouritesController.favourites
    let searchString = HomeController.homeControllerCurrentQuote.quote
    var filteredArray = [Quote]()
    filteredArray = tempArray.filter( { !$0.quote.contains(searchString) } )
    UserDefaults.standard.set(try? PropertyListEncoder().encode(filteredArray), forKey:"myKey")
}

// update static variable on HomeController
internal override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
....
    HomeController.homeControllerCurrentQuote = Quote(category: cell.categoryLabel.text ?? "", quote: cell.quoteLabel.text ?? "", author: author)
....
}

Should I change how this is done? I don't like the use of static variables but as it's my first app I was more focused on getting it done rather than how it was done. Is it a good case for using a delegate and protocol to communicate between the views (I've never used this before)? If so how would I start to think about implementing it or, as it works, is what I've done satisfactory?

2.0 When the app launches on HomeController required data is generated and is stored in a static variable.

                          //  [category : [quote  : author]]
static var xQuotesByCategory: [String   : [String : String]] = [:]

I make this data static because when I instantiate HomeController again from another controller, I don't want to have to refetch the data. I want to retrieve it once. Then when a new instance of HomeController is called I can make this check which should return false. Is this an appropriate use of a static variable?

if HomeController.xQuotesByCategory.values.isEmpty {
    ... fetchJson()
}

Following on from this, as HomeController.xQuotesByCategory is static, on CategoriesController I can call

var categories = Array(HomeController.xQuotesByCategory.keys)

This gets only the outer keys (categories) which I use to create the collectionView cells with the text and images shown in image 2. Again, same question, is this appropriate use of a static variable? Is there better way to ensure data is loaded only once and then pass the keys to CategoriesController in a different way when it's required?

If you'd like to try running the app, there is a test version available on TestFlight. Let me know and I can add you in TestFlight!


texts: Checking to see if value is in datalist or not

texts:
I have a form that is used for inputting data, one of the fields is a datalist with around 6000 options in it, I needed to check that the value entered in to the datalist is actually in the list, here is what I came up with,

$('#submit').on('click', function (e) {
    var datalistval = $('#ItemSelect').val().split('|');
    datalistval = $.trim(datalistval[0]);

    var IsinList;
    $("#jobs option").each(function ()
    var arraylist = $(this).val().split('|');
    arraylist = $.trim(arraylist[0]);
    if ($(this).val() != datalistval) {
        console.log($(this).val());
        console.log("Not there ");
    } else {
        console.log("there");
        IsinList = true;
        return false;
    }
    });

if (IsinList !== true) {
    alert('Please check the product code as it is not in the list, make sure you select an option in the list ');
    e.preventDefault();
}
});

Is this the most optimum way of doing this? Is there anything I can do to improve it?


texts:
I was writing a program that used a bit of recursion with objects, and it wasn't working at all. After debugging I realized that JS's evil scope was playing nasty tricks.

To spare you guys a wall of text code, I wrote a smaller program:

//Class definition and framework:
TestClass=function(label,level){
    this.label=label;
    this.level=level;

}

TestClass.prototype.recur=function(){
   r=Math.random(); //initialise a local variable
   document.write(this.label+":"+r+"
");
   if(this.level==0){return;} //exit after this if level==0, we don't want to blow up the call stack
   x=new TestClass("inner1",0)
   x.recur();
   document.write(this.label+":"+r+"
"); //Check if r has changed
   y=new TestClass("inner2",0)
   y.recur();
   document.write(this.label+":"+r+"
"); //check if r has changed
}

//Run this:
a=new TestClass("outer",1);
a.recur();

Output:

outer:0.5542382076382637
inner1:0.7689833084587008
outer:0.7689833084587008
inner2:0.24465859192423522
outer:0.24465859192423522

As one can see, the value of r in the outer function has changed. From this, I see that JS joins the scope of a function with a function (recursively) called in itself. This seems slightly icky and illogical.

My own solution to this was to make every locally initialized variable a member variable. In this example, I would replace all instances of r with this.r.

Then, since I like my objects to be clean, I wrote a garbage collector. Final code would be somewhat like:

//Class definition and framework:
TestClass=function(label,level){
    this.label=label;
    this.level=level;

}
TestClass.allowedProperties=["label","level"] // do NOT blow these up during garbage collection
TestClass.prototype.recur=function(){
   this.r=Math.random(); //initialise a local variable
   document.write(this.label+":"+this.r+"
");
   if(this.level==0){return;} //exit after this if level==0, we don't want to blow up the call stack
   x=new TestClass("inner1",0)
   x.recur();
   document.write(this.label+":"+this.r+"
"); //Check if r has changed
   y=new TestClass("inner2",0)
   y.recur();
   document.write(this.label+":"+this.r+"
"); //check if r has changed
}

//Garbage collector:
TestClass.prototype.cleanup=function(){
    for(x in this){
        if(TestClass.allowedProperties.indexOf(x)==-1){
            delete this[x];
        }
    }
}

//Run this:
a=new TestClass("outer",1);
a.recur();
a.cleanup();

This manages the job reasonably well, and cleans up after itself. But I feel that this is a rather inelegant way to do it. Is there a better, elegant way to deal with this form of evil javascript scoping?


texts:
I want a general criticism on this code. Using external modules is not an option, I can only use what comes with CPython.

from collections import Counter
from typing import Sequence, NamedTuple

Coordinates = Sequence[float]

class KNNPoint(NamedTuple):
    coords: Coordinates
    classif: str

def predict(target: Coordinates, points: Sequence[KNNPoint], k: int) -> str:
    '''
    Applies the K-Nearest Neighborhood algorithm in order to find the
    classification of target.

    - target: Single data to be classified.
    - points: Collection of data which classifications are known.
    - k: The number of closest neighbors to be used.
    '''
    def distance(p: KNNPoint) -> float:
        return sum((a - b) ** 2 for a, b in zip(target, p.coords))

    neighbors = sorted(points, key=distance)
    counter = Counter(x.classif for x in neighbors[:k])

    return counter.most_common(1)[0][0]

If you'd like to run it, this gist has everything ready. it uses a dataset of mobile phones. (This gist shall not be reviewed)


texts:
I've written a relatively small abstract class in Java which keeps track of all instances of it's sublasses. Any class which extends this abstract class will automatically have all its instances stored (via a weak reference) in a Set, which can be retrieved if a subclass ever wants to get references to all it's instances.

Although this class is relatively short and simple, I have never made anything like it and so I want to ensure that I'm not doing something terribly wrong or giving in to any bad practices:

import java.util.*;

public abstract class InstanceRecorder {
    private static Map<Class<? extends InstanceRecorder>, Set<InstanceRecorder>> instances;

    static {
        instances = new HashMap<>();
    }

    {
        instances.putIfAbsent(this.getClass(), Collections.newSetFromMap(new WeakHashMap<>()));
        instances.get(this.getClass()).add(this);
    }

    protected static int countInstances(Class<? extends InstanceRecorder> key) {
        if (instances.containsKey(key))
            return instances.get(key).size();
        return 0;
    }

    @SuppressWarnings("unchecked")
    protected static <T extends InstanceRecorder> Set<T> getInstances(Class<T> key) {
        if (instances.containsKey(key))
            return Collections.unmodifiableSet((Set<T>) instances.get(key));
        return new HashSet<>();
    }
}

As I said above, I've never made a class like this before and so any feedback or insight would be greatly appreciated.


texts:
This is a chunk of code I wrote for a job interview at some point - it is a remote key-value storage REST API supporting CRUD operations.

Maybe anyone has some feedback on this? It would be very helpful for me.

I did not attach the tests, since it might be a little bit too much code. You don't have to review both files - even commenting on just one can be extremely helpful.

remotekvs.py

# -*- test-case-name: tests.remotekvs_test.RemoteKVSTest -*-

import json
import inspect

from twisted.internet import reactor
from twisted.web.resource import Resource
from twisted.web.server import Site

from keyvaluestorage import KeyValueStorage

class RemoteKVSResource(Resource):
    """
    This is a Twisted Resource object used to serve requests for
    KeyValueStorage operations. It supports POST, GET, PUT and DELETE
    request methods and replies in JSON.
    """
    isLeaf = True

    def __init__(self):
        self.kvs = KeyValueStorage()

    def render(self, request):
        operations = {
            'POST': 'create',
            'GET': 'read',
            'PUT': 'update',
            'DELETE': 'delete'}
        if request.method in operations.keys():
            response = {
                'success': True}
            try:
                operation = getattr(self.kvs, operations[request.method])
                args = {k: v[0] if isinstance(v, list) else v
                        for k, v in request.args.items()}
                result = operation(**(args))
                if result is not None:
                    response['result'] = result
            except (TypeError, KeyValueStorage.KeyAlreadyExistsError,
                    KeyValueStorage.InvalidKeyError), exception:
                response['success'] = False
                response['error'] = exception.__class__.__name__
                if isinstance(exception, TypeError):
                    response['error_message'] = (
                        "Valid request parameters: %s." % (
                            ', '.join(inspect.getargspec(operation)[0][1:])))
                else:
                    response['error_message'] = str(exception)
        else:
            response = {
                'success': False,
                'error': 'InvalidRequestMethod',
                'error_message': (
                    "Valid request methods: POST, GET, PUT, DELETE.")}
        return json.dumps(response)

if __name__ == '__main__':  # pragma: no cover
    site = Site(RemoteKVSResource())
    reactor.listenTCP(2048, site)
    reactor.run()

keyvaluestorage.py

# -*- test-case-name: tests.keyvaluestorage_test.KeyValueStorageTest -*-

class KeyValueStorage(object):
    """The most basic key-value storage, supports all 4 CRUD operations."""

    class KeyAlreadyExistsError(Exception):
        """Key you are trying to create already exists in the database."""

    class InvalidKeyError(Exception):
        """Key you are trying to access does not exist in the database."""

    def __init__(self):
        self.storage = {}

    def create(self, key, value):
        if key in self.storage.keys():
            raise self.KeyAlreadyExistsError(
                ("Key already exists. KeyValueStorage does not allow "
                 "duplicate keys."))
        self.storage[key] = value

    def read(self, key):
        try:
            return self.storage[key]
        except KeyError:
            raise self.InvalidKeyError(
                "Key does not exist. You can not read by a nonexistent key.")

    def update(self, key, value):
        if key not in self.storage.keys():
            raise self.InvalidKeyError(
                "Key does not exist. You can not update by a nonexistent key.")
        self.storage[key] = value

    def delete(self, key):
        try:
            del self.storage[key]
        except KeyError:
            raise self.InvalidKeyError(
                "Key does not exist. You can not delete by a nonexistent key.")


texts:
I'm making a wrapper for querying the database so that I can more easily control the flow of database management and to make it easier for me to write data beans around my database.  This code is going to be used a ton so I'm looking to make it as clean as possible.

/**
 * Query the database.
 *
 * @param sql
 *            The query statement
 * @return List of rows returned by the query.
 */
public List<Map<String, Object>> query(String sql) {
    return this.query(sql, null);
}

/**
 * Query the database.
 *
 * @param sql
 *            The query statement
 * @param params
 *            The prepared statement parameters (in order).
 * @return List of rows returned by the query.
 */
public List<Map<String, Object>> query(String sql, Object[] params) {
    final String METHODNAME = "query";
    List<Map<String, Object>> resList = null;

    try {
        if (conn != null && !conn.isClosed()) {
            resList = new ArrayList<Map<String, Object>>();

            PreparedStatement stmt = conn.prepareStatement(sql);
            if (params != null && params.length > 0) {
                for (int i = 1; i <= params.length; i++) { // 1 based, not 0
                    stmt.setObject(i, params[i - 1]);
                }
            }

            ResultSet res = stmt.executeQuery();

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

                for (int i = 1; i <= res.getMetaData().getColumnCount(); i++) {
                    String key = res.getMetaData().getColumnName(i);
                    Object val = res.getObject(i);
                    row.put(key, val);
                    resList.add(row);
                }
            }

        } else {
            logger.log(LogLevel.ALL, CLASSNAME, METHODNAME, "Attempted to run query when "
                    + "there was no established connection to the database.");
        }
    } catch (Throwable e) {
        logger.log(LogLevel.ERROR, CLASSNAME, METHODNAME,
                "An error occurred when trying to run the query.");
    }

    return resList;
}


texts:
I need to send and receive data. Here is solution for my original problem. I want to know how safe my finished code is and how I can improve it.

int sslWrite(SSL *ssl, const std::string &data)
{
    return sslWrite(ssl, &data[0], data.size());
}

int sslWrite(SSL *ssl, const void *buf, unsigned num)
{
    const int INT_SIZE = sizeof(int);
    const int numv = INT_SIZE + num;

    std::vector<char> bufv(numv);

    memcpy(&bufv[0], &numv, INT_SIZE);
    if (num != 0) {
        memcpy(&bufv[INT_SIZE], buf, num);
    }

    int n = 0;
    while (n < num) {
        int w = SSL_write(ssl, &bufv[0], numv - n);
        if (w < 0) {
            return 0;
        }
        n += w;
    }

    return n;
}

const int BUF_INIT_SIZE = 0x10000;

std::vector<char> sslRead(SSL *ssl)
{
    const int INT_SIZE = sizeof(int);
    std::vector<char> bufv(BUF_INIT_SIZE);

    int m = SSL_read(ssl, &bufv.at(0), BUF_INIT_SIZE);

    if (m == 0) {
        return std::vector<char>();
    }

    if (m < 0) {
        throw std::runtime_error("m < 0");
    }

    const int n = *reinterpret_cast<int *>(&bufv[0]);
    bufv.resize(n);

    while (m < n) {
        int k = SSL_read(ssl, &bufv.at(m), n - m);
        if (k < 0) {
            throw std::runtime_error("k < 0");
        }
        m += k;
    }

    bufv.resize(m);

    if (m < INT_SIZE) {
        throw std::runtime_error("m < INT_SIZE");
    }

    bufv.erase(bufv.begin(), bufv.begin() + INT_SIZE);
    return bufv;
}


texts: Givens QR decomposition in R or C++: poor performance (or lack thereof) for rectangular matrices

texts:
My own Givens-based QR decomposition function in R (pseudocode from Politecnico of Turin's math department) is the following:

>Givens.fn<-function(V) {

   tol<-1.0*10^-14
   m<-dim(V)[1]
   n<-dim(V)[2]

   spId<-bandSparse(m,m,0,list(rep(1, m+1))) # computed just once
   Q<-spId
   R<-V
   sapply(1:n, function(j){
      if (j<m) {
         vapply((j+1):m, function(i){          # vectorized internal loop
         if(abs(R[i,j])>tol) {
            G<-spId
            x<-R[j,j]
            y<-R[i,j]
            norm<-sqrt(x^2+y^2)
            c<-x/norm
            s<-y/norm
            G[j,j]=c
            G[i,i]=c
            G[j,i]=s
            G[i,j]=-s
            Q<<-G%*%Q
            R<<-G%*%R
         }
         return(1)                   # --> saves 15% execution time!
      },FUN.VALUE=1.0)
   }
})

Q<-t(Q)

return(list(Q,R))
}

It works fine, but the givens() function provided in R by pracma is 134x faster on an total elapsed time around 10" (on my intel i5-3570 4core, 8GB desktop):

>m<-20; n<-20
>set.seed(1)
>X <- as.matrix(replicate(n, runif(m)))
>library(rbenchmark)
>library(pracma)
>benchmark(Givens.fn(X),
           givens(X),
           order = "elapsed",
           replications = 10)

          test replications elapsed relative user.self sys.self user.child sys.child
2    givens(X)           10    0.08    1.000      0.08     0.00         NA        NA
1 Givens.fn(X)           10   10.77  134.625     10.69     0.08         NA        NA

Unfortunately, the pracma version accepts just square matrices, which is not my case. Any further code improvements? Any other Givens-based QR functions (even in C++)? Thanks.


texts: Function to parse a Javascript object and return a CSV

texts:
This function converts a Javascript Object into a CSV.

var dataFromAPI = [{"name":"first"},{"name":"sec,ond"},{"name":"third 'jibberish"},{"name":"fourth, jibberish"}]

function convertToCSVandDownload(objArray) {
    var csvOutput = "";
    Object.keys(objArray).forEach(function(key) {
      if (csvOutput.length == 0) {
        csvOutput = "Index,Field Value\n";
        csvOutput = csvOutput + JSON.stringify(key) + "," + JSON.stringify(objArray[key]["name"]) + "\n";
      } else {
        csvOutput = csvOutput + JSON.stringify(key) + "," + JSON.stringify(objArray[key]["name"]) + "\n";
      }
    })
    return csvOutput;
}

console.log(convertToCSVandDownload(dataFromAPI));


texts: "MathChallenge" game for sums with 4 operators

texts:
I am trying to start learning Python using Learn Python the Hard Way. I wrote my first game that works as far as tested. It was done as an exercise for this.

Please give me some constructive criticism on this program on sections and areas where I can improve. I realise that my object-oriented programming specifically, and my programming in general, still needs lots of work:

"""
MathChallenge:
A game randomly creating and testing math sums with 4 operators: addition, subtraction, multiplication and division.
Difficulty levels are incremented after each correct answer.
No more than 3 incorrect answers are accepted.
"""

from random import randint, choice

class Math(object):
    """Class to generate different math sums based on operator and difficulty levels"""

    def __init__(self):
        """To initialise difficulty on each run"""
        self.difficulty = 1

    def addition(self, a, b):
        """To return 'addition', '+' sign , and answer of operation"""
        return ('addition', '+', a+b)

    def subtraction(self, a, b):
        """To return 'subtraction', '-' sign , and answer of operation"""
        return ('subtraction', '-', a-b)

    def multiplication(self, a, b):
        """To return 'multiplication', '*' sign , and answer of operation"""
        return ('multiplication', '*', a*b)

    def division(self, a, b):
        """To return 'division', '/' sign , and answer of operation"""
        return ('division', '/', a/b)

    def mathsum(self, difficulty):
        """Function that generates random operator and math sum checks against your answer"""

        print "Difficulty level %d." % difficulty

        #let's initialize some random digits for the sum
        a = randint(1,5)*difficulty
        b = randint(1,5)*difficulty

        #Now let's choose a random operator
        op = choice(self.operator)(a, b)

        print "Now lets do a %s calculation and see how clever you are." % op[0]
        print "So what is %d %s %d?" % (a, op[1], b)

        correct = False
        incorrect_count = 0                         #No more than 3 incorrect answers
        while not correct and incorrect_count<3:
            ans = int(raw_input(">"))

            if ans == op[2]:
                correct = True
                print "Correct!"
                self.difficulty += 1
                self.mathsum(self.difficulty)       #Restart the function with higher difficulty

            else:
                incorrect_count += 1
                if incorrect_count == 3: print "That's 3 incorrect answers.  The end."
                else: print "That's not right.  Try again."

class Engine(Math):
    """Game engine"""

    def __init__(self):
        """To initialise certain variables and function-lists"""

        #Initialise list of math functions inherited to randomly call from list
        self.operator = [
            self.addition,
            self.subtraction,
            self.multiplication,
            self.division
            ]

        #Initialise difficulty level
        self.difficulty = 1

        print "Welcome to the MathChallenge game. I hope you enjoy!"

    def play(self):
        """To start game"""

        #start game
        self.mathsum(self.difficulty)

        #print returned difficulty level achieved
        print "Difficulty level achieved: ", self.difficulty

# Start game
game = Engine()
game.play()


texts:
I've seen few ways of processing forms with PHP. Whenever I am working with a form, I typically have two files: one for displaying the information (e.g. form.php) and the other for processing information (e.g. process_form.php). The latter uses sessions and simply redirects to the appropriate page depending on if the information submitted has been validated correctly or not. Below is a simple example of how I normally do things.

Form.php

<form name="form" action="process_form.php" method="POST">

  <? $field = 'name'; ?>
  <label for="<?= $field ?>">What is your name?
  <input type="text" id="<?= $field ?>" name="<?= $field ?>"
    value="<?= !isset($_SESSION['form'][$field]) ? $_SESSION['form'][$field] : '' ?>" maxlength="60" />
  <? if (!isset($_SESSION['errors'][$field])) { ?>
  <label class="error" for="<?= $field ?>"><?= $_SESSION['errors'][$field] ?>
  <? } ?>

  <? $field = 'age'; ?>
  <label for="<?= $field ?>">What is your age?
  <input type="text" id="<?= $field ?>" name="<?= $field ?>"
    value="<?= isset($_SESSION['form'][$field]) ? $_SESSION['form'][$field] : '' ?>" maxlength="2" />
  <? if (isset($_SESSION['errors'][$field])) { ?>
    <label class="error" for="<?= $field ?>"><?= $_SESSION['errors'][$field] ?>
  <? } ?>

  <? $field = 'email'; ?>
  <label for="<?= $field ?>">What is your email?
  <input type="text" id="<?= $field ?>" name="<?= $field ?>"
    value="<?= isset($_SESSION['form'][$field]) ? $_SESSION['form'][$field] : '' ?>" maxlength="100" />
  <? if (isset($_SESSION['errors'][$field])) { ?>
    <label class="error" for="<?= $field ?>"><?= $_SESSION['errors'][$field] ?>
  <? } ?>

  <input type="submit" value="Submit Your Information" />
  <input type="hidden" name="hid_submit" value="1" />

</form>
<?
if (isset($_SESSION['form'])) unset($_SESSION['form']);
if (isset($_SESSION['errors'])) unset($_SESSION['errors']);
?>

Process_form.php

$redirect_page = 'form.php';

$form   = array();
$errors = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $hid_submit = isset($_POST['hid_submit']) ? $_POST['hid_submit'] : NULL;

    if ($hid_submit) {

        $form['name'] = isset($_POST['name']) ? trim($_POST['name']) : '';
        $form['age'] = isset($_POST['age']) ? trim($_POST['age']) : '';
        $form['email'] = isset($_POST['email']) ? trim($_POST['email']) : '';

        // validate fields
        if (!valid($form['name'], 'name')) $errors['name'] = 'Please enter a valid name.';
        if (!valid($form['age'], 'age')) $errors['age'] = 'Please enter a valid age.';
        if (!valid($form['email'], 'email')) $errors['email'] = 'Please enter a valid email.';

        if (count($errors)) {
            $_SESSION['form']   = $form;
            $_SESSION['errors'] = $errors;
        } else {
            $redirect_page = 'another_page.php';
        }
    }
}

redirect($redirect_page);

I find the following approach has worked well in most situations, however I am always looking for better ways to improve.


texts:
I'm trying to build a ThreadPoolExecutor singleton to use it across my app. I'm very new to this concept and after going through Google docs I have created this:

public class MyThreadPoolExecutor {

    // Sets the amount of time an idle thread will wait for a task before terminating
    private static final int KEEP_ALIVE_TIME = 1;

    // Sets the Time Unit to seconds
    private static final TimeUnit KEEP_ALIVE_TIME_UNIT;

    // Sets the initial threadpool size to 8
    private static final int CORE_POOL_SIZE = 8;

    // Sets the maximum threadpool size to 8
    private static final int MAXIMUM_POOL_SIZE = 8;    // A static block that sets class fields

    private final BlockingQueue<Runnable> MyBlockingQueue;

    // A managed pool of background download threads
    private final ThreadPoolExecutor MyPoolExecutor;

    // A single instance of PhotoManager, used to implement the singleton pattern
    private static MyThreadPoolExecutor MyThreadPoolInstance = null;

    static {

        // The time unit for "keep alive" is in seconds
        KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;

        // Creates a single static instance of PhotoManager
        MyThreadPoolInstance = new MyThreadPoolExecutor();
    }

    private MyThreadPoolExecutor() {
        MyBlockingQueue = new LinkedBlockingQueue<Runnable>();

        MyPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE,
                KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, MyBlockingQueue);
    }

    public static MyThreadPoolExecutor getInstance() {

        return MyThreadPoolInstance;
    }

    public void queueJob(Runnable r){

        MyPoolExecutor.execute(r);
    }

}

And I'm using it like this throughout the app:

            MyThreadPoolExecutor threadPool = MyThreadPoolExecutor.getInstance();
            threadPool.queueJob(new MyRunnable());

It looks fine to me, but I can't find good reference of how to do it. Is the above correct, or is it the right way to implement such a thing?