texts: Create MD5 hash list of big memory mapped files

texts:
I wrote this class:

public class MediaFile : IDisposable
{

    private const int SECTION_SIZE = 8192;

    public string FilePath { get; private set; }
    public List<byte[]> Checksums { get; private set; }

    private FileInfo fileInfo;
    private MemoryMappedFile memoryMappedFile;

    public MediaFile(string filePath)
    {
        if (!File.Exists(filePath))
            throw new FileNotFoundException($"{filePath} was not found!");

        this.FilePath = filePath;
        this.Checksums = null;

        this.fileInfo = new FileInfo(filePath);
        this.memoryMappedFile = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open);

        this.Checksums = this.GenerateChecksums();
    }

    public void Dispose()
    {
        this.memoryMappedFile.Dispose();
    }

    public byte[] Read(long offset, int size)
    {
        using (MemoryMappedViewStream memoryMappedViewStream = this.memoryMappedFile.CreateViewStream(offset, size, MemoryMappedFileAccess.Read))
        using (BinaryReader binaryReader = new BinaryReader(memoryMappedViewStream))
            return binaryReader.ReadBytes(size);
    }

    private List<byte[]> GenerateChecksums()
    {
        List<byte[]> checksums = new List<byte[]>();

        double sectionsCalc = this.fileInfo.Length / (double) SECTION_SIZE;

        long normalSizedSectionCount = (long) Math.Floor(sectionsCalc);
        int lastSectionSize = (int) ((sectionsCalc - normalSizedSectionCount) * (double) SECTION_SIZE);

        using (MD5 hashProvider = MD5.Create())
        {
            for (long i = 0; i < normalSizedSectionCount; i++)
                checksums.Add(hashProvider.ComputeHash(this.Read(i * SECTION_SIZE, SECTION_SIZE)));

            checksums.Add(hashProvider.ComputeHash(this.Read(normalSizedSectionCount * SECTION_SIZE, lastSectionSize)));
        }

        return checksums;
    }

}

The purpose of this class is to read large media files and create md5 hashes (checksums in this case) for all x bytes (SECTION_SIZE) of the file and add them to a list.

I want to know if there is a better/faster way to accomplish this.


texts:
I need to make a project related to a library catalog.

It should have following methods relevant to these books:

add
delete
list
There are two types of books: novels and poetry. Both types have number of pages and names. Novels have categories (SF...) and poetry have themes. Need to be able to list the books in the library.

How should I model the code for this (using inheritance, Lists, no hashmap)? I have thought to create a class BasicBook (fields pages, names), Novels (field category) and Poetry (field theme) to inherit from BasicBook. Create a class Library (fields List Novel, List Poetry) and methods to add, delete, print).
Is there a better way to tackle this problem? Thanks a lot!

package com.andy85;
public class Book {
private String name;
private int numOfPages;

  public Book(String name, int numOfPages) {
        this.name = name;
        this.numOfPages = numOfPages;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getNumOfPages() {
        return numOfPages;
    }

    public void setNumOfPages(int numOfPages) {
        this.numOfPages = numOfPages;
    }

    @Override
    public String toString() {
        return this.name + ", " + this.numOfPages;
    }
}

public class Novel extends Book {
    private String types;

    public Novel(String name, int numOfPages, String types) {
        super(name, numOfPages);
        this.types = types;
    }

    public String getTypes() {
        return types;
    }

    public void setTypes(String types) {
        this.types = types;
    }

    @Override
    public String toString() {
        return super.toString() + ": " + types;
    }
}

public class ArtAlbum extends Book {
    private String paperQuality;

    public ArtAlbum(String name, int numOfPages, String paperQuality) {
        super(name, numOfPages);
        this.paperQuality = paperQuality;
    }

    public String getPaperQuality() {
        return paperQuality;
    }

    public void setPaperQuality(String paperQuality) {
        this.paperQuality = paperQuality;
    }

    @Override
    public String toString() {
        return super.toString() + paperQuality;
    }

public class LibraryCatalog {
    private List<Novel> novel = new ArrayList<>();
    private List<ArtAlbum> artAlbum = new ArrayList<>();

    public LibraryCatalog(List<Novel> novel, List<ArtAlbum> artAlbum) {
        this.novel = new ArrayList<>(novel);
        this.artAlbum = new ArrayList<>(artAlbum);
    }

    public List<Novel> getNovel() {
        return novel;
    }

    public void setNovel(List<Novel> novel) {
        this.novel = novel;
    }

    public List<ArtAlbum> getArtAlbum() {
        return artAlbum;
    }

    public void setArtAlbum(List<ArtAlbum> artAlbum) {
        this.artAlbum = artAlbum;
    }

    public void addNovel (Novel newNovel) {
        this.novel.add(newNovel);
    }
}


texts:
I would like to add basic Cloud system to my website project. I have my php login system already included. Every person must be logged in to view this site.
There are several session variables like $_SESSION["id"].

I've got my files.php file - main file with list of uploaded files on server, form to upload new and delete. File data to remove/add is sent to PHP script by POST + hidden inputs keeping user id.

I've found some basic PHP functions that are successfully connected to my website and working.

uploadscript.php (w3schools)

<?php
$target_dir = "files/" . $_POST["id"] . "/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    header('Location: files.php?alert=4;');
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    header('Location: files.php?alert=5;');
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    header('Location: files.php?alert=3;');
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        header('Location: files.php?alert=1;');
    } else {
        header('Location: files.php?alert=2;');
    }
}
?>

downloadscript.php (php.net/manual/en/function.readfile.php)

<?php
$file = "files/" . $_POST["id"] . "/" . $_POST["file"];

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>

deletescript.php (php.net/manual/en/function.unlink.php)

<?php
$file = "files/" . $_POST["id"] . "/" . $_POST["file"];

if (file_exists($file)) {
    unlink($file);
    header('Location: files.php?alert=6;');
    exit;
}
?>

Are these scripts secure? Do you suggest any modifications to it to prevent some unexpected and unwanted actions by users?


texts: function to append "a" or "an" to the front of a number as appropriate

texts:
Input: any integer

Output: that integer in number format (commas) with a leading a or an as appropriate with the rules of English

After a bit of groping around I hacked out the following PHP function, and am looking for any advice on code structure and optimization. Thank you!

function prefixAAnToNumber($num) {
    $prefixAn = array(8, 11, 18, '8', '11', '18');
    $verAn = 'an ' . number_format($num);
    $verA = 'a ' . number_format($num);

    if (in_array($num,$prefixAn)) {
        return $verAn;
    } else if (strlen($num) > 1) {
        $numComma = number_format($num);
        if (substr($numComma,0,1) == '8') {
            return $verAn;
        } else if (in_array(substr($numComma,0,2), $prefixAn) && substr($numComma,2,1) == ',') {
            return $verAn;
        } else {
            return $verA;
        }
    } else {
        return $verA;
    }
}

Example usage:

$num = 11;
for ($i = 0; $i < 10; ++$i) {
    echo '<p>'.$num.' -> "';
    echo prefixAAnToNumber($num);
    echo ' kg shipment"</p>';
    $num = $num * 10;
}

Output:

11 -> "an 11 kg shipment"

110 -> "a 110 kg shipment"

1100 -> "a 1,100 kg shipment"

11000 -> "an 11,000 kg shipment"

110000 -> "a 110,000 kg shipment"

1100000 -> "a 1,100,000 kg shipment"

11000000 -> "an 11,000,000 kg shipment"

110000000 -> "a 110,000,000 kg shipment"

1100000000 -> "a 1,100,000,000 kg shipment"

11000000000 -> "an 11,000,000,000 kg shipment"


texts: Accessing value from either os.environ or argparse

texts:
I have the following code:

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

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

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

    print("Verbose:", verbose)

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

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

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

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

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

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

otherwise False.


texts: Replacing tokens in a text file with replaced text

texts:
This code parses a text file, replacing special tokens marked as $(token) with some replaced text.  The $ symbol can be escaped by entering a double $$.  In the example a user enters a text file containing tokens to replace and a separate mapping file with, for instance, colour:red to denote how to replace a token.

Some remarks I have is that is is not using any OO really.  Does it need to be?

#include <fstream>
#include <iostream>
#include <vector>
#include <map>
#include <string>

static void readToken(std::istream& strm, std::vector<char>& token)
{
   while(strm) {
      int c (strm.get());
      token.push_back(c);
      if(')' == c) break;
   }
}

static void lookup_replacement(const std::map<std::string,std::string>& token_map,
                               const std::vector<char>& key, std::vector<char>& value) {
    if(key.size() > 3) {  //3 chars min are '$', '(' and ')'
        std::map<std::string,std::string>::const_iterator it = token_map.find(std::string(key.begin()+2, key.end()-1));
        if(it != token_map.end())
           value.insert(value.end(), it->second.begin(), it->second.end());
    }
}

static bool readTo(std::istream& strm, std::vector<char>& buf, const char term[])
{
   bool ret(false);
   while(strm) {
      int c (strm.peek());
      if(strchr(term, c)) {
         strm.get();
         int c2(strm.peek());
         if(c != c2) {
           strm.unget();
           ret = true;
           break;
         }
      }
      strm.get();
      buf.push_back(c);
   }
   return ret;
}

static void create_mapping(std::ifstream& strm, std::map<std::string,std::string>& tokens) {
   if(strm.good()) {
      std::string line;
      while(std::getline(strm, line)) {
         std::string::size_type pos = line.find_first_of(':');
         if(pos != std::string::npos)
            tokens.insert(std::make_pair<std::string, std::string>(line.substr(0, pos), line.substr(pos+1)));
      }
   }
}

int main() {
   std::map<std::string,std::string> token_map;

   typedef std::map<std::string,std::string>::iterator map_iter;

   std::cout << "Enter path to text file to replace\nTokens to be replaced should be of form: $(token)\n";
   std::string file;
   std::cin >> file;

   std::cout << "Enter path to file with target token <-> replacement token in format:\n"
                "<toreplace1>:<replacement1>\n<toreplace2>:<replacement2>\netc\n";
   std::string mapfile;
   std::cin >> mapfile;

   std::ifstream strmmap(mapfile.c_str());
   create_mapping(strmmap, token_map);

   // replaced text
   std::vector<char> replaced;

   std::ifstream strm(file.c_str());
   if(!strm.bad()) {
      while(!strm.eof()) {
         if(readTo(strm, replaced, "$")) {
            std::vector<char> token;
            readToken(strm, token);
            std::vector<char> replace_tok;
            lookup_replacement(token_map, token, replace_tok);
            if(!replace_tok.empty())
                replaced.insert(replaced.end(), replace_tok.begin(), replace_tok.end());
         }
      }
   }

   //print out replaced text
   std::cout << "your replaced text file\n";
   std::vector<char>::iterator pit = replaced.begin();
   while(pit != replaced.end())
      std::cout << *pit++;

   return 0;
}

The example input file I was using:

  Once upon a $(place1) there was a $(adjective1) $(colour) $(animal).

  Do you have a $$

  You have enemies? Good. That means you've stood up for something,
  sometime in your life. by $(author) on $(date)

  A fanatic is one who can't change his mind and won't change the
  subject. By $(author)

And the mapping file:

place1:time
adjective1:cunning
colour:brown
animal:fox
author:Winston Churchill
date:06/06/2013


texts:
I need to subclass UIButton, however the design of UIButton makes this really painful. This is because to create a button you really need to call:

[UIButton buttonWithType:UIButtonTypeRoundedRect]

So if I want to subclass I really need to do whatever it is this method does. However, it is not possible to set the buttons underlying type.

One option is to use something like decorator and subclass UIButton but have the actual button as an ivar and defer all property/method calls to this button. The problem here is that I then need to implement most of the UIButton interface (yawn).

What I have done is something a bit sneakier in my sub class. I have created this method:

- (id) initWithType:(UIButtonType)buttonType
{
    [super init];

    actualButton = [[UIButton buttonWithType:buttonType] retain];

    memcpy(self, actualButton, sizeof(UIButton));
    self->isa = [ABDescriptorButton class];

    return self ;
}

I know this is pretty unorthodox, but it works and is fairly clean in terms of code. What are the pitfalls I might have with this approach?


texts: Given two strings, determine if one is a permutation of the other

texts:
After comparing my newbie attempt with other people's answers, I have a couple questions:

I've made s1_set the size of s1. I've seen other people assume that the strings are ASCII-256 and use s1_set(256) but to me this doesn't make sense. Won't s1_set have at most s1.size() bytes (and fewer if s1 has duplicate characters)?
I've also seen explicit casting before accessing s1_set: int val = static_cast<int>(x);. Is this necessary? Is it bad form to use implicit casting?
Would it be preferred to use the regular for statement, or does the range-for work just as well?

#include <iostream>
#include <vector>

using namespace std;

bool is_permutation(const string& s1, const string& s2) {
  if (s1.size() != s2.size()) {
    return false;
  }

  vector<int> s1_set(s1.size());
  for (const auto& x : s1) {
    ++s1_set[x];
  }

  for (const auto& x : s2) {
    if (--s1_set[x] < 0) {
      return false;
    }
  }

  return true;
}

int main(int argc, char* argv[]) {
  cout << is_permutation("AABC", "BCBA") << endl; // false
  cout << is_permutation("BC", "CBA") << endl; // false, different sizes
  cout << is_permutation("ABC", "CBA") << endl; // true
  cout << is_permutation("AABC", "ACBA") << endl; // true
}


texts: Re-implementing an Array Class in Python

texts:
I gave an attempt at reinventing the wheel and recreate list methods using my own Array Class to broaden my understanding about lists. I would like advice regarding efficiency, and in implementing negative indexes, since my code only works for positive ones.

class Array:

    def __init__(self, List=[]):
        self.array = List

    def display(self):
        print(self.array)

    def len(self):
        array = self.array
        count = 0
        for _ in array:
            count += 1
        return count

    def append(self, value):
        array = self.array
        length = self.len()
        results = [None] * (length+1)
        for i in range(length):
            results[i] = array[i]
        results[length] = value
        self.array = results

    def search(self, value):
        array = self.array
        pos = -1
        for index in range(self.len()):
            if array[index] == value:
                pos = index
        return pos

    def insert(self, index, value):
        array = self.array
        length = self.len()
        results = [None] * (length+1)
        if index > length:
            raise IndexError
        elif index == length:
            self.append(value)
            results = self.array
        else:
            for i in range(length):
                if i == index:
                    for j in range(index + 1, length + 1):
                        results[j] = array[j-1]
                    results[index] = value
                    break
                else:
                    results[i] = array[i]
        self.array = results

    def delete(self, value):
        array = self.array
        length = self.len()
        results = [None] * (length-1)
        pos = self.search(value)
        if pos == -1:
            raise "Index Error: Element Not Found"
        else:
            for i in range(length):
                if i != pos:
                    results[i] = array[i]
                else:
                    for j in range(pos+1, length):
                        results[j-1] = array[j]
                    break
        self.array = results

    def pop(self):
        array = self.array
        length = self.len()
        results = [None] * (length-1)
        if length == 0:
            raise IndexError

        value = array[-1]
        for i in range(length-1):
            results[i] = array[i]
        self.array = results
        return value


texts: Functions to handle async calls and also handle loading and error status in React component

texts:
I've got the following component structure:

Component hierarchy:

<AdminBlogPostContainer>
  <AdminBlogPostPage>
    <BlogPostForm>

AdminBlogPostContainer.js

Contains all the functions to make the API calls, get posts from database, save posts, delete posts, upload images, etc. It also sets the loading and error states.

When I'm editing a blogPost, before rendering the <BlogPostForm/> I need to get the blogPost from the database (using the blog-post-slug from the route), store in the blogPost state object.

Note: This is a Single Page App and I'm using react-router-dom for client-side routing.

The way I'm currently doing is this:

I have an "action" function that handles the setting of the loading and error status.

function ACTION_getBlogPost()

async function ACTION_getBlogPost() {
    try {
      setLoading(true);
      setError(null);

      await getBlogPostFromFirestore(props.match.params.slug);

      setLoading(false);
    }
    catch(err) {
      console.log(err);
      setError(err);
      setLoading(false);
    }
  }

And that "action" function calls the actual function getBlogPostFromFirestore() that retrieves the blogPost.

function getBlogPostFromFirestore(slug)

function getBlogPostFromFirestore(slug) {
    return new Promise(async (resolve,reject) => {

      try {
        const querySnapshot = await firebase.firestore().collection('blog').where('slug','==',slug).get();
        const blogPostData = querySnapshot.docs[0].data();

        setFirestoreID(querySnapshot.docs[0].id);
        setBlogPost(blogPostData );

        resolve();
      }

      catch(err) {
        reject(err);
      }
    });
  }

QUESTION

I think I could still improve the readability on this code. Maybe keep the "action" function like it is, but change the getBlogPostFromFirestore to this:

function getBlogPostFromFirestore() {
  return
    firebase.firestore().collection('blog').where('slug','==',slug).get()
    .then((querySnapshot) => {
      const blogPostData = querySnapshot.docs[0].data();
      setFirestoreID(querySnapshot.docs[0].id);
      setBlogPost(blogPostData);
    })
    .catch((err) => throw err);
}

What do you think? Which one is the best? Any other suggestions?


texts:
I'm new to the filesystem from Laravel, but I need an upload script that allows users to upload images to my server. However, i'm concerned about securety, so I thought why not ask for advice, because there aren't much reverences about that big topic of securety.

Basicly, this is how I check the user upload and how I upload the file:

My request Class:

 return [
        'profile_picture' => 'image',
    ];

My check if the image is actually an image and not some bad maleware:

function checkIfImageIsAllowed($file) {
$allowedMimes = [
    'image/jpeg',
    'image/jpg',
    'image/png'
];

$allowedExtensions = [
    'jpg',
    'JPG',
    'jpeg',
    'png'
];
$allowedMaxSize = 2000000;
if(!in_array($file->getClientOriginalExtension(), $allowedExtensions) || !in_array($file->getMimeType(), $allowedMimes) || $file->getSize() > $allowedMaxSize) {
    return false;
}
return true;
}

And than I upload the file:

$path = $request->file('profile_picture')->store('UserUpload/Images');

This is how I display the Image:

    $images = \App\Image::where('uuid', $uuid)->firstOrFail();
    $path = $images->path;
    $image = Storage::get($path);
    $response = Response::make($image, 200);
    $response->header("Content-Type", $images->memeType);

    return $response;

What are your thoughts about this? Do you think this is secure enough? Or do you have some improvement for this?


texts:
I chanced upon this code written by the Solution Architect for an MS CRM project and I am lost for words. Am I going crazy or is this code OK?

string returnedOptionSetStringValue=string.Empty;
int returnedInt = 0;

Utils.RetrieveOptionSetLabelOrValue(CRMAccess.xrmService, Contact.EntityLogicalName, "new_status", optionSetValue.Value, string.Empty, ref returnedOptionSetStringValue, ref returnedInt, CRMAccess.tracerService);

The method within the Utils class is as follows

public static void RetrieveOptionSetLabelOrValue(IOrganizationService CrmWebService, string EntityName, string AttributeName, int OptionSetValue, string optionSetText, ref string returnedText, ref int returnedNumber, ITracingService tracerService)
{
    string returnLabel = string.Empty;
    tracerService.Trace("starting in function ");
    OptionMetadataCollection optionsSetLabels = null;

    tracerService.Trace("in retrieve option set label with values:" + OptionSetValue + " and text " + optionSetText);

    optionsSetLabels = RetrieveOptionSetMetaDataCollection(ref CrmWebService, EntityName, AttributeName);

    foreach (OptionMetadata optionMetdaData in optionsSetLabels)
    {
        tracerService.Trace("now in loop with  " + optionMetdaData.Label.UserLocalizedLabel.Label + " and " + optionMetdaData.Value.Value);
        //we have number we need text from optionset
        if (OptionSetValue != 0)
        {
            if (optionMetdaData.Value == OptionSetValue)
            {
                returnedText = optionMetdaData.Label.UserLocalizedLabel.Label;
                break;
            }
        }
        //we have text we need number from optionset
        else if (optionSetText != String.Empty)
        {

            if (optionMetdaData.Label.UserLocalizedLabel.Label == optionSetText)
            {
                returnedNumber = optionMetdaData.Value.Value;
                break;
            }

        }
    }
}


texts:
Here is my very first event dispatcher. I would like to get both, style and code review, as well as some ideas to improve this implementation (new features etc.)

I tried to write code in C++17 style as much as possible.

IEventDispatcher.h

#pragma once

#include <map>
#include <functional>

template<typename EventType>
class IEventDispatcher
{
public:
    using EventHandler = std::function<void()>;

    virtual void addEventListener(EventType eventToAdd, EventHandler handler) = 0;
    virtual void removeEventListener(EventType eventToRemove) = 0;
    virtual void dispatch(EventType eventToDispatch) = 0;
};

EventDispatcher.hpp

#pragma once

#include "IEventDispatcher.h"

template<typename EventType>
class EventDispatcher : public IEventDispatcher<EventType>
{
public:
    using EventHandler = std::function<void()>;

    EventDispatcher();
    ~EventDispatcher();

    void addEventListener(EventType eventToAdd, EventHandler handler);
    void removeEventListener(EventType eventToRemove);
    void dispatch(EventType eventToDispatch);

private:
    std::multimap<EventType, EventHandler> eventListeners;
};

template<typename EventType>
EventDispatcher<EventType>::EventDispatcher()
{}

template<typename EventType>
EventDispatcher<EventType>::~EventDispatcher()
{}

template<typename EventType>
void EventDispatcher<EventType>::addEventListener(EventType eventToAdd, EventHandler handler)
{
    eventListeners.emplace(eventToAdd, handler);
}

template<typename EventType>
void EventDispatcher<EventType>::removeEventListener(EventType eventToRemove)
{
    eventListeners.erase(eventToRemove);
}

template<typename EventType>
void EventDispatcher<EventType>::dispatch(EventType eventToDispatch)
{
    for (const auto &[event, handler] : eventListeners)
    {
        if (event == eventToDispatch)
        {
            handler();
        }
    }
}


texts: Finding out players gender and name in text based adventure game

texts:
#include <iostream>
#include <string>
#define NL "\n"

int main(void) {

    //Acquires players first name
    std::string introOne = "Welcome to The World of Magick\nWhat is your name?\n";
    std::cout << introOne;

    std::string playerName;
    std::cin >> playerName;

    //Asks for players gender
    while(true) {
    std::cout << "Are you a boy or a girl?" << NL << "1. Boy | 2. Girl"
    << NL << "Choices are selected by typing in a single number" << NL;

    int playerGenderSelect;
    std::string playerGender;
    std::cin >> playerGenderSelect;

        //Sets gender depending on value entered
        switch(playerGenderSelect) {

        case 1:
        playerGender = "male";
        break;

        case 2:
        playerGender = "female";
        break;

        default:
        std::cout << "Not a valid number, try again" << NL;

    }

    //If the player entered a valid number, break loop, if not, continue it.
    if(playerGender == "male" or playerGender == "female") {
        break;
    }
    else {
        continue;
    }
}

    return 0;
}

I wrote this code for a text based adventure game I'm making too keep me busy over the weekend.

I usually do this kind of boredom-project in python but decided to tackle it in C++. I was wondering if there were any obvious taboos or things that could obviously be optimized better.


texts: finding boundary elements in cartesian grid

texts:
I have a 2D cartesian grid (see picture below). The colorful cells are filled element. I would like to detect blue cells. Blue cells are bound  elements if you scan from bottom to top and left to right and vice versa.

I wrote following code when I do scan from bottom, but I do not know what would be the best for all four side scanning. I try to simulate on the simple example below with 8 cells in x direction and 5 cells in y direction. However, the real problem is order of (10000 x 10000) cells. The following code only find the two bottom blue cells.

#include "stdafx.h"
#include <vector>
#include <set>

#include "iostream"

struct cell
{
  cell(size_t i_x, size_t i_y)
    {
    x = i_x;
    y = i_y;
    }
  size_t x;
  size_t y;
  bool operator==(cell a)
    {
    if (a.x == x && a.y == y)
      return true;
    else
      return false;
    };
};

int main()
  {
  std::vector<cell> cartesian{ cell(0, 1), cell(0, 2), cell(0, 3),
    cell(1, 2), cell(1, 3), cell(1, 4), cell(1, 5),
    cell(2, 1), cell(2, 2), cell(2, 3), cell(2, 4), cell(2, 5),
    cell(3, 0), cell(3, 1), cell(3, 2), cell(3, 3), cell(3, 4), cell(3, 5), cell(3, 6),
    cell(4, 2), cell(4, 3), cell(4, 4), cell(4, 5), cell(4, 6) };
  size_t max_X = 8;
  size_t max_Y = 5;

  std::vector<size_t> bound_elements;
  for (size_t i = 0; i < max_X; ++i)
    {
    bool found = false;
    for (size_t j = 0; j < max_Y; ++j)
      {
      auto is_filled = std::find(cartesian.begin(), cartesian.end(), cell(i, j));
      if (is_filled == cartesian.end())
        {
        continue;
        }
      size_t position = (j + (max_X* i));

      if (bound_elements.size() == 2)
        {
        bound_elements[1] = position;
        }
      else
        {
        bound_elements.push_back(position);
        }
      found = true;
      }
    if (found)
      {
      break;
      }
    }
  for (auto element : bound_elements)
    {
    std::cout  << element << std::endl;
    }
  return 0;
  }

For top to down It is just opposite side for loop iteration. This strategy seems to be too verbose, is there a better way in terms of performance or coding style?


texts: Removing all duplicated pairs in a Python list

texts:
I need a function to remove duplicated pairs from a list. The following is example list:

a = [1, 1, 1, 2, 3, 5, 4, 4, 5, 2, 3, 3, 2, 3, 1, 6, 6, 6, 6]

I need remove all pairs [a[i], a[i+1]] if a[i] == a[i+1] until all such pairs eliminated:

[1, 1, 1, 2, 3, 5, 4, 4, 5, 2, 3, 3, 2, 3, 1, 6, 6, 6, 6]

[1, 2, 3, 5, 5, 2, 2, 3, 1]

[1, 2, 3, 3, 1]

[1, 2, 1] - final list

I wrote a removepairs function:

def removepairs(list):
    result_prev = list
    while True:
        result = __removepairs_once__(result_prev)
        if len(result) == len(result_prev):
            return result
        else:
            result_prev = result

def __removepairs_once__(list):
    result = []
    most_recent_element = None
    for i in list:
        if i != most_recent_element:
            if most_recent_element:
                result.append(most_recent_element)
            most_recent_element = i
        else:
            most_recent_element = None
    if most_recent_element:
        result.append(most_recent_element)
    return result

Please help me to make it better.


texts:
This code is a representation of lambda calculus using an AST instead of text.

-- beta
-- (App (Abst var body) env) -> (Sub body var env)

-- eta
-- (Abst var (App body var')) -> body

-- alpha
-- (Sub (Var var) var env) -> env
-- (Sub (Var var') var env) -> (Var var')
-- (Sub (Abst var body) var env) -> (Abst var body)
-- (Sub (Abst var' body) var env) -> (Abst var' (Sub body var env))
-- (Sub (App a b) var env) -> (App (Sub a var env) (Sub b var env))

My goal is to represent the transformation rules listed here accurately and explicitly. This code is slower than many other interpreters, and if there is a way to make the code more efficient while still conveying the reduction rules clearly, that would be an improvement.

module Eval where

import Data.Maybe
import Data.Tuple
import Data.List

data Expr a
  = Var a
  | Abst a (Expr a)
  | App (Expr a) (Expr a)
  | Sub (Expr a) a (Expr a)
deriving (Eq, Show)

app :: (Eq a) => Expr a -> Expr a
app (App (Abst var body) env) = (Sub body var env)
app a = a

abst :: (Eq a) => Expr a -> Expr a
abst (Abst var (App body (Var var')))
  | var == var' = body
abst a = a

sub :: (Eq a) => Expr a -> Expr a
sub (Sub (Var var') var env)
  | var == var' = env
  | otherwise = (Var var')
sub (Sub (Abst var' body) var env)
  | var == var' = (Abst var body)
  | otherwise = (Abst var' (Sub body var env))
sub (Sub (App a b) var env) = (App (Sub a var env) (Sub b var env))
sub a = a

eval :: (Eq a) => Expr a -> Expr a
eval expr@(Var _) = expr
eval expr@(Abst a b) = abst (Abst a (eval b))
eval expr@(App a b) = app (App (eval a) (eval b))
eval expr@(Sub a b c) = sub (Sub (eval a) b (eval c))

evalWhile :: (Eq a) => Expr a -> Expr a
evalWhile a
  | a == b = a
  | otherwise = evalWhile b
where b = eval a

Here are a few applicative combinators for debugging.

s, k, i :: Expr String
i = Abst "x" (Var "x")
k = Abst "x" (Abst "y" (Var "x"))
s = Abst "x" (Abst "y" (Abst "z" (App (App (Var "x") (Var "z")) (App (Var "y") (Var "z")))))

For instance:

λ> evalWhile (App (App (App s k) k) k)
Abst "x" (Abst "y" (Var "x"))

The eval function feels particularly awkward to me, as every type in Expr is preceded by it's equivalent function. Perhaps there is a better way to do this. The evalWhile function also seems like a poor way to check if we've reached normal form, though I have seen other code that does this. With memoization this might not be so bad.

I appreciate any feedback!


texts: Iterating an array of nodes, each of which can have children

texts:
I've written some C# (7) code to iterate through a Node[], listing all of its nodes in order (i.e. child elements are listed immediately after the parent).

Each Node is defined as follows,

class Node
{
    public string Name { get; set; }

    public List<Node> Children { get; set; } = new List<Node>();

    public bool HasChildren => Children.Count > 0;

    public Node(int n)
    {
        Name = $"Node #{n}";
    }

    public Node AddChild(Node n)
    {
        Children.Add(n);
        return this;
    }

    public override string ToString() => Name;
}

The collection of nodes to be iterated would be,

var nodes = new Node[]
{
    new Node(1),
    new Node(2),
    new Node(3)
        .AddChild(new Node(4))
        .AddChild(new Node(5))
        .AddChild(new Node(6)
            .AddChild(new Node(7)))
        .AddChild(new Node(8)
            .AddChild(new Node(9))
            .AddChild(new Node(10)))
};

...and output for the above would be 10 lines of "Node #", each followed by the number passed to the constructor of each (i.e. 1 to 10, in ascending order).

The code I've written to perfom the aforementioned task is,

var stack = new Stack<(Node[], int)>();

var i = 0;

while (i < nodes.Length)
{
    WriteLine($"{nodes[i]}");

    if (nodes[i].HasChildren)
    {
        // Stores away the current Node[] and the next index, to return to it once all children are iterated though.
        stack.Push((nodes, i + 1));

        // Makes the child Node[] the iteration target.
        nodes = nodes[i].Children.ToArray();

        // Resets the index to iterate all the children.
        i = 0;

        continue;
    }

    // If the current node is the last in the targeted Node[], and there are parent Node[]s from which this Node[] was switched to in the stack.
    if (i == nodes.Length - 1 && stack.Count > 0)
    {
        // Pop the stack until the popped Node[] isn't the last element, and assign it to the array being iterated.

        var (_target, _i) = stack.Pop();

        while (stack.Count > 0 && _i >= _target.Length)
        {
            (_target, _i) = stack.Pop();
        }

        nodes = _target;
        i = _i;

        continue;
    }

    ++i;
}

Do provide me with constructive criticism of my algorithm.
Does it work for Node[]s of any depth (level of child-ception ;)?
Are there ways in which it can be optimized?

N.B. (T1, T2) is equivalent to a Tuple (see: C# 7's System.ValueTuple)


texts: Applying Function to `Seq[B]` in `Seq[Either[A, B]]`

texts:
Given:

  def rights[A, B](xs: Seq[Either[A, B]]): Seq[B] =
    xs.flatMap {
      case Right(x) => List(x)
      case Left(_)  => List.empty
    }

  def lefts[A, B](xs: Seq[Either[A, B]]): Seq[A] =
    xs.flatMap {
      case Right(_) => List.empty
      case Left(x)  => List(x)
    }

  def combine[A, B](xs: Seq[A], ys: Seq[B]): Seq[Either[A,B]] = {
    val l: Seq[Either[A, B]] = xs.map(Left[A,B](_))
    val r: Seq[Either[A, B]] = ys.map(Right[A,B](_))
    l ++ r
  }

Is there a better way to do the following, i.e. apply distinct to the Right[Int] in the Seq[Either[String, Int]].

Look to res1 in the below output as the desired output.

scala> val xs: Seq[Either[String, Int]] = List( Left("foo"), Right(42), Right(6), Right(42) )
xs: Seq[Either[String,Int]] = List(Left(foo), Right(42), Right(6), Right(42))

scala> val distinct = rights(xs).distinct
distinct: Seq[Int] = List(42, 6)

scala> combine(lefts(xs), distinct)
res1: Seq[Either[String,Int]] = List(Left(foo), Right(42), Right(6))


texts: Mapping a product its corresponding image file

texts:
I'm writing this method that elaborates an image name..

I think my logic is not being the best one here but I'm not very savvy in programming yet.

Right now it looks like this:

if($this->isCustom($product)){
            $image_path = PRODUCT_IMAGE_PATH . $this->order['order_number'] . $index . '.jpg';
            $index++;
        }
        else{
            $image_path = PRODUCT_IMAGE_PATH . $product['sku'] . '.jpg';
        }

        if($this->checkRemoteImage($image_path)){
            return $image_path;
        }

        else{
            if (!$this->isCustom($product)){
                $this->notifyOnNonCustoms($image_path);
            }
            return "No Image";
        }

I believe something like this would be better:

if ($this->isCustom($product)){
            $image_path = PRODUCT_IMAGE_PATH . $this->order['order_number'] . $index . '.jpg';
            $index++;

            if (!$this->checkRemoteImage($image_path)){
                return "No Image";
            }
            return $image_path;
        }

        else{
            $image_path = PRODUCT_IMAGE_PATH . $product['sku'] . '.jpg';

            if (!$this->checkRemoteImage($image_path)){
                $this->notifyOnNonCustoms($image_path);
                return "No Image";
            }
            return $image_path;
        }
    }

The flow is meant to be like this:

If the product is custom, the image path should be the path + order number + ascending numbers ( using outer index here )

If not, it should be the image path + the product's sku

There should be a check if the image does exist in the server. If it doesn't it should return "No Image" and if it's not custom, call the method notifyOnNonCustoms I'm not sure on the best way to structure this.


texts:
I'm trying to do a some kind of a message parser. I have written this code. It literally works, but in my opinion, it looks like overkill. Do you have any idea to simplify it?

messageParser.js:

// ...

const { messages } = configParser('messages')

module.exports = function (api, msg) {
  // ...

  _.forEach(_.words(msg.body), body => { // For every word in message
    _.forEach(messages, message => { // Get all message templates
      if (_.some(message.triggers, trigger => { // If any of message templates matches tolerated distance (i want it to work even if we have a simple typo)
        return new Levenshtein(trigger, body).distance <= config.stringDiffrenceTolerate
      })) {
        // Process it

        return false // Stop forEach
      }
    })
  })
}

Example messages file:

{
  "messages": [
    {
      "triggers": [
        "rozkladarece",
        "shrug"
      ],
      // ...
    },
    {
      "triggers": [
        "lenny"
      ],
      // ...
    }
  ]
}


texts:
Here is one of my msTest Unit Tests and possibly one of the worst "looking" tests.

[TestMethod]
public void UniquePositionPoint_CreateUPP_UPPExistsInPPField()
{
    //Setup the values to be used by this test.
    CIM_Network network = new CIM_Network();
    string x = "5";
    string y = "10";
    string expectedMRID = String.Format("_UPP{0}", (x + y).GetHashCode());
    //Carry out the test
    CIM_PositionPoint pp = new CIM_PositionPoint(network, mRID: "pp", fields: new Dictionary<string, object>()
        {
                    {"cim:PositionPoint.CoordinateSystem",new CIM_CoordinateSystem(network, mRID: "coordSys")},
                    {"cim:PositionPoint.xPosition", x},
                    {"cim:PositionPoint.yPosition", y},
        }, addBackReferences:true);
    //Checks if the test was carried out correctly.
    Assert.AreEqual(2, pp.Fields.Count(),
        String.Format("ERROR: There should only be 2 fields in the position point as the x and y values should of been moved out to the UPP. Currently the fields in the pp are {0}",
        string.Join(":", pp.Fields.Select(kvp => (kvp.Key + ":" + kvp.Value.ToString())))));
    Assert.IsNotNull(pp.Fields.ContainsKey("uniquePositionPoint"), "ERROR: The field 'uniquePositionPoint:' does not exist in the position point fields.");
    Assert.IsInstanceOfType(pp.getField("uniquePositionPoint"), typeof(CIM_UniquePositionPoint),
        String.Format("ERROR: Expected the object at field 'uniquePositionPoint' to be of type CIM_UniquePositionPoint however it was of type {0}",
        pp.getField("uniquePositionPoint").GetType().Name));
    CIM_UniquePositionPoint uPP = (CIM_UniquePositionPoint)pp.getField("uniquePositionPoint");
    Assert.AreEqual(expectedMRID, uPP.MRID,
        String.Format("ERROR: Expected the mRID {0} to be the UPP's mRID but instead it was {1}", expectedMRID, uPP.MRID));
    Assert.IsTrue(uPP.BackRefs.Contains(pp), "ERROR: The position point was not found within the upp.");
}

What the code does is add a "position point" into a network. When this happens a few things also happen as a result:
1. A UniquePositionPoint (upp for short) is created.
2. That upp will contain all of the coordinates of the position point.
3. The coordinates will be removed from the position point.

What I mainly want to know is if this (a bunch of asserts) is the correct way to test this functionality or should it be broken down at all?


texts:
Any way to make this more concise/efficient?

// Write a loop that reverses the elements of an array.
#include <iostream>
#include <iomanip>

const int SIZE = 10;

void reverse(int iArrayRef1 []);
void display(int iArrayRef2 []);

int main()
{
    int iArray[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    // Display in the original order.
    std::cout << "Forwards:\n";
    display(iArray);

    // Reverse the array.
    reverse(iArray);

    std::cout << std::endl;

    // Display in reversed order.
    std::cout << "Backwards:\n";
    display(iArray);
    return 0;
}

void reverse(int iArrayRef1 [])
{
    int temp = 0;
    int* indexPtrBeg = iArrayRef1;
    int* indexPtrEnd = iArrayRef1 += (SIZE-1);

    for (int index = 0; index < (SIZE/2); index++)
    {
        temp = *indexPtrEnd;
        *indexPtrEnd = *indexPtrBeg;
        *indexPtrBeg = temp;
        indexPtrEnd--;
        indexPtrBeg++;
    }
}

void display(int iArrayRef2 [])
{
    for (int index = 0; index < SIZE; index++)
    {
        std::cout << std::setw(2) << iArrayRef2[index] << " ";
    }
    std::cout << std::endl;
}


texts:
I have been a Python developer for a few years and I'm going through some simple exercises to learn C++.

Please consider the following Python snippet

# Find the most frequent integer in an array
lst = [1,2,4,3,1,3,1,4,5,15,5,2,3,5,4]
mydict   = {}
cnt, itm = 0, ''

for item in lst:
     mydict[item] = mydict.get(item, 0) + 1
     if mydict[item] >= cnt :
         cnt, itm = mydict[item], item

print(itm)

It may not be very clean and it misses elements that tie for most frequent, but it is succinct code.  I re-wrote this to C++11 as:

#include <iostream>
#include <unordered_map>
#include <string>

int main(int argc, char const *argv[])
{
    using std::cout;

    int foo [] = {1,2,4,3,1,3,1,4,5,15,5,2,3,5,4};

    std::unordered_map<std::string, int> dict;

    std::string item;

    int count = 0;

    std::string itm;

    for (int i : foo) {
        item = std::to_string(i);

        auto it = dict.find(item);

        if (it != dict.end()) {
            it->second = it->second++;

            if (it->second >= count) {
                count = it->second;
                itm = item;
            }
        } else {
            dict.insert(std::make_pair<std::string, int>(item, 0));
        }

    }

    std::cout << "The integer most frequent is " << itm << "\n";
    return 0;
}

This executes fine and returns 4 which is one of the correct answers.  Can someone please offer a re-write of this to make it more succinct.

At present I am not concerned about if there's more than one element in the list that has a tie for most frequent.  I am more concerned with cleaner code.


texts: Refactor multiple if condition in JavaScript/TypeScript

texts:
I want to refactor this code but am wondering how I should start it. I'm not sure this code is totally against clean code or not. I'm thinking to use RxJS or a JavaScript builtin method. I'd like to have some help here to learn how to have clean code or how I can minimize the code to few line or chain multiple method of RxJS or JS to get rid of if conditions.
public loadChart(): void {
    this.chartDataSets = [];
    let allData = this.availableDataSet;
    if(this.selectedAttribute === Dashbaord.All && this.selectedComponent === Dashbaord.All) {
    this.prepareIntialData();
}
if (this.selectedAttribute === Dashbaord.All && this.selectedComponent !== Dashbaord.All) {
    const groupedByComponent = this.pendingActionDataSet.groupByArray(x => x.component);
    allData = groupedByComponent[this.selectedComponent];
}
if (this.selectedAttribute !== Dashbaord.All && this.selectedComponent === Dashbaord.All) {
    allData = this.groupedByAttribute[this.selectedAttribute].flattenArray();//["",""]
    const components = allData.groupByArray(x => x.component);//["key":["values"]]
    this.componentOptions = Mapper.mapToSelectItemWithAll(Object.keys(components));
}
if (this.selectedAttribute !== Dashbaord.All && this.selectedComponent !== Dashbaord.All) {
    const allDataByAttribute = this.groupedByAttribute[this.selectedAttribute].flattenArray();
    const groupedByComponent = allDataByAttribute.groupByArray(x => x.component);
    this.componentOptions = Mapper.mapToSelectItemWithAll(Object.keys(groupedByComponent));
    if (!this.componentOptions.filter(x => x.value === this.selectedComponent).length) {
        this.selectedComponent = Dashbaord.All;
        allData = allDataByAttribute;
    } else {
        allData = groupedByComponent[this.selectedComponent];
    }
}
this.prepareChartData(allData);
}


texts:
I've recently begun to teach myself to code. One simple project that I wanted to do was create a Caesar cipher that works well. Now that I feel I've accomplished that task, I'd like to know how I'm doing with overall code quality. Here's the code.

import java.util.Scanner;

public class Encryptor
{
    private char[] upperCase = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
    private char[] lowerCase = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    private char oneChar;
    private String encryptedString = "";
    private int counter;

    public String encryptString(String input, int offset)
    {
        for (counter = 0; counter < input.length(); counter++)
        {
            oneChar = input.charAt(counter);

            boolean moveOn = false;
            int i = 0;

            //get a single character

            while (!moveOn)
            {
                if (i > 26)
                {
                    encryptedString += oneChar;
                    moveOn = true;
                }
                //remainder keeps me from going over array length
                else if (oneChar == upperCase[i%26])
                {
                    encryptedString += upperCase[(i+offset)%26];
                    moveOn = true;
                }
                else if (oneChar == lowerCase[i%26])
                {
                    encryptedString += lowerCase[(i+offset)%26];
                    moveOn = true;
                }
                else
                {
                    i++;
                }
            }
        }
        return encryptedString;
    }
}

public class Main
{
    public static void main (String[] args)
    {
        String inText = "";
        String encryptedText = "";
        int offset = 0;
        String choice;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter something to encrypt or decrypt");
        inText = input.nextLine();

        System.out.println("Would you like to encrypt your message, or decrypt your message? Please type in encrypt or decrypt.");
        choice = input.next();

        System.out.println("How many letters over should the program shift everything? Enter numbers only.");
        offset = input.nextInt();

        Encryptor encrypt = new Encryptor();
        if (choice.equalsIgnoreCase("encrypt") || choice.equalsIgnoreCase("e"))
        {
            encryptedText = encrypt.encryptString(inText, offset);
        }
        else if (choice.equalsIgnoreCase("decrypt") || choice.equalsIgnoreCase("d"))
        {
            offset = 26 - offset;
            encryptedText = encrypt.encryptString(inText, offset);
        }
        System.out.printf("Your message is %s", encryptedText);

        }

    input.close();

    }
}

What do you think of it in terms of overall readability? And for a first attempt, how'd you rank it?

EDIT: Adding in some more questions that occurred overnight.

What things in this make you cringe/confused/ need to be improved?
I noticed that during decryption, if the offset goes below 0, I get an index out of range error. For example, if some joker decides to offset more than 26, say 27, the offset becomes -1. This is then subtracted and ran through the remainder and comes out negative. A negative value in an array is an error. I can't simply do the absolute value of the number either as the way my code and arrays are set out, -1%26 would not be 1%26, rather -1%26 should be equivalent to 25.


texts:
I am using PDO for the first time in my project.  In my previous project someone suggested me to use PDO as my queries were wide open to inject.  I am pasting a sample code of my project.  Can you please let me know how safe my code and query is?

<?php
require('config.php');
try {
    $pid = $_GET['pid'];
    $conn = new PDO("mysql:host=" . $DB_HOST . ";dbname=" . $DB_NAME, $DB_USER, $DB_PASS);
    $sql = "SELECT * FROM packages_to_be_shipped_on_bremail_address WHERE package_id=$pid";

    $q = $conn->prepare($sql);
    $q->execute();

    $q->bindColumn(1, $pid);
    $q->bindColumn(2, $custemail);
    $q->bindColumn(3, $shipcompany);
    $q->bindColumn(4, $deliverydate);
    $q->bindColumn(5, $trackingid);
    $q->bindColumn(6, $destaddress);
    $q->bindColumn(7, $destzip);
    $q->bindColumn(8, $status);
    $q->bindColumn(9, $rate);
    $q->bindColumn(10, $rates_sent_status);
    $q->bindColumn(11, $customer_response);

    while($q->fetch()){
        echo "Shipping Company - ".$shipcompany."

";
        echo "Expected Delivery Date - ".$deliverydate."

";
    }
}
catch(PDOException $e) {
    echo $e->getMessage();
}
?>


texts: Macro to remove rows with data not meeting certain requirements

texts:
I have created several macros that delete rows based on cell values. I run it 5 times for different data, but think there should be a way to combine them and speed up the macro. Currently, it is running a little slow.

It is pulling a date from another worksheet and if it doesn't match, removing the line. I am basically running the same macro over and over, just changing the values slightly.

I am just changing the value in column E (120 in this example, but could be 30, 60, 90, etc) and seeing if it matches the date on another worksheet. The cell on the other worksheet changes depending on E value
If 30, use date A1
If 60, use date in A2
etc.

Here is one of the five macros I have:

Sub Remove_FutureRenewals_120()
    Dim Firstrow As Long
    Dim LastRow As Long
    Dim Lrow As Long
    Dim CalcMode As Long
    Dim ViewMode As Long

Firstrow = ThisWorkbook.Worksheets(2).UsedRange.Cells(1).Row
LastRow = ThisWorkbook.Worksheets(2).Cells(ThisWorkbook.Worksheets(2).Rows.Count, "A").End(xlUp).Row

With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    '.ScreenUpdating = False
End With

With ActiveSheet
    For Lrow = LastRow To Firstrow Step -1
        With .Cells(Lrow, "E")
            If Not IsError(.Value) Then
                If .Value = "120" _
                    And Format(.Offset(0, -1).Value, "YYYYMMDD") <> Format(ThisWorkbook.Worksheets("Date Calc").Cells(5, "A").Value, "YYYYMMDD") _
                    Then .EntireRow.Delete
            End If
        End With

    Next Lrow

End With

End Sub


texts: Create a calendar application to check the scheduling conflicts of meetings

texts:
The purpose here is to find if there is a conflict in the given set of start and end times of the meeting time slots listed.

Input: Start and end times of meetings

Output: True / False for conflicts

package code.Misc;

import java.util.ArrayList;

public class Calendar {

static int time [] = new int[1440];

public static void main(String args[]){

    String s[] =   {"15:30","1:30","1:15","15:00"};
    String e[] = {"18:35","13:28","1:30","15:29"};

    System.out.println(scheduler(s, e));
}

public static int calculateMinute(int hour, int minute){
        return hour*60+minute;
}

public static boolean timeClashChecker(int start, int end){
        for(int i=start;i<=end;i++){
            if(i==end){
                time[i] =  -1;
            }
            else if(time[i]==1){
                return false;
            }
            else if(time[i]==-1){
                time[i]=1;
            }
            else{
                time[i]=1;
            }
        }
    return true;
}
public static int parser(String time){
    String [] timeParts = time.split(":");
    int hour = Integer.parseInt(timeParts[0].trim());
    int minute = Integer.parseInt(timeParts[1].trim());

    return calculateMinute(hour,minute);
}
public static boolean scheduler(String start[], String end[]){

    for(int i=0;i<start.length;i++){
        int startMeeting = parser(start[i]);
        int endMeeting = parser(end[i]);
        boolean result = timeClashChecker(startMeeting,endMeeting);
        if(result == false){ //clash check
            return false;
        }
    }
    return true;
}
}


texts:
I just felt a sting as for the first time, I copy-pasted code blocks, and made very little change to it, to overload it. It works fine, but I have 3 constructors that are basically copy-pasted. I'm hoping there is a smarter way to do this.

This simply creates a thread and runs it with 1, 2 or 3 arguments, and then prints numbers to System.out using that thread. I will include an example usage below. The code doesn't strike me as bad of itself, but the sheer repetition is really bugging me. All criticism welcome.

import java.lang.Thread;

/**
 * Generic class that creates a thread and then loops and prints numbers to stdout.
 */
public class NumLoopThread implements Runnable {
    Thread thread;
    private String threadName;
    private int sleepTime = 400;
    private int numLoops = 10;

    /** Default constructor with threadName */
    public NumLoopThread(String threadName) {
        this.threadName = threadName;
        thread = new Thread(this, threadName);
        thread.start();
    }
    /** Extra constructor with threadName and sleepTime */
    public NumLoopThread(int sleepTime, String threadName) {
        this.sleepTime = sleepTime;
        this.threadName = threadName;
        thread = new Thread(this, threadName);
        thread.start();
    }
    /** Extra constructor with threadName, sleepTime, and numberLoops */
    public NumLoopThread(int sleepTime, String threadName, int numberLoops) {
        this.sleepTime = sleepTime;
        this.threadName = threadName;
        this.numLoops = numberLoops;
        thread = new Thread(this, threadName);
        thread.start();
    }
    /** Run the thread from start() */
    public void run() {
        System.out.printf("%s starting%n", threadName);
        try {
            for(int i = 0; i < numLoops; i++) {
                Thread.sleep(sleepTime);
                System.out.printf("%s, i = %d%n", threadName, i);
            }
        } catch(InterruptedException exc) {
            exc.printStackTrace();
        }
        System.out.printf("%s ending%n", threadName);
    }
}

Example usage I wrote for an exercise (feel welcome to also criticize this, if you want). Looks like this paste after it's ran.

public class ThreadIsAlive {
    public static void main(String[] args) {
        System.out.println("Main thread starting");
        // create 3 running threads
        NumLoopThread t1 = new NumLoopThread(400, "t1");
        NumLoopThread t2 = new NumLoopThread(400, "t2");
        NumLoopThread t3 = new NumLoopThread(400, "t3");

        do {
            System.out.print(".");
            try {
                Thread.sleep(100);
            } catch (InterruptedException exc) {
                exc.printStackTrace();
            }
        //wait until all threads terminate:
        } while (t1.thread.isAlive() ||
                 t2.thread.isAlive() ||
                 t3.thread.isAlive());
        System.out.println("Main thread ending");
    }
}


texts:
I have these two XMLs that I want to merge together based on these conditions:

If any of the element is more than 7 weeks old, it has to be deleted.
If any of the element is newer with the same date (regardless of time), take everything from the new XML.

Sample XML:

<programme start="20150317173000 -0000" stop="20150317180000">
   <something else />
</programme>

I use start field to check if the element should be deleted or not.

old_xml = ET.fromstring(old)
new_xml = ET.fromstring(new)

new_programmes = new_xml.findall('programme')

dates_to_delete = set()
programmes_to_add = []

for new_programme in new_programmes:
    start = new_programme.get('start')
    new_prog_st_t = datetime.datetime.strptime(start, DATETIME_FORMAT)
    new_prog_str_t = new_prog_st_t.strftime('%Y%m%d')

    dates_to_delete.add(new_prog_str_t)
    svn_wks = datetime.datetime.now(TIMEZONE) - datetime.timedelta(weeks=7)
    is_less_than_7_weeks = new_prog_st_t > svn_wks

    if is_less_than_7_weeks:
        programmes_to_add.append(new_programme)

all_programmes = old_xml.findall('programme')
for programme in all_programmes:
    start = programme.get('start')
    start_time = datetime.datetime.strptime(start, DATETIME_FORMAT)
    svn_wks = datetime.datetime.now(TIMEZONE) - datetime.timedelta(weeks=7)
    is_older_than_7_weeks = start_time < svn_wks

    if is_older_than_7_weeks:
        old_xml.remove(programme)
    else:
        start_st_t = start_time.strftime('%Y%m%d')
        if start_st_t in dates_to_delete:
            old_xml.remove(programme)

for p in programmes_to_add:
    old_xml.append(p)

return old_xml


texts:
This challenge was pretty simple - be given the coordinates of a king and a queen on a chess board and determine if the king is in check.

Input is the number of test cases with each test case on a new line, king coordinates first. I read in via text file.

Output "Y" or "N" as the result for each test case.

e.g.

input data:
8
b4 b8
b4 e7
b4 d2
b4 g4
f2 b1
f2 c4
f2 d5
f2 g7

answer:
Y Y Y Y N N N N

I tried a bunch of stuff using System.Text.Encoding to try to figure out how to get the ascii char code from my letters, but ended up falling back on to what I know (Microsoft.VisualBasic).

Option Explicit On
Option Strict On
Option Infer On
Option Compare Text

Imports System.IO
Module Module1

    <STAThread>
    Sub Main()
        Const PATH = "C:\Temp\kingqueen.txt"
        Dim fileContents As String() = System.IO.File.ReadAllLines(PATH)
        Dim numberOfScenarios As Integer = Convert.ToInt32(fileContents(0))
        Dim result As String
        Dim king As String
        Dim queen As String
        For game As Integer = 1 To numberOfScenarios
            king = fileContents(game).Substring(0, 2)
            queen = fileContents(game).Substring(fileContents(game).Length - 2, 2)
            result = result & TestLines(king, queen) & " "
        Next
        result.Trim()
        Console.WriteLine(result)
    End Sub

    Private Function TestLines(ByVal king As String, ByVal queen As String) As String
        Dim kingsub As String = king.Substring(0, 1)
        If king.Substring(0, 1) = queen.Substring(0, 1) Or king.Substring(king.Length - 1, 1) = queen.Substring(queen.Length - 1, 1) Then
            Return "Y"
        Else
            Return TestDiagonals(king, queen)
        End If
    End Function

    Private Function TestDiagonals(ByVal king As String, ByVal queen As String) As String
        Dim kingRank As Integer = Microsoft.VisualBasic.Strings.AscW(king.Substring(0, 1))
        Dim kingFile As Integer = Convert.ToInt32(king.Substring(1, 1))
        Dim queenRank As Integer = Microsoft.VisualBasic.Strings.AscW(queen.Substring(0, 1))
        Dim queenFile As Integer = Convert.ToInt32(queen.Substring(1, 1))

        If (kingRank + kingFile = queenRank + queenFile) Or (kingRank - kingFile = queenRank - queenFile) Then
            Return "Y"
        Else
            Return "N"
        End If
    End Function
End Module


texts:
This is my implementation of a recursive binary search in C++. I'm still a newbie at C++ so:

Have I used any bad practices?
How could the code be improved upon in terms of efficiency?
Could recursion cause a stack overflow error, and if so how can I avoid this?

Criticism is welcome and appreciated!

#include<iostream>
#include<sstream>
#include<vector>

template <typename T>
void outputVector(std::vector<T> input){
    std::cout << "[";
    for(int i = 0; i < input.size(); i++){
        std::cout << input[i];
        if(i != input.size()-1){
            std::cout << ", ";
        }
    }
    std::cout << "]\n";
}

int binarySearch(std::vector<double> input, double target, int startIndex = 0){
    if(input.size() < 2){
        //std::cout << "Closest match found\n";
        return startIndex;
    }

    int middleIndex = int(input.size())/2;
    double middle = input[middleIndex];

    if(target == middle){
        return middleIndex + startIndex;
    }
    else if(target < middle){
        std::vector<double>::const_iterator begin = input.begin();
        std::vector<double>::const_iterator last = input.begin() + middleIndex;
        std::vector<double> firstHalf(begin, last);
        //std::cout << "First Half: ";
        //outputVector(firstHalf);
        return binarySearch(firstHalf, target, startIndex);
    }
    else if(target > middle){
        std::vector<double>::const_iterator begin = input.begin() + middleIndex + 1;
        std::vector<double>::const_iterator last = input.begin() + input.size();
        std::vector<double> secondHalf(begin, last);
        //std::cout << "Second Half: ";
        //outputVector(secondHalf);
        return binarySearch(secondHalf, target, startIndex+middleIndex+1);
    }
    else{
        return -1;
    }
}

std::vector<double> doubleVectorInput(){
    std::string inputString;
    getline(std::cin, inputString);
    std::vector<double> array;
    std::istringstream iss(inputString);
    float val;
    while(iss >> val){
        array.push_back(val);
    }
    return array;
}

int main(){
    double target;
    std::cout << "Vector to search: ";
    std::vector<double> input = doubleVectorInput();
    std::cout << "Target: "; std::cin >> target;
    std::cout << "Target index: " << binarySearch(input, target) << "\n";
    return 0;
}

Thank you.


texts:
Is there a better way to do it and have it be .Net 2.0 compatible?

public static DataTable GetErrorLog(int startRowIndex, int maximumRows, string sortExpression, string logPath)
{
    if (string.IsNullOrEmpty(sortExpression))
    {
        sortExpression = "fileName DESC";
    }

    DataTable errorLog = GetErrorLogDataTable();

    string[] filePaths = Directory.GetFiles(logPath);
    foreach (string filePath in filePaths)
    {
        DataRow row = errorLog.NewRow();
        row["fileName"] = Path.GetFileName(filePath);
        row["filePath"] = filePath;
        errorLog.Rows.Add(row);
    }

    DataView dataView = new DataView(errorLog);
    dataView.Sort = sortExpression;
    errorLog = dataView.ToTable();
    DataTable pagedErrorLog = errorLog.Clone();

    for (int i = startRowIndex; i < startRowIndex + maximumRows; i++)
    {
        if (i >= errorLog.Rows.Count)
        {
            break;
        }
        pagedErrorLog.ImportRow(errorLog.Rows[i]);
    }

    if (pagedErrorLog.Rows.Count <= 0)
    {
        return errorLog;
    }
    else
    {
        return pagedErrorLog;
    }
}

private static DataTable GetErrorLogDataTable()
{
    DataTable dataTable = new DataTable();
    dataTable.Columns.Add("fileName");
    dataTable.Columns.Add("filePath");
    return dataTable;
}


texts: Extract numbers from the head of a string in BASH script

texts:
In my current BASH script project I am processing a string, which cannot have spaces.

At one point I get to where it is possible to have a series of digits. The series can be of any length, including zero, up to the abilities of the shell to handle command line arguments, and need not be a valid decimal integer. Leading zeros are acceptable, decimal points are not, comma separators could be handled for human compatibility if needed.

At the end I should have two strings: the collected digits (stripped of commas if allowed) and the remainder of the original string following the last digit in the series. The original string has been partially consumed by other sections, and the remainder string will be consumed by other sections, which may include a return to this section if another series of digits becomes valid. The collection of digits will be handed off to another section to deal with, including any validation which might be needed.

The snippet I've settled on is this:

original_group="$1"
source_group="$original_group"
number_group=''
while case "${source_group::1}" in
    [[:digit:]] )
        number_group+="${source_group::1}"
        source_group="${source_group:1}"
        ;;
#    ',' )
#        source_group="${source_group:1}"
#        ;;
    * )
        false
esac; do :; done

# Output not normally in the script.
results_top="Removing numbers from the head of %s gives:\n"
results_list="\tDigits: %s\n\tBalance: %s\n"
printf "$results_top" "'$original_group'"
printf "$results_list" "'$number_group'" "'$source_group'"

The possible contents of the source, once it reaches this point, are in one of four types:

An empty string, (the last character could have sent it here and the empty has not been checked for)

Results should be a pair of empty strings

A non-empty string which begins with a non-digit character

Results should be an empty string for the number list and the untouched source for the remainder

A string with one, or more, digits, and nothing more

Results should be the digits for the number list and an empty string for the remainder

A string with one, or more, digits followed by one, or more, additional non-digit characters

Results should be the digits for the number list and the sub-string beginning with the first non-digit character for the remainder

In all four cases, there cannot be an error triggered by the process. (There are no invalid characters, and the series of digits may not be a 'number' in a mathematical sense; it could be an account number, for example.) Validation of the number belongs elsewhere, and the contents of the string are consumed, whether or not the results are valid for some other purpose.

Performance is not a major issue, it is a shell script. In addition, this section is unlikely to be executed more than 3 times in any execution, commonly once if at all. Likewise, Bashisms are not a concern here, as the remainder of the script is replete with such.

Part of my reasoning for using this snippet is the convenience of adding/removing support for commas in the number series, and the ease of changing from [[:digit:]] to [[:xdigit:]] should I need to implement the same general logic for hexadecimal digits later.

Is there something inherently wrong with this method? Or, is there a different method which is simply better, cleaner, or easier?

I avoided RegEx as either extractor, or loop conditional, under the belief that when not needed, RegEx introduces needless overhead. (Yes, performance is not a major issue here, but bad habits are worth avoiding as well.)


texts: Updating or adding data to an associative array as a cache

texts:
I have this if else statement where I don't know how to remove the code duplication

if(array_key_exists($key,$cachetable))
{
 if($cachetable[$key] != $newdata[$key])
  {
    //data existed but is not valid
    //update the cachetable
    $cachetable[$key] == $newdata[$key]
  }
}

else
{
    //data didn't existed before in cache so add it now
    //update the cachetable
    $cachetable[$key] == $newdata[$key]
 }


texts:
I am doing Project Euler problem 67 which involves finding the heaviest path through a triangle of integers like this one (this is a smaller version from an earlier problem)

75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

This is my code:

import Control.Monad (liftM)

addRows :: Integral a => [a] -> [a] -> [a]
addRows xs@(x:_) (y:ys) = x + y : addMid xs ys ++ [last xs + last ys]
    where addMid (a:b:bs) (c:cs) = c + max a b : addMid (b:bs) cs
          addMid _         _     = []

parse :: (Integral a, Read a) => String -> [[a]]
parse = map ((read <$>) . words) . lines

main = do
    tri <- liftM parse $ readFile "Triangles.txt"
    return $ maximum . foldl1 addRows $ tri

The above code works, however it seems inefficient in some respects. It seems like I'm not being as lazy as I should be with regards to my concatenation and use of last.


texts: SQL query that flattens many-to-one relationships

texts:
I have a database with these tables, where each mapping table represents a "many-to-one" relationship between the table on the right and the table on the left (click to enlarge):

I am selecting a single item from product and then adding on all of the other attributes through joins. Here is my current SQL:

SELECT
    p.id,
    p.name,
    p.price,
    p.description,
    GROUP_CONCAT(DISTINCT c.name SEPARATOR ",") AS categories,
    GROUP_CONCAT(og.options SEPARATOR ";") AS options
FROM
    product p
    LEFT JOIN product_category pc ON p.id = pc.product_id
    LEFT JOIN category c ON c.id = pc.category_id
    LEFT JOIN product_optiongroup pog ON p.id = pog.product_id
    LEFT JOIN (
        SELECT
            og.id AS id,
            CONCAT(
                og.name,
                ":",
                GROUP_CONCAT(oi.value)
            ) AS options
        FROM
            optiongroup og
            LEFT JOIN optiongroup_optionitem ogoi ON og.id = ogoi.optiongroup_id
            LEFT JOIN optionitem oi ON oi.id = ogoi.optionitem_id
        GROUP BY og.id
    ) AS og ON og.id = pog.optiongroup_id
WHERE
    p.id = 1 -- This is the input

My desired output is something like:

id    name    price    description    categories     options
-------------------------------------------------------------------------------------------
1     Big Hat 10.00    A good hat.    Hats,Clothing  Color:Black,White;Style:Baseball,Sun

My concern is, would this be a terrible pain to maintain? Are there simpler solutions? Also, does it need to be optimized & how? I don't have much experience with SQL. The output format isn't set in stone; I'm working solo.


texts:
The goal of this code is to format any log to STDOUT and STDERR with the file and the line of where the call is made. I took inspiration from different C loggers that I found on the internet. I want it to be small and efficient while using C++17.

I'm a bit suspicious about the call to std::data at line 30 not being null-terminated.

#include <iostream>
#include <string_view>
#include <array>

enum Log_level
{
    L_SILENT = 0,
    L_ERROR = 1,
    L_INFO = 2,
    L_DEBUG = 3,
};

static Log_level log_level = L_ERROR;

static constexpr std::array log_colors
{
    "",
    "\x1B[1;31m",
    "\x1B[1;34m",
    "\x1B[1;30m"
};

template<typename... Args>
void vlk_log_internal(const Log_level level, const std::string_view s, Args... args)
{
    std::FILE* output = (level == L_ERROR ? stderr : stdout);
    if (level <= log_level)
    {
        std::fprintf(output, "%s", log_colors[level]);
        std::fprintf(output, std::data(s), args...);
        std::fprintf(output, "\x1B[0m");
        std::fprintf(output, "\n");
    }
}

#define vlk_log(lvl, msg, ...) { vlk_log_internal(lvl, "[%s:%d] " msg, __FILE__, __LINE__, ##__VA_ARGS__); } (void)0

int main()
{
    log_level = L_SILENT;

    vlk_log(L_ERROR, "Error will not show");

    log_level = L_ERROR;

    vlk_log(L_ERROR, "Error %s", "msg");
    vlk_log(L_INFO, "Info will not show");

    log_level = L_INFO;

    vlk_log(L_INFO, "Info %s", "msg");
    vlk_log(L_DEBUG, "Debug will not show");

    log_level = L_DEBUG;

    vlk_log(L_DEBUG, "Debug %s", "msg");

    return 0;
}

Compiler Explorer link


texts:
Is this way acceptable to do a C# singleton for use in ASP.NET webforms legacy app:

public class FileSingleton
{
    private static readonly Lazy<FileSingleton> lazy =
        new Lazy<FileSingleton>(() => new FileSingleton( new FileRepository()));

    public static FileRepository Repository { get; private set; }

    public static FileSingleton Instance { get { return lazy.Value; } }

    private FileSingleton(FileRepository repository)
    {
        Repository = repository;
    }
}

I created a repository for dealing with files in Azure. It has some overhead, so I don't want to instantiate it on every request. My design is based off of this post.

protected void Application_Start(object sender, EventArgs e)
{

    HttpContext.Current.Items.Add("fileRepository", FileSingleton.Instance);
}

Does that seem reasonable? Is there a better way to do this?


texts: Google Guice module that loads two kinds of views

texts:
The code of my Guice Module looks like this:

public class FXMLModule extends AbstractModule {

    private final Locale locale = Locale.getDefault();
    private final ResourceBundle messages = ResourceBundle.getBundle("i18n.messages", locale);

    @Override
    protected void configure() {
        bind(Controller.class).annotatedWith(MainView.class).to(MainController.class);
        bind(Controller.class).annotatedWith(MovieView.class).to(MovieViewController.class);
    }

    @Provides @MainView
    public FXMLLoader mainViewLoader(@MainView Controller controller) {
        FXMLLoader loader = new FXMLLoader(locate("/jfx/fxml/MainView.fxml"), messages);
        loader.setController(controller);
        return loader;
    }

    @Provides @MovieView
    public FXMLLoader movieViewLoader(@MovieView Controller controller) {
        FXMLLoader loader = new FXMLLoader(locate("/jfx/fxml/MovieView.fxml"), messages);
        loader.setController(controller);
        return loader;
    }

    private URL locate(String location) {
        return getClass().getResource(location);
    }

}

Basically I want to inject fully configured FXMLLoaders into some Controller classes, so that they can work with the root nodes returned from the loaders without having to know anything about other controllers. The MainViewLoader gets injected into the Application class, and the MovieViewLoader gets injected into MainViewController. It works, but I'd have to write a provide method (with almost the same code) for every loader/controller. Any ideas how to make this more generic?


texts: A general-use For-comprehensible Loan Pattern

texts:
I use Scala's loan pattern in order to ensure and automate the resource aquisition and release after its use. When multiple resources have to be acquired at once, however, the function calls must be nested, impairing readability.

Scala ARM supports for-comprehension to avoid the nesting. However, in order to have Scala ARM manage resources, the managed class must extend scala.resource.Resource or simply AutoCloseable, which requires a definiton of close() method.

I'd like to avoid defining close() methods because it separates aquisition and release into different methods but I believe such operations are so tightly coupled that keeping them close will enhance the maintainability.

My idea is to restrict resource access to only via certain loaner-functions, while supporting for-comprehension to keep readability.

So, I wrote a trait ForComprehensible:

/**
 * @tparam A The type of the loaned object.
 */
trait ForComprehensible[+A] {
  /**
   * The loaner-function. Subclasses must define this.
   *
   * @tparam B The result type of the callback
   * @param  f The callback
   * @return The result value of the callback
   */
  def apply[B](f: A => B) : B

  def map[B](f: A => B)     : B    = apply(f)
  def flatMap[B](f: A => B) : B    = apply(f)
  def foreach[B](f: A => B) : Unit = { apply(f); () }

  // The methods filter and withFilter are omitted on purpose because they don't make sense.
}

Since ForComprehensible defines the apply method, client code can use one much like an ordinary loaner-function. Here is a simple example program which copies a content of a file into another:

import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import scala.annotation.tailrec

// Opens a FileInputStream and loans it to the callback. After that, closes the stream.
def withInputStream(infilename: String) = new ForComprehensible[FileInputStream] {
  override def apply[B](f: FileInputStream => B) = {
    val res = new FileInputStream(infilename)
    try {
      f(res)
    } finally {
      res.close()
    }
  }
}

// Opens a FileOutputStream and loans it to the callback. After that, closes the stream.
def withOutputStream(outfilename: String) = new ForComprehensible[FileOutputStream] {
  override def apply[B](f: FileOutputStream => B) = {
    val res = new FileOutputStream(outfilename)
    try {
      f(res)
    } finally {
      res.close()
    }
  }
}

// Pipes all the content of the input stream into the output stream.
@tailrec def pipe(is: InputStream, os: OutputStream) : Unit = {
  val bytes = new Array[Byte](1024)
  val n = is.read(bytes)
  if (n >= 0) {
    os.write(bytes, 0, n)
    pipe(is, os)
  }
}

// The following are equivalent. Both automatically close streams.
// Without for-comprehension:
withInputStream("input.txt"){ is =>
  withOutputStream("output.txt"){ os =>
    pipe(is, os)
  }
}

// With for-comprehension:
for {
  is <- withInputStream("input.txt")
  os <- withOutputStream("output.txt")
} {
  pipe(is, os)
}

It works and looks nice. Before writing this, I googled for "scala loan pattern for-comprehension" and found nothing looking relevant. I think this trait is quite straight-forward and I doubt no one ever come up with something like this.

So I've got skeptical; is there any problem with this?


texts:
Background

I'm writing a wrapper for a significant portion of a native library in Java. The native objects my classes are wrapping are giving me some headaches in terms of design.

I'm not a fan of the two-step initialization idiom but I've resigned myself to use it if the native object has a lot of configuration options followed by a rather complex and error-prone initialization.

The real issue is that I still have some constructors that throw exceptions after native resources have been allocated, though I'm able to avoid it in most cases. All classes wrapping native resources implement the Disposable interface.

public interface Disposable extends AutoCloseable
{
   boolean isClosed();

   @Override
   void close();
}

The close method is always written in the most safest way, making no assumptions about the state of the object. Okay, so I can call it from the constructor... that is unless there are subclasses that override this method.

Code

So I've been thinking about an elegant solution to solve these problems. I've decided to upgrade the allocation and deallocation of native objects to full object status.

public interface Resource<T> extends Disposable
{
    T get();
}

These Resource objects are supposed to be pushed onto a stack that is shared with every class in the hierarchy so there is no longer a need to override the close method of a base class.

I have an abstract implementation that lazily allocates the native object once and returns it. I cannot use the double checked locking idiom to do this because I'm dealing with three states.

Either the native object hasn't been allocated, either it has, or it has been deallocated. If it has been deallocated, I don't want the possibility that it may accidentally be reallocated.

public abstract class AbstractResource<T> implements Resource<T>
{
    private enum State
    {
        INITIAL,
        ALLOCATED,
        DISPOSED
    }

    private final AtomicReference<State> refState;
    private final AtomicReference<T> refResource;

    public AbstractResource()
    {
        this.refState = new AtomicReference<>(State.INITIAL);
        this.refResource = new AtomicReference<>(null);
    }

    @Override
    public boolean isClosed() {
        return this.refState.get() == State.DISPOSED;
    }

    @Override
    public T get()
    {
        final State currentState = this.refState.get();
        T resource = this.refResource.get();

        if (currentState == State.DISPOSED)
            throw new ObjectDisposedException(resource.getClass().getName());

        if (currentState == State.INITIAL) {
            if (this.refState.compareAndSet(State.INITIAL, State.ALLOCATED)) {
                try {
                    resource = this.allocate();
                    this.refResource.set(resource);
                } catch (Exception ex) {
                    this.refState.set(State.INITIAL);
                    throw ex;
                }
            }
        }
        return resource;
    }

    protected abstract T allocate();

    @Override
    public void close()
    {
        if (this.refState.getAndSet(State.DISPOSED) == State.ALLOCATED)
            this.release(this.refResource.get());
    }

    protected abstract void release(final T resource);
}

Is this class 100% thread-safe or have I missed anything? Might there be a better way to do this that does not require locking or at least keep it to a minimum?


texts:
I've never really done anything with concurrency, so I'm not sure if this is done correctly.

Basically, I have a class that handles all messages from the server and decides what to do them. It uses a separate thread to keep looping through a list to check for any new messages it has to deal with.

The main server thread needs to be able to add messages to the ArrayList without causing a concurrency error, and so far it seems ok but I don't have that many messages coming in.

public class MessageThread implements Runnable {
    public static ArrayList<Message> messages = new ArrayList<Message>();

    @Override
    public void run() {
        while (true) {
            synchronized (messages) {

                for (Message m : messages) {

        }
    }
}
    public static void addMessage(Message message) {
        synchronized (messages) {
            messages.add(message);
        }
    }

    public static void removeMessage(Message message) {
        synchronized (messages) {
            messages.remove(message);
        }
    }
}

So as you can see, the server thread would use the MessageThread.addMessage method whenever it needs to add a message.


texts:
I'm printing a diamond shape in Java. It's working fine, but is there a way to re-write this code to make it faster?

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

sc.close();

String ns = String.valueOf(n);
int z = n/2;

int k = n%2;

for (int j = 0 ; j<n;j++) {

    for (int i = 0; i < z; i++)
        System.out.print(" ");
    for (int i = 0; i < k ; i++){
        System.out.print("*");
    if (i==k-1)
        System.out.print("\n");
    }

    if ((k-n)==0)
        break;
    z--;
    k=k+2;

}

 z = (n)/2;

 k = (n)%2;
int w = k;
int y = n-2;

for (int j = 0 ; j<z  ;j++) {

    for (int i = 0 ; i<w;i++)
    System.out.print(" ");

    for (int i = 0 ; i< y ;i++)
        System.out.print("*");
    w=w+1;
    y=y-2;

    System.out.print("\n");

}


texts:
I implemented the Haversine formula to calculate the distance between two (latitude, longitude) coordinates.

I was wondering if it looks natural to Clojure programmers.  What could be improved?

(ns br.com.reactive-poc.calc)

(def raio 6372.795477598)

(defn calculate-distance
"Calcula distância entre duas coordenadas geográficas"
([source to]
  {:pre [every? (every-pred map? #(contains? % :lgt) #(contains? % :ltd)) [source to]]}
  (let [delta-latitude (Math/toRadians (- (:source/ltd source) (:to/ltd to)))
        delta-longitude (Math/toRadians (- (:source/lgt source) (:to/lgt to)))
        ]
    (* (* raio (* 2 (Math/atan2 (Math/sqrt (+ (Math/pow (Math/sin (/ delta-latitude 2)) 2)
                                              (* (Math/cos (Math/toRadians (:source/ltd source))) (Math/cos (Math/toRadians (:to/ltd to))) (Math/sin (/ delta-longitude 2)) (Math/sin (/ delta-longitude 2)))))
                                (Math/sqrt (- 1 (+ (Math/pow (Math/sin (/ delta-latitude 2)) 2)
                                                   (* (Math/cos (Math/toRadians (:source/ltd source))) (Math/cos (Math/toRadians (:to/ltd to)) ) (Math/sin (/ delta-longitude 2)) (Math/sin (/ delta-longitude 2))))))))) 1000)
    )
  )
)


texts:
I am coding an interview question from Yahoo Software Engineer Intern Interview.

  Given an unordered list of numbers, find all pairs that add up to x.

I have a working solution in Java:

    public static void main (String args[]){
        int[] numbers = new int[]{2, 5, 7, 3, 9, 4, 1, 8}; //input array
        int x = 6; //target sum

        int[] result = new int[numbers.length]; //stores the output pairs
        int count = 0;

        int[] sorted = numbers;
        Arrays.sort(sorted);
        int beg = 0;
        int end = numbers.length-1;
        while (beg < end){
            int sum = sorted[beg] + sorted[end];
            if (sum > x)
                end--;
            else if (sum == x){
                result[count++] = sorted[beg];
                result[count++] = sorted[end];
                end--; beg++;
            }
            else if (sum < x)
                beg++;
        }
    }

Looking for code review optimizations and best practices.


texts: Vertical & Horizontal Direction of a DataTable

texts:
I wanted to have a DataTable with cells in direction that is top to bottom or bottom to top and left to right or right to left.

LR - LEFT to RIGHT
RL - RIGHT to LEFT
BT - BOTTOM to TOP
TB - TOP to BOTTOM

To do that, below is the method I created

    internal DataTable GetContainerLocationMap(int row, int column, string bayCode, string horizontalDirection, string verticalDirection)
    {
        var pageMap = new DataTable();

        if (horizontalDirection == "LR")
        {
            for (int i = 1; i <= column; i++)
            {
                pageMap.Columns.Add("C" + i);
            }
            if (verticalDirection == "BT")
            {
                for (int i = row; i > 0; --i)
                {
                    var _pageMapRow = pageMap.NewRow();
                    for (int j = 1; j <= column; j++)
                    {
                        _pageMapRow["C" + j] = string.Format("{0}-{1}-{2}", bayCode, j, i);
                    }
                    pageMap.Rows.Add(_pageMapRow);
                }
            }
            else if (verticalDirection == "TB")
            {
                for (int i = 1; i <= row; i++)
                {
                    var _pageMapRow = pageMap.NewRow();
                    for (int j = 1; j <= column; j++)
                    {
                        _pageMapRow["C" + j] = string.Format("{0}-{1}-{2}", bayCode, j, i);
                    }
                    pageMap.Rows.Add(_pageMapRow);
                }
            }
        }
        else if (horizontalDirection == "RL")
        {
            for (int i = column; i > 0; --i)
            {
                pageMap.Columns.Add("C" + i);
            }
            if (verticalDirection == "BT")
            {
                for (int i = row; i > 0; --i)
                {
                    var _pageMapRow = pageMap.NewRow();
                    for (int j = column; j > 0; --j)
                    {
                        _pageMapRow["C" + j] = string.Format("{0}-{1}-{2}", bayCode, j, i);
                    }
                    pageMap.Rows.Add(_pageMapRow);
                }
            }
            else if (verticalDirection == "TB")
            {
                for (int i = 1; i <= row; i++)
                {
                    var _pageMapRow = pageMap.NewRow();
                    for (int j = column; j > 0; --j)
                    {
                        _pageMapRow["C" + j] = string.Format("{0}-{1}-{2}", bayCode, j, i);
                    }
                    pageMap.Rows.Add(_pageMapRow);
                }
            }
        }

        return pageMap;
    }

If you call above method by these params

GetContainerLocationMap(2, 5, "A", "LR", "TB");

It would return DataTable like below:

A-1-1   A-2-1   A-3-1   A-4-1   A-5-1
A-1-2   A-2-2   A-3-2   A-4-2   A-5-2

I would like to know the code I have written is all okay or do I need to make it more simple?

Thanks in advance


texts:
I am trying to sort the options within a SELECT element. I wonder if I am doing it stupidly or not, so perhaps someone can look at it and provide suggestions.

// Function Name            = sortSelect(jsID, tagAttr)
// Function Purpose         = Sort elements within a select element by supplying the ID of the select element. Sorting parameter is based on the order of the tags passed in through tagAttr as an array with decreasing importance. CSS styles can be use as a sort parameters as well with syntax css:
// Example Call             = sortSelect("element", ["css: display", "id"]);

function sortSelect(jsID, tagAttr) {
    var jqID = "#"+jsID;
    var arrHold = [];
    var arrTemp = [];
    var arrObjs = [];
    var ct;
    var comp;

    if ($(jqID).prop("tagName").toUpperCase() == "SELECT") {
        $(jqID + " option").each(function() {
            arrHold = [];
            arrHold.push($(this));

            for (var j in tagAttr) {
                if (tagAttr[j].replace(/\s+/g, '').substring(0, 4) !== "css:") {
                    arrHold.push($(this).attr(tagAttr[j]));
                } else {
                    arrHold.push($(this).css(tagAttr[j].replace(/\s+/g, '').substring(4, tagAttr[j].length).trim()));
                }

                j+=1;
            }

            arrTemp.push(arrHold);
            ct+=1;
        });

        if (ct < $("#"+jsID).childElementCount) {
            var message = "Nodes other than 'option' has been detected, and may have been lost!"
            console.warn(message);
        }

        arrTemp = arrTemp.sort(function(a,b) {
            for (i=1; i<=tagAttr.length; i++) {
                comp = (''+a[i]).localeCompare(b[i]);

                if (comp != 0) {
                    return comp;
                }
            }

            return 0;
        });

        for (i=0; i < arrTemp.length; i++) {
            arrObjs.push(arrTemp[i][0]);
        }

        $(jqID).empty();
        $(jqID).append(arrObjs);
    }
}


texts:
Generate as many distinct primes P such that reverse (P) is also prime
  and is not equal to P.

  Output: Print per line one integer( ≤ 10^15 ). Don't print more than
  10^6 integers in all.

  Scoring: Let N = correct outputs. M = incorrect outputs. Your score
  will be max(0,N-M).

  Note: Only one of P and reverse(P) will be counted as correct. If both
  are in the file, one will be counted as incorrect.

  Sample Output: 107 13 31 17 2

  Explanation

  Score will be 1. Since 13,107,17 are correct. 31 is incorrect because
  13 is already there. 2 is incorrect.

  Time Limit: 2 sec(s) for each input file. Memory Limit: 256 MB Source
  Limit: 25 KB

public class ReversePrime {

    final static int MAX = 1000000;
    final static int MAXLISTSIZE = 1000000;
    final static int BASE = 10;

    final static boolean[] isPrime = generatePrime();

    public static void main(String args[]) {
        Set<Long> reversedCheckedPrime = new LinkedHashSet<Long>();
        int isPrimeLength = isPrime.length;
        for (int i = 0; i < isPrimeLength; i++) {
            if (isPrime[i]) {
                long prime = 2 * i + 3;
                long reverse = reversePrime(prime);
                if ((!(prime == reverse))
                        && (!reversedCheckedPrime.contains(reverse))
                        && (reversedCheckedPrime.size() <= MAXLISTSIZE)) {
                    reversedCheckedPrime.add(prime);
                }
                if (reversedCheckedPrime.size() == MAXLISTSIZE) {
                    break;
                }
            }
        }

        for (Long prime : reversedCheckedPrime) {
            System.out.println(prime);
        }

    }

    private static long reversePrime(long prime) {
        long result = 0;
        long rem;
        while (prime != 0) {
            rem = prime % BASE;
            prime = prime / BASE;
            result = result * BASE + rem;
        }
        return result;
    }

    private static boolean[] generatePrime() {
        int root = (int) Math.sqrt(MAX) + 1;
        root = root / 2 - 1;
        int limit = (int) ((MAX - 1) / 2);
        boolean[] isPrime = new boolean[limit];
        Arrays.fill(isPrime, true);
        for (int i = 0; i < root; i++) {
            if (isPrime[i]) {
                for (int j = 2 * i * (i + 3) + 3, p = 2 * i + 3; j < limit; j = j
                        + p) {
                    isPrime[j] = false;
                }
            }

        }
        return isPrime;
    }
}

While the code is working the real concern is the time limit. I'm not able to get it below 2 seconds. How could I further improve the runtime?

One way I reduced it further by avoiding the println() call in the for loop by doing this:

StringBuilder outputResult = new StringBuilder();
        for (int i = 0; i < isPrimeLength; i++) {
            if (isPrime[i]) {
                long prime = 2 * i + 3;
                long revrse = reversePrime(prime);
                if ((!(prime == revrse))
                        && (!reversedCheckedPrime.contains(revrse))
                        && (reversedCheckedPrime.size() <= MAXLISTSIZE)) {
                    reversedCheckedPrime.add(prime);
                    outputResult.append(prime);
                    outputResult.append("\n");
                }
                if (reversedCheckedPrime.size() == MAXLISTSIZE) {
                    break;
                }
            }
        }

        System.out.println(outputResult);
    }

Question link for submission


texts:
What would be the best approach to write this class.

This class validates 3 types of passwords,

Normal
Medium
Strong

Github Link

<?php namespace azi\Rules;

use azi\Arguments;
use azi\Rules\Contracts\RuleInterface;

/**
 * Class Password
 *
 * @package azi\Rules
 */
class Password implements RuleInterface
{
    const NORMAL = 'normal';
    const MEDIUM = 'medium';
    const STRONG = 'strong';

    protected $message = null;

    /**
     * @param $field
     * @param $password
     * @param Arguments $args
     * @return mixed
     */
    public function validate($field, $password, Arguments $args)
    {
        $type = $args->getVariables();

        if ($type && $type != self::NORMAL) {
            return $this->is($type[ 0 ], $password);
        }

        return $this->isNormal($password);
    }

    /**
     * @param $strength
     * @param $password
     * @return bool
     */
    public function is($strength, $password)
    {
        $method = sprintf("is%s", ucwords($strength));
        return call_user_func([$this, $method], $password);
    }

    /**
     * @param $password
     * @return bool
     */
    public function isNormal($password)
    {
        if (strlen($password) < 8) {
            $this->message = '{field} must be at least 8 characters long';
            return false;
        }

        if (!preg_match("#[a-zA-Z]#", $password)) {
            $this->message = '{field} must contain at least one letter';
            return false;
        }

        return true;
    }

    /**
     * Checks a strong password
     *
     * @param $password
     * @return bool
     */
    public function isStrong($password)
    {
        if (!$this->isMedium($password)) {
            return false;
        }

        if (!preg_match("#[!@\#\$%^&*()_+\-=\[\]{};':\"\\|,.<>\/?]+#", $password)) {
            $this->message = '{field} must contain at least special character';
            return false;
        }

        return true;
    }

    /**
     * @param $password
     * @return bool
     */
    public function isMedium($password)
    {
        if (!$this->isNormal($password)) {
            return false;
        }

        if (!preg_match("#[a-z]#", $password)) {
            $this->message = '{field} must contain at least one lowercase letter';
            return false;
        }

        if (!preg_match("#[A-Z]#", $password)) {
            $this->message = '{field} must contain at least one uppercase letter';
            return false;
        }

        return true;
    }

    /**
     * @return mixed
     */
    public function message()
    {
        if ($this->message) {
            return $this->message;
        }

        return "{field} must be a good password";
    }
}