texts: Adding new or existing tags to a blog post

texts:
I'm working on a simple blogsystem (for learning purposes, not to reinvent the wheel). In this system the user can add existing or new tags to a blogpost. I wrote a method to achieve this, but it's ugly, inconvenient and probably of bad performance.

Some facts:

I make use of Propel as mapper to a PostgreSQL database
relevant tables in this part are tag and post_tag

CREATE-Statements:

CREATE TABLE tag (
    id integer NOT NULL,
    name character varying(100),
    slug character varying(100),
    modified timestamp(0) without time zone
);

CREATE SEQUENCE tag_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

ALTER TABLE ONLY tag
    ADD CONSTRAINT tag_pkey PRIMARY KEY (id);

ALTER TABLE ONLY tag ALTER COLUMN id SET DEFAULT nextval('tag_id_seq'::regclass);

CREATE TABLE post_tag (
    post_id integer NOT NULL,
    tag_id integer NOT NULL
);

ALTER TABLE ONLY post_tag
    ADD CONSTRAINT post_tag_pkey PRIMARY KEY (post_id, tag_id);

ALTER TABLE ONLY post_tag
    ADD CONSTRAINT post_tag_post FOREIGN KEY (post_id) REFERENCES post(id) ON UPDATE CASCADE ON DELETE CASCADE;

ALTER TABLE ONLY post_tag
    ADD CONSTRAINT post_tag_tag FOREIGN KEY (tag_id) REFERENCES tag(id) ON UPDATE CASCADE ON DELETE CASCADE;

The method is called after submitting the post. It gets the postID and an array containing all tags assigned to this post. It adds new tags in the table tag and makes sure that in table post_tag all new, all previously existing and all previously existing but not assigned tags, which the user chose, are connected to the post.

This is the method:

      public function addTagByPost($posttags, $postid){

        //collect all existing tags
        $all = $this->getAllTags();

        $existing = array();
        foreach($all AS $tags){
            $existing[$tags->getName()] = $tags->getId();
        }

        //delete all tags linked to the post
        $links = PostTagQuery::create()
            ->filterByPostId($postid);

        $links->delete();

        foreach($posttags AS $tag){
            if(!isset($existing[$tag])){
                //add new tags from post
                $newtag = new Tag();
                $newtag->setName($tag);
                $newtag->setSlug($this->generateSlug($tag));
                $newtag->save();
                $tagid = $newtag->getId();
            }else{
                $tagid = $existing[$tag];
            }

            //link all tags to the post
            $link = new PostTag();
            $link->setPostId($postid);
            $link->setTagId($tagid);
            $link->save();

        }
    }

Imagine in table tag are three rows, PHP, MySQL and PostgreSQL. Imagine there is a blogpost tagged with PHP and PostgreSQL. The user edits the post, removing the tag PHP and adding the tag Python. When he submits, the current tags are PostgreSQL and Python.

At first, all existing tags are fetched from db (PHP, MySQL and PostgreSQL).
Then all links between the current post and its tags are deleted from table post_tag (PHP and PostgreSQL).

Now the tags assigned by the user (PostgreSQL and Python) are matched against the existing ones (PHP, MySQL and PostgreSQL). As Python does not already exist, it is added to table tag.

Now, all userassigned tags are accessible via id. These IDs are then inserted into table post_tag (PostgreSQL and Python), so the post is connected to them.

Please feel free to make suggestions.


texts: Similar manipulations on several numpy arrays

texts:
I have n numpy arrays which all contain time series data for t periods. It is not an option to instead have one nxt matrix. I am storing all these arrays in a ResultSimulation object.

I seem to have repetitive code, which I am wondering how to shorten.

It starts with

ResultSimulation.v0 = ResultSteadyState.v0[::-1].copy()
ResultSimulation.v1 = ResultSteadyState.v1[::-1].copy()
ResultSimulation.nl = ResultSteadyState.nl[::-1].copy()
ResultSimulation.nh = ResultSteadyState.nh[::-1].copy()
ResultSimulation.ul = ResultSteadyState.ul[::-1].copy()
ResultSimulation.uh = ResultSteadyState.uh[::-1].copy()
ResultSimulation.V1 = ResultSteadyState.V1[::-1].copy()

at some place there is

# nTSteady is some number
ResultSimulation.v0 = ResultSimulation.v0[:nTSteady]
ResultSimulation.v1 = ResultSimulation.v1[:nTSteady]
ResultSimulation.nl = ResultSimulation.nl[:nTSteady]
ResultSimulation.nh = ResultSimulation.nh[:nTSteady]
ResultSimulation.ul = ResultSimulation.ul[:nTSteady]
ResultSimulation.uh = ResultSimulation.uh[:nTSteady]
ResultSimulation.V1 = ResultSimulation.V1[:nTSteady]

and finally,

addZeros = np.zeros((additionalSize,))
ResultSimulation.v0 = np.concatenate((ResultSimulation.v0, addZeros))
ResultSimulation.v1 = np.concatenate((ResultSimulation.v1, addZeros))
ResultSimulation.nl = np.concatenate((ResultSimulation.nl, addZeros))
ResultSimulation.nh = np.concatenate((ResultSimulation.nh, addZeros))
ResultSimulation.ul = np.concatenate((ResultSimulation.ul, addZeros))
ResultSimulation.uh = np.concatenate((ResultSimulation.uh, addZeros))

I guess one way to reduce this repetitive code, is to use "variable variable names", a practice that isn't encouraged in Python. Another alternative is to store them not directly in the object, but in an intermediate dict:

for series in ResultSimulation.myDict:
    ResultSimulation.myDict[series] = ResultSteadyState.myDict[series].copy()

for the first case. Say I don't like these two options+. What else can I do?

+: I dont mind creating an intermediate dictionary, but I want to keep my numpy arrays as properties of the object, and not stored in a dictionary within the object.


texts:
I need to extract all numbers before a colon in a string, e.g.:

abc1234:blah -> 1234
5n63:124 -> 63
stringwithnocolon -> ""
stringwith:nonumber -> ""

Limitations:

no external dependency (looking forward to keep it simple)
no << operator allowed
not C++11

Here is the code I came up with:

const std::string DNAStorage::get_block(const std::string& name)
{
    char* buffer = new char[name.size()];
    char* temp = new char[name.size()];
    size_t i, j;
    for (i = 0; i < name.size(); i++)
    {
        if (name[i] == ':')
            break;

        buffer[i] = name[i];
    }

    if (i == name.size())
        return ""; // : not found, cannot be done

    for (j = i - 1; i > 0; j--)
    {
        if (!isdigit(buffer[j]))
            break;

        temp[i - j - 1] = buffer[j];
    }

    temp[i - j - 1] = '\0';

    std::string result = std::string(temp);
    std::reverse(result.begin(), result.end());
    return result;
}

But I don't really like it. How could I make this code better?


texts: Universally unique 64 bit long generator

texts:
I'm trying to make an ID generator that generates 64 bit longs. The IDs should be globally unique even between two offline machines. This is the same idea as UUID (GUID), but UUID is 128 bit long and contains redundant (constant) bits (eg. it uses the millisecs passed since the year 1980 and has 5-8 versioning bits). I could use either the least or most significant 64 bits of a UUID, but because it contains these constant bits, it may not be unique enough.

So I made my own logic. It's important that it has to run everywhere, so I can't use MAC address, because it's not always accessible (eg. on Android). What do you think of my code?

public class UID {

private static long swRndVal;
private static Random random = new Random();
private static final long mstsigMask = 0b11111111_00000000_00000000_00000000_00000000_00000000_00000000_00000000L;
private static final long middleMask = 0b00000000_11111111_11111111_11111111_11111111_11111111_11111111_11111111L;
private static final long lstsigMask = 0b00000000_00000000_00000000_00000000_00000000_00001111_11111111_11111111L;

static {
    String s1 = System.getProperty("os.arch", "");
    String s2 = System.getProperty("os.version", "");
    String s3 = System.getProperty("java.vm.version", "");
    String s4 = System.getProperty("java.class.version", "");
    Random rand1 = new Random((s1+s2+s3+s4).hashCode());
    Random rand2 = new Random();
    swRndVal = rand1.nextLong() ^ rand2.nextLong();
}

public static long getUniqueLong() {
    //8 bits of random, 36 bits of millis (~800 days), 20 bits of nanos (~1ms)
    return ((random.nextLong() & mstsigMask) | (System.currentTimeMillis() & middleMask) | (System.nanoTime() & lstsigMask)) ^ swRndVal;
}
}


texts:
This is a function for JavaScript validation:

var alpha = "[ A-Za-z]";
var numeric = "[0-9]";
var alphanumeric = "[ A-Za-z0-9]";

function onKeyValidate(e,charVal){
    var keynum;
    var keyChars = /[\x00\x08]/;
    var validChars = new RegExp(charVal);
    if(window.event)
    {
        keynum = e.keyCode;
    }
    else if(e.which)
    {
        keynum = e.which;
    }
    var keychar = String.fromCharCode(keynum);
    if (!validChars.test(keychar) && !keyChars.test(keychar))   {
        return false
    } else{
        return keychar;
    }
}

and HTML code:

<input type="text"  name="shipname"  onkeypress="return onKeyValidate(event,alpha);"/>
<input type="text"  name="price"   onkeypress="return onKeyValidate(event,numeric);" />

I want to know about code quality, creating issues or any alternative for this.  I need some suggestion from experts.


texts: Triangle calculator: calculate if it's a valid triangle and what type

texts:
This is my first program and I wanted to know if there was any way to improve the design or cut back on unnecessary coding.

import java.util.Scanner;

public class Main {

    public static void main(String args[]) {

        int side1; int side2; int side3;
        int side1s; int side2s; int side3s;
        Boolean Triangle;
        String TriangleType;
        String Q1 = "What is the first side of the Triangle?";
        String Q2 = "What is the second side of the Triangle?";
        String Q3 = "What is the third side of the Triangle?";

        Scanner input = new Scanner(System.in);
        System.out.println(Q1);
        side1 = input.nextInt();

        Scanner input2 = new Scanner(System.in);
        System.out.println(Q2);
        side2 = input2.nextInt();

        Scanner input3 = new Scanner(System.in);
        System.out.println(Q3);
        side3 = input3.nextInt();

        if(side1 + side2 > side3) {
            Triangle = true;
            System.out.println("The triangle is true!");

        } else {
            Triangle = false;
            System.out.println("The Triangle is False!");
            return;

        }

        if(Triangle == true) {
            side1s = side1 * side1;
            side2s = side2 * side2;
            side3s = side3 * side3;

            if(side1s + side2s == side3s) {
                TriangleType = "Right";

                System.out.println("The Triangle is..." + TriangleType);

            } else if (side1s + side2s > side3s) {
                TriangleType = "Acute";

                System.out.println("The Triangle is..." + TriangleType);

            } else if(side1s + side2s < side3s) {
                TriangleType = "Obtuse";

                System.out.println("The Triangle is..." + TriangleType);

            } else {
                TriangleType = null;

                System.out.println("The Triangle is..." + TriangleType);

            }

        }
    }

}


texts:
I'm building a GWT application for GAE, using JDO for Datastore access. I use and Entity class for data mapping, so it contains lots of Persistence annotations:

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class AppointmentEntity implements Serializable {

    private static final long serialVersionUID = 1L;
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;
    @Persistent
    private String firstName;
    @Persistent
    private String lastName;
    @Persistent
    private String DNI;
    @Persistent
    private Date appointmentDate;
    @Persistent
    private String attendant;
    @Persistent
    private String treatment;
    @Persistent
    private String details;
    @Persistent
    private Date nextAppointment;
    @Persistent(serialized = "true")
    private DownloadableFile file;

    //getters and setters...

Because of GWT and JDO nature, i can't use this Entity classes in my presentation layer; so there's a need of passing Entity Object attributes to the corresponding DTO, which is a POJO that has the same attributes of the Entity class:

public class AppointmentDTO implements Serializable {

    private static final long serialVersionUID = 1L;
    private Long id;
    private String firstName;
    private String lastName;
    private String DNI;
    private Date appointmentDate;
    private Date nextAppointmentDate;
    private String attendant;
    private String treatment;
    private String details;

    //getters and setters...

To do the Job of mapping attributes i make a Wrapper class that handles it, but it doesn't feel quite right to me. Does anyone have a better approach?

public class AppointmentWrapper {

    private List<AppointmentEntity> entitiesList;

    public AppointmentWrapper(List<AppointmentEntity> appointmentEntities) {
            entitiesList = appointmentEntities;
    }

    public List<AppointmentDTO> getDTOList() {
            List<AppointmentDTO> dtoList = new ArrayList<AppointmentDTO>();

            for (AppointmentEntity entity : entitiesList) {
                    AppointmentDTO dto = new AppointmentDTO();

                    dto.setId(entity.getId());
                    dto.setFirstName(entity.getFirstName());
                    dto.setLastName(entity.getLastName());
                    dto.setAppointmentDate(entity.getAppointmentDate());
                    dto.setNextAppointmentDate(entity.getNextAppointment());
                    dto.setAttendant(entity.getAttendant());
                    dto.setDetails(entity.getDetails());
                    dto.setDNI(entity.getDNI());
                    dto.setTreatment(entity.getTreatment());
                    dtoList.add(dto);
            }
            return dtoList;
    }
}


texts:
I have JSON data which can be an object/array of recursively nested object or array. The value of an array can not be null, but a value in an object can be null. And I would like to return all combinations of these keys and values through depth-first search.

For example:

var data = {
  "title": {
     "original": "Hitchhiker",
     "more": ["HGTTG"],
     "link": null
  },
  "date": ["20150101", "20160101"]
}

The data's length and depth is arbitrary, and the combination result I want is something like this:

["title-original-Hitchhiker", "title-more-HTTG", "title-link", "date-20150101", "date-20160101"]

What I came up with is recursive:

function nestedObjectToArray(obj) {
  if (typeof(obj) != "object"){
    return [obj];
  }
  var result = [];
  if (obj.constructor == Array){
    for (var i = 0; i <obj.length; i++){
      if (obj[i]){
        var temp = nestedObjectToArray(obj[i]);
        for (var j = 0; j < temp.length; j++){
          result.push(temp[j]);
        }
      }
    }
  } else {
    for (var i in obj){
      if (obj.hasOwnProperty(i)) {
        if (obj[i] == null){
          result.push(i);
        } else {
          var temp = nestedObjectToArray(obj[i]);
          for (var j = 0; j < temp.length; j++){
            result.push(i+"-"+temp[j]);
          }
        }
      }
    }
  }
  return result;
}

Would you have a better/more elegant solution than this chunk of conditions, loops and recursion? I can use any library if it's more convenient.


texts: Displaying dependent options when a selection is made in a dropdown

texts:
I was wondering if someone could please point me in the right direction with this bit of JavaScript I have been working on.

I have made this form that currently has onblur JavaScript validation and additionally I am to make it dynamic so that when a user selects an option from a dropdown option form a div is shown with corresponding options.  But at the moment that code I have written for this is looking pretty repetitive and suffering from 'code smell'.

Is there a better way to do this? I am thinking a for loop that iterates through the dropdown options but am not 100% sure how to put this in place?

adventureForm = document.querySelector('#adventure');
       charterDrop = document.querySelector('.charter-options');
       mountainDrop = document.querySelector('.mountain-lake-options');
       trampDrop = document.querySelector('.tramp-options');
       photoDrop = document.querySelector('.photo-options');
       dropDowns =  document.querySelector('#dropdowns');

      // check adventure dropdown choice
      if (field.id === "adventure" && adventureForm.selectedIndex === 0) {
      dropDowns.classList.add('hidden');

          } else if (field.id === "adventure" && adventureForm.selectedIndex === 1)  {
              dropDowns.classList.remove('hidden');
             charterDrop.classList.remove('hidden');
           mountainDrop.classList.add('hidden');
           trampDrop.classList.add('hidden');
           photoDrop.classList.add('hidden');
         } else if (field.id === "adventure" && adventureForm.selectedIndex === 2)  {
           dropDowns.classList.remove('hidden');
           charterDrop.classList.add('hidden');
           mountainDrop.classList.remove('hidden');
           trampDrop.classList.add('hidden');
           photoDrop.classList.add('hidden');
         } else if (field.id === "adventure" && adventureForm.selectedIndex === 3)  {
           dropDowns.classList.remove('hidden');
           charterDrop.classList.add('hidden');
           mountainDrop.classList.add('hidden');
           trampDrop.classList.remove('hidden');
           photoDrop.classList.add('hidden');
         } else
if (field.id === "adventure" && adventureForm.selectedIndex === 4)  {
           dropDowns.classList.remove('hidden');
           charterDrop.classList.add('hidden');
           mountainDrop.classList.add('hidden');
           trampDrop.classList.add('hidden');
           photoDrop.classList.remove('hidden');
         }

You can view the JSBin link here.


texts: Simplification of multi level object array

texts:
I have a JavaScript array:

var data = [{abc: "vf",def: [{ a:"1", b:"3"},{a:"2",b:"4"}]}];

I want it to convert to:

[{"abc":"vf","a":"2","b":"4"},{"abc":"vf","a":"2","b":"4"}]

I have written the JavaScript code for it:

Javascript:

    var push_apply = Function.apply.bind([].push);
    var slice_call = Function.call.bind([].slice);

    Object.defineProperty(Array.prototype, "pushArrayMembers", {
        value: function() {
            for (var i = 0; i < arguments.length; i++) {
                var to_add = arguments[i];
                for (var n = 0; n < to_add.length; n+=300) {
                    push_apply(this, slice_call(to_add, n, n+300));
                }
            }
        }
    });

var globalResultArr = [];
var data = [{abc: "vf",def: [{ a:"1", b:"3"},{a:"2",b:"4"}]}];
function f(){
    for(var i=0;i<data.length;i++){    //Iterate Data Array
        var obj = data[i];
        var resultArray = [{}];
        for (var key in obj) {          // Iterate Object in Data Array
            if (obj.hasOwnProperty(key)) {
                if(Object.prototype.toString.call(obj[key]) === "[object Array]"){
                    var tempRes = $.extend(true, [], resultArray);
                    resultArray = [];
                    for(var k=0;k<tempRes.length;k++){
                        var tempResObj = tempRes[k];
                        for(var j=0;j<obj[key].length;j++){ // If it has array, then iterate it as well
                            var innerObj = obj[key][j]; //Iterate Object in inner array
                            for(var innerkey in innerObj){
                                if (innerObj.hasOwnProperty(innerkey)) {
                                    tempResObj[innerkey] = innerObj[innerkey];
                                }
                            }
                            resultArray.push(tempResObj);
                        }
                    }
                }else{
                    for(var i=0;i<resultArray.length;i++){
                        resultArray[i][key] = obj[key];
                    }
                }
            }
        }
        globalResultArr.pushArrayMembers(resultArray);
    }
    document.getElementById("test").innerHTML = JSON.stringify(globalResultArr);
}

f();

HTML:

How can I make this more space efficient? Is there any simpler approach?

JSFiddle : http://jsfiddle.net/La1687jc/


texts: Recursive function that reverse the words in a string

texts:
I have been working on a problem that asks me to a write recursive function that can reverse the words in a string. For example if the string is "cat is running", then the result should be "running is cat".

I already completed the problem, but I feel like my implementation is really bad. Does anyone know any other way to solve this problem? Are there other ways to improve my code?

#include <stdio.h>
#include <string.h>
void reverse(char* string, int count);

int main()
{
   char string[] = "cat is running";

   //result will be running is cat

   reverse(string, -1);
   printf("%s\n", string);
}

void reverse(char* string, int count) {
   if (count == 0) {
       return;
   }

   int first = 0;
   int second = 0;
   int length = 0;

   for (int i = 0; i < strlen(string); i++) {
       if(string[i] == ' ' && first == 0) {
           first = i;
           length++;
           if (length == count) {
              break;
           }
       } else if(string[i] == ' ') {
           second = first+1;
           first = i;
           length++;
           if (length == count) {
               break;
           }
       }
   }

   if(first == 0 && second == 0) {
       return;
   }
   int flag = 0;
    for(int i = first; i >= 0; i--) {
       char temp = string[i];
       for(int k = i; k < strlen(string) - 1; k++) {
           if(flag > 2 && k == (strlen(string) - flag)) {
               k = strlen(string);
           } else {
               string[k] = string[k+1];
           }
        }
    if(i == second) {
        i = 0;
    }
    if (flag == 0) {
        string[(strlen(string) - 1) - flag] = temp;
        flag++;
    } else {
        string[(strlen(string) - flag)] = temp;
        flag++;
    }
}

count = length;
reverse(string, count - 1);
}


texts: Sorting possibly unstable and general jsfiddle/jquery problem

texts:
I have a simple sorting algorithm that I was told is possibly unstable. I'm wondering what in the sort is unstable. I have test cases written to test all fields with no issues.

A secondary problem is that jQuery is not appending the rows for some reason (works fine in local and server environments).

http://jsfiddle.net/SucGH/

var applyData = function (dataSet) {
    $('#healthplans tbody').empty();
    for (var i = 0; i < dataSet.length; i++) {
        var itemRow = '';
        for (item in dataSet[i]) {
            var newItem = dataSet[i][item];
            if (typeof newItem === 'number') newItem = "$" + newItem;
            itemRow += '' + newItem + '	';
        }
        $('#healthplans tbody').append('
' + itemRow + '
');
    }
}

var order = '';
var sortDataByField = function (field, newOrder, test) {
    if (!newOrder) order = (order == 'asc') ? 'desc' : 'asc';
    else order = newOrder;
    if (field) {
        jsonData.sort(function (a, b) {
            if (typeof b[field] === 'string') {
                var bfield = b[field].toUpperCase();
                var afield = a[field].toUpperCase();
                if (bfield < afield) return (order == 'asc') ? -1 : 1;
                if (bfield > afield) return (order == 'asc') ? 1 : -1;
                return 0;
            } else if (typeof b[field] === 'number') {
                if (order == 'desc') return b[field] - a[field]
                else if (order == 'asc') return a[field] - b[field]
                return 0;
            }
        });
        if (!test) {
            applyData(jsonData);
        }

    } else {
        return 'Field and/or order not properly defined';
    }
}


texts: calling Cancel() on CompletableFuture after get() is correct approch

texts:
I writing this code to leverage the advantages of Completable future.
My doubt is call cancel() method after get() is correct approach?
 private void combineFilters(JobFilter jobFilter,
                            CompletableFuture<List<String>> measureCompletableFuture,
                            CompletableFuture<List<String>> dqTypCompletableFuture,
                            CompletableFuture<List<String>> ownerCompletableFuture,
                            CompletableFuture<List<String>> jobTypeCompletableFuture,
                            CompletableFuture<List<String>> jobStateCompletableFuture) {
    try {
        CompletableFuture.allOf(measureCompletableFuture, dqTypCompletableFuture,
                                ownerCompletableFuture, jobTypeCompletableFuture,
                                jobStateCompletableFuture)
                         .join();
        LOGGER.info("All filters DB calls completed");
        if (measureCompletableFuture.isDone()) {
            LOGGER.info("Populating measure filters results");
            jobFilter.setMeasureName(measureCompletableFuture.get());
        }
        if (dqTypCompletableFuture.isDone()) {
            LOGGER.info("Populating dqtype filters results");
            jobFilter.setDqType(dqTypCompletableFuture.get());
        }
        if (ownerCompletableFuture.isDone()) {
            LOGGER.info("Populating owner filters results");
            jobFilter.setOwner(ownerCompletableFuture.get());
        }
        if (jobTypeCompletableFuture.isDone()) {
            LOGGER.info("Populating jobtype filters results");
            jobFilter.setType(jobTypeCompletableFuture.get());
        }
        if (jobStateCompletableFuture.isDone()) {
            LOGGER.info("Populating jobstate filters results");
            jobFilter.setTriggerState(jobStateCompletableFuture.get());
        }
    } catch (InterruptedException | ExecutionException e) {
        LOGGER.error("Exception occurred while populating the filter results {}",
                     e.getMessage());
        Thread.currentThread().interrupt();
    } finally {
        LOGGER.info("Exiting from combine job filters");
        measureCompletableFuture.cancel(true);
        dqTypCompletableFuture.cancel(true);
        ownerCompletableFuture.cancel(true);
        jobTypeCompletableFuture.cancel(true);
        jobStateCompletableFuture.cancel(true);
    }
}


texts:
Since the Esteemed Academia wants me to learn Haskell, and Haskell seems just weird for me, I thought that to train some basic Haskell skills I'd write a simple script I now need in Haskell.

This is what the script is supposed to do... I have a file that looks like this:

oo R
j
j ai            I'm a comment
kd oo
stack j
a

I needed to extract duplicated elements from this file with lines they appear on. The catch is that the tab character denotes comments; so I'm a comment should not be considered here and in particular, this a from I'm a comment should not match this a that appears as the last element from these sample lines.

If fed this particular sample file, my script should report finding duplicate elements: oo on lines 1 and 4 and j on lines 2, 3 and 5. I believe I wrote a script that does this correctly.

Here it is:

import qualified Data.Map as Map
import Data.List
import Data.Function

main = do
  input <- fmap preprocess getContents
  printDupes $ findDupes input

preprocess input = let
    untabbedLines = map (takeWhile (/= '\t')) $ lines input
    wordsedLines = map words untabbedLines
    numberedLines = zip wordsedLines [1..]
    numberedWords = concat $ map indexDown numberedLines where
      indexDown (words', index) = map (flip (,) $ index) words'
  in numberedWords

findDupes entries = let
    occurences = Map.fromListWith (flip (++)) $ map (fmap (:[])) entries
  in Map.filter ((>1).length) occurences

printDupes :: Map.Map String [Int] -> IO()
printDupes dupes = let
    showPositions positions = intercalate ", " $ map show positions
    printDupe (dupe, positions) = putStrLn $ "Duplicated element " ++ dupe ++ " found on positions: " ++ showPositions positions
  in let
    sortedDupes = sortBy (compare `on` snd) $ Map.assocs dupes
  in mapM_ printDupe sortedDupes

The task is simple, but I guess it's OK for learning how to code in Haskell...

So could you kindly review this self-imposed exercise? What could've been done better than I did? Simpler? Shorter? I'm sure much, but what precisely? Also how to improve readability?


texts:
I am currently working on my own little game engine and thought about implementing a simplified version of Unitys component system where you can attach objects of derived Components to an GameObject. Later you can request specific Components to use their functionality. Below is a stripped down (but still working) version of what I think about implementing.

#include <iostream>
#include <vector>

class GameObject;

class Component
{
private:
    GameObject * parent;

public:
    Component(GameObject * parent = nullptr)
    {
        this->parent = parent;
    }

    virtual ~Component() { parent = nullptr; }

    GameObject* GetParent() { return parent; }

    void SetParent(GameObject* parent) { this->parent = parent; }

    virtual std::string What() { return "Basic Component"; }
};

class SoundSource : public Component
{
private:
    // some sound specific members

public:
    SoundSource(GameObject * parent = nullptr) : Component(parent) {}

    virtual ~SoundSource() { }

    std::string What() { return "SoundSource Component"; }
};

class GameObject
{
private:
    std::vector<Component*> m_Components;

public:
    GameObject() :
        m_Components()
    {}

    ~GameObject()
    {
        for (size_t i = 0; i < m_Components.size(); ++i)
            if (m_Components[i]->GetParent() == this) delete m_Components[i];
        m_Components.clear();
    }

    void AddComponent(Component* comp)
    {
        if (comp->GetParent() == nullptr)
        {
            comp->SetParent(this);
        }
        m_Components.push_back(comp);
    }

    template <class component_type>
    component_type* GetComponent()
    {
        for (auto comp : m_Components)
        {
            component_type* c =  dynamic_cast<component_type*>(comp);
            if (c) return c;
        }
        return nullptr;
    }
};

int main()
{
    GameObject go;
    go.AddComponent(new SoundSource());
    go.AddComponent(new Component());

    SoundSource *s = go.GetComponent<SoundSource>();
    if (s) std::cout << s->What() << std::endl;
}

My initial plan for GetComponent<>() was to use the name of typeid to compare the component types, however since all components need to derive from the same base I think that using a dynamic_cast is the better option in this case. However I have never worked with dynamic casting before and I am not sure whether the way I use it is safe, so please tell me is it?

Also if you see any points for improvements I would appreciate your opinions.


texts:
I have written this Rust code to implement the quick sort algorithm. Could you review it and tell me if it is idiomatic or not? Especially about my use of the slices?

fn quick_sort<T: Ord>(array: &mut [T]) {
    let n = array.len();
    if n > 0 {
        let mut i_pivot = 0;
        for i in 1..n {
            if &array[i] < &array[n - 1] {
                array.swap(i, i_pivot);
                i_pivot += 1;
            }
        }
        array.swap(i_pivot, n - 1);
        quick_sort(&mut array[0..i_pivot]);
        quick_sort(&mut array[i_pivot + 1..n]);
    }
}

fn main() {
    // Fixed-size array (type signature is superfluous)
    let mut xs = [
        8, 13, 20, 13, 4, 21, 24, 13, 18, 23, 14, 6, 10, 2, 4, 6, 16, 6, 17, 9, 8, 20, 14, 19, 7,
        9, 18, 0, 18, 1, 8, 10,
    ];

    quick_sort(&mut xs);

    println!("{:?}", xs);
}
```


texts:
I'm coming from languages like Java and Python and I'm completely new to C++. Therefore, my knowledge is somewhat limited.
My goal is to implement a listener in C++ myself and I came up with a solution using function pointers and lambdas.
The design is different from other questions that I have seen on this site so I hope it's not a duplicate.
My question: Is my implementation optimal or is it good from a C++ point of view? If there are any optimizations or any better ways please let me know. (Below code is just an example of my design)
class IntegerListener {
public :

    void (*number_changed)(int old_number, int new_number);

    void (*number_increased)(int increased_value);

    //deleting default constructor to make users to define number_changed and number_increased
    IntegerListener() = delete;

    IntegerListener(void (*&&number_changed)(int, int), void (*&&number_increased)(int)) {
        this->number_changed = number_changed;
        this->number_increased = number_increased;
    }

};

class Integer {

private:
    int number;
    std::vector<IntegerListener *> integer_listeners;
public:

    explicit Integer(int num) : number(num) {}

    void set_number(int new_number) {
        for (IntegerListener *&integer_listener:integer_listeners) {
            (*integer_listener).number_changed(number, new_number);
        }
        if (new_number > number) {
            for (IntegerListener *&integer_listener:integer_listeners) {
                (*integer_listener).number_increased(new_number - number);
            }
        }
        number = new_number;
    }

    void add_number_changed_listener(IntegerListener &&integer_listener) {
        integer_listeners.push_back(&integer_listener);
    }
};

and in order to add some listener my idea is something like below:
void test() {
    Integer integer(1);

    // from a java background it represents the java way the best, in my opinion.
    integer.add_number_changed_listener(IntegerListener(
            [](int oldNum, int newNum) {
                std::cout << "changed(from 1listener): (" << oldNum << ") -> (" << newNum << ")" << std::endl;
            },
            [](int increasedValue) {
                std::cout << "increased by(from 1listener): (" << increasedValue << ")" << std::endl;
            }));

    integer.add_number_changed_listener(IntegerListener(
            [](int oldNum, int newNum) {
                std::cout << "changed(from 2listener): (" << oldNum << ") -> (" << newNum << ")" << std::endl;
            },
            [](int increasedValue) {
                std::cout << "increased by(from 2listener): (" << increasedValue << ")" << std::endl;
            }));
    std::cout << "first call: \n";
    integer.set_number(2);
    std::cout << "second call: \n";
    integer.set_number(1);
}


texts: Finding specific small byte arrays in large binary files

texts:
I'm trying to quickly and efficiently find every recurring position of small byte arrays (4 bytes) in large binary files (several GBs). My current method is as follows:

Stream stream = File.OpenRead(filepath);

List<long> searchResults = new List<long>(); //The results as offsets within the file
int searchPosition = 0; //Track of how much of the array has been matched
int[] searchPattern = { 0x00, 0x01, 0x02, 0x03 }; // The array to search

while(true) //Loop until we reach the end of the file
{
    var latestbyte = stream.ReadByte();
    if(latestbyte == -1) break; //We have reached the end of the file

    if(latestbyte == searchPattern[searchPosition]
    {
        searchPosition++;
        if(searchPosition == searchPattern.Length)
        {
            searchResults.Add(stream.Position);
        }
    }
    else
    {
        searchPosition = 0;
    }
}

It's slow, and seems quite inefficient (3-4 seconds for a small 174MB file, 35 seconds for a 3GB one).

How can I improve the performance?

I looked into Boyer-Moore, but is it really worth it, considering the pattern i'm looking for is only 4 bytes?


texts: Reversal of a singly-linked list in Rust

texts:
I was trying to write some simple data structures to practice ownership concepts in Rust:

type Link<T> = Option<Box<Node<T>>>;

struct Node<T> {
    elem: T,
    next: Link<T>,
}

struct List<T> {
    head: Link<T>,
}

pub struct Iter<'a, T: 'a> {
    next: Option<&'a Node<T>>,
}

impl<T> List<T> {
    pub fn new() -> Self {
        List { head: None }
    }

    pub fn push_front(&mut self, elem: T) {
        let new_node = Box::new(Node {
            elem: elem,
            next: self.head.take(),
        });

        self.head = Some(new_node);
    }

    pub fn reverse(&mut self) {
        if self.head.is_none() || self.head.as_ref().unwrap().next.is_none() {
            return;
        }

        let mut prev = None;
        let mut current_node = self.head.take();
        while current_node.is_some() {
            let next = current_node.as_mut().unwrap().next.take();
            current_node.as_mut().unwrap().next = prev.take();
            prev = current_node.take();
            current_node = next;
        }

        self.head = prev.take();
    }

    pub fn iter(&self) -> Iter<T> {
        Iter { next: self.head.as_ref().map(|node| &**node) }
    }
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        self.next.map(|node| {
            self.next = node.next.as_ref().map(|node| &**node);
            &node.elem
        })
    }
}

fn main() {
    let mut l = List::new();
    l.push_front(3);
    l.push_front(2);
    l.push_front(1);
    l.push_front(12);

    for item in l.iter() {
        print!("{} ", item);
    }
    println!();
    l.reverse();
    for item in l.iter() {
        print!("{} ", item);
    }
    println!();
}

Link to Rust Playground


texts:
Please review my strstr implementation. This is an interview question that does not allow the use of strlen(). Is there a better way than using a boolean below?

#include <iostream>
#include <cstring>
char* my_strstr(char * s1, const char *s2)
{
  if ( s1 == NULL || s2 == NULL )
    return NULL;

  size_t s2Size = 0;

  const char *end = s2;
  while (*end++)
    ++s2Size;

  bool match;
  while ( *s1 )
  {
    match = true;
    for ( int i = 0; i < s2Size ; ++i )
    {
      if ( s1[i] != s2[i] )
      {
        match = false;
        break;
      }
    }
    if ( match )
      return s1;

    ++s1;
  }
  return NULL;
}

const char* my_strstr(const char * s1, const char *s2)
{
  return my_strstr(const_cast<char*>(s1),s2);
}

int main()
{
  const char str[]= "This is a strstr test";
  const char search[]= "strstr";

  const char *result = my_strstr(str,search);

  if ( result )
    printf("original: %s\n item: %s\n found: %s\n", str, search, result );
}


texts: ArrayBlockingQueue: concurrent put and take

texts:
I have implemented an ArrayBlockingQueue (put and take) on the lines of LinkedBlockingQueue i.e using two locks so that my take should not block my put.

For more information please see this Stack Overflow question.  The code is also available at GitHub.

Please review the code for any race conditions.

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ArrayBlockingQueue<T> {

    private final int capacity;
    private final AtomicInteger count = new AtomicInteger(0);
    private final Lock putLock = new ReentrantLock();
    private final Lock takeLock = new ReentrantLock();
    private final Condition notEmpty = takeLock.newCondition(); // putLock will signal that its not empty
    private final Condition notFull = putLock.newCondition(); // signal when queue is notFull
    private final Object [] items ;
    int takeIndex;
    int putIndex;

    public ArrayBlockingQueue(int capacity) {
        this.capacity = capacity;
        items = new Object[capacity];

    }

    public void add(T t) throws InterruptedException {
        int c = -1;
        final Lock lock = this.putLock;
        final AtomicInteger count = this.count;
        lock.lock();
        try {
            while(count.get() == capacity) {
                    notFull.await();
            }
            enqueue(t);
            c = count.getAndIncrement();
            if(c+1 < capacity) {
                notFull.signal();
            }
        }finally {
            lock.unlock();
        }
        if(c == 0) {
            signalNotEmpty();
        }
    }

    public T take() throws InterruptedException {
        int c = -1;
        final Lock lock = this.takeLock;
        final AtomicInteger count = this.count;
        T t = null;
        lock.lock();
        try {
            while(count.get() == 0) {
                notEmpty.await();
            }
            t = dequeue();
            c = count.getAndDecrement();
            if(c > 1) {
                notEmpty.signal();
            }
        }finally {
            lock.unlock();
        }
        if(c == capacity) {
            signalNotFull();
        }
        return t;
    }

    private void signalNotEmpty() {
        final Lock lock = this.takeLock;
        lock.lock();
        try {
            notEmpty.signal();
        }finally {
            lock.unlock();
        }
    }

    private void signalNotFull() {
        final Lock lock = this.putLock;
        lock.lock();
        try {
            notFull.signal();
        }finally {
            lock.unlock();
        }
    }

    private T dequeue() {
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        T x = (T) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length)
            takeIndex = 0;
        return x;
    }

    private void enqueue(T t) {
        final Object[] items = this.items;
        items[putIndex] = t;
        if (++putIndex == items.length)
            putIndex = 0;
    }

}


texts: Is this a good way to limit the occurrence of OutOfMemoryException?

texts:
I have a class that uses the SqlBulkCopy to bulk insert data into a SQL Server database.  My original implementation just passed the m_buffer (which is a reference to a class that implements IDataReader) directly into the WriteToServer. Now a new requirement has been added that, upon failure, the process should retry the Bulk Insert command.  Why you ask? Because one of our clients get intermittent SQL exceptions because they have crappy hardware.

Okay, I digress, since IDataReader is read-once I needed to come up with something different.  I chose to load the IDataReader into a DataTable first and then pass the DataTable into the WriteToServer method.  Now my problem is that I will be using more memory and since I do not know anything about the data (the number of columns nor the amount of data in each row) I wanted to attempt to make the code safe from an OutOfMemoryException.

Unfortunately I could not find a good way to determine the amount of available memory, so instead I chose to dump the data every 50,000 rows or when the memory allocation reaches an arbitrary number (1 gig), whichever comes first.

Does this sound like a sound approach or is there a better way?

// m_buffer is a read-once cache (implements IDataReader) that pulls
// data from an external source as needed so it uses very little memory.
// My original implementation just used m_buffer as the parameter of
// WriteToServer but now I have to add retry logic into the process.
// The retry logic is in the PutDataIntoDatabase method.

const long MAX_MEMORY_TO_USE = 1073741824;  // 1 gig

DataTable dataTable = new DataTable(m_tableName);
foreach (DataField d in m_buffer.GetColumns())
    dataTable.Columns.Add(new DataColumn(d.FieldName, d.FieldType));

while (m_buffer.Read())
{
    DataRow row = dataTable.NewRow();
    for (int i = 0; i < m_buffer.FieldCount; i++)
        row[i] = m_buffer.GetValue(i);

    dataTable.Rows.Add(row);

    long totalMemory = GC.GetTotalMemory(false);
    if (rowCount++ > 50000 || totalMemory > MAX_MEMORY_TO_USE)
    {
        PutDataIntoDatabase(dataTable);
        dataTable.Clear();
        rowCount = 0;
    }
}

if (dataTable.Rows.Count > 0)
    PutDataIntoDatabase(dataTable);


texts:
I have, in Java, an arraylist with these values (many lines, this is just an extract):

  20/03/2013 23:31:46   6870    6810    6800    6720    6860    6670    6700    6650    6750    6830    34864   34272
  20/03/2013 23:31:46 6910    6780    6800    6720    6860    6680    6620    6690    6760    6790    35072   34496

where the first two values are strings that contain data and are stored in a single element.

What I want to do is to compare the string data elements and delete, for example, the second one and all the elements referred to that line.

For now, I've used a for cycle that every 13 elements compares the string (in order to compare only data strings).

Can I implement this with other better solutions?

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Downsampler {
    public static void main(String[] args) throws Exception{
        //The input file
        Scanner s = new Scanner(new File("prova.txt"));

        //Saving each element of the input file in an arraylist
        ArrayList<String> list = new ArrayList<String>();
        while (s.hasNext()){
            list.add(s.next());
        }
        s.close();

        //Arraylist to save modified values
        ArrayList<String> ds = new ArrayList<String>();

        int i;
        for(i=0; i<=list.size()-13; i=i+14){
            //combining the first to values to obtain data
            String str = list.get(i)+" "+list.get(i+1);
            ds.add(str);
            //add all the other values to arraylist ds
            int j;
            for(j=2; j<14; j++){
                ds.add(list.get(i+j));
            }

            //comparing data values
            int k;
            for(k=0; k<=ds.size()-12; k=k+13){
                ds.get(k); //first data string element

                //Comparing with other strings and delete
                //TODO
            }
        }
    }
}


texts:
I wrote a small script as an answer for a Stack Overflow question, which referred to counting lines of code and comments (in C and C++ style).

f = File.open("test.txt")

loc = 0
comments = 0
while line = f.gets
  if commented ||= line.match(/^\/\*/)
    commented = nil if line.match(/\*\/$/)
    comments += 1
  elsif line.match(/^\s*\/\//)
    comments += 1
  else
    loc +=1 unless line.match(/^\s*\n/)
  end
end

puts loc
puts comments

I'm just looking for a review.


texts:
I have an Excel file and each row within the sheet represents an employee's data.

I am trying to find a cleaner way to map each row to a model object:

public IList<Employee> ReadEmployees(byte[] file, string companyId)
{
    var employees = new List<Employee>();
    using (var stream = new MemoryStream(file))
    {
        using (var package = new ExcelPackage(stream))
        {
            var worksheet = package.Workbook.Worksheets[0];
            for (var rowNumber = 3; rowNumber <= worksheet.Dimension.End.Row; rowNumber++)
            {
                //---- Trying to retrieve the row data in an elegant way----
                var employee = GetEmployeeRowSummary(worksheet, rowNumber, companyId);
                employees.Add(employee);
            }
        }
    }

    return employees;
}

I was kind of hoping to use something like auto-mapper but don't know if that would be the best way (maybe create a Custom Resolver).

Is there a better way of mapping excel rows to an model? The way I am doing it currently seems like a maintenance issue.

private static Employee GetEmployeeRowSummary(ExcelWorksheet worksheet, int rowNumber, string companyId)
{
    var employeeId = Guid.NewGuid().ToString();

    return new Employee
           {
               CompanyId = companyId,
               EmployeeId = employeeId,
               EmployeeNumber = worksheet.Cells[rowNumber, 1].GetValue<string>(),
               FirstName = worksheet.Cells[rowNumber, 2].GetValue<string>(),
               LastName = worksheet.Cells[rowNumber, 3].GetValue<string>(),
               BirthDate = worksheet.Cells[rowNumber, 4].GetValue<DateTime>(),
               AppointmentDate = worksheet.Cells[rowNumber, 5].GetValue<DateTime>(),
               CompanyRunFrequencyId = 9,
               JobTitle = worksheet.Cells[rowNumber, 8].GetValue<string>(),
               DateCreated = DateTime.Now,
               EmployeeAddress = new List<EmployeeAddress>
                                 {
                                    new EmployeeAddress
                                    {
                                        EmployeeId = employeeId,
                                        StreetNumber = worksheet.Cells[rowNumber, 9].GetValue<int>(),
                                        Suburb = worksheet.Cells[rowNumber, 11].GetValue<string>(),
                                        City = worksheet.Cells[rowNumber, 12].GetValue<string>(),
                                        PostalCode = worksheet.Cells[rowNumber, 13].GetValue<int>()
                                    }
                                 }
           };
}


texts:
I recently wrote a name generator that uses a DTMC underneath (I asked about it here) and, since I'm not entirely confident I did it right, I wrote a script to check my code, or at least its output.

It works pretty well, but, being new to the language, I want to know how to make it more idiomatic. Performance boosts (in terms of speed and memory efficiency) would also be a plus, but since this is just a simple test script they're not as important.

# arguments: '-dDELIMITER'
if ARGV[0] == '-h'
    [
            'Should be used in the form:',
            '<invocation of name_gen.rb> | <ruby> name_gen_test.rb -d<delimiter>',
            'The delimiter MUST be specified in name_gen.rb and it MUST NOT be ``.'
    ].each { |line| puts line }
end

DELIMITER = ARGV[0] || abort('You must specify a delimiter as the sole command-line argument')

connections = Hash.new { |hash, key| hash[key] = Hash.new 0 }
start = Hash.new 0

until (cur_line = STDIN.gets).nil?
    cur_line.chomp!
    individual_syllables = cur_line.split DELIMITER
    individual_syllables.each_with_index { |from, index|
        start[from] += 1 if index == 0
        connections[from][individual_syllables[index + 1] || !!false] += 1
    }
end

# % of start per syllable
# % of connections to each syllable it connected to

puts 'Start:'
total_start_count = start.values.inject(:+).to_f
max_len = start.keys.inject (0) { |memo, cur|
    (cur.length > memo) ? cur.length : memo
}
start.each { |text, percent|
    puts "  #{text.ljust max_len} : #{(percent * 100 / total_start_count).round.to_i}%"
    # Get the percent -> Truncate -> convert to string -> justify
}
puts

END_MARKER = '[end]'
puts 'Connections:'
connections.each { |from, links|
    total_connection_count = links.values.inject(:+).to_f
    max_len = links.keys.inject(END_MARKER.length) { |memo, cur|
        ((cur ? cur : '').length > memo) ? cur.length : memo
    }
    puts "  #{from}:"
    links.each { |to, probability|
        next unless to
        puts "    #{to.ljust max_len} : #{(probability * 100 / total_connection_count).round.to_i}%"
    }
    puts "    #{END_MARKER} : #{(links[false] * 100 / total_connection_count).round.to_i}%"
}

This is the name generator; this script is meant to be used something like this (on Windows, at least):

ruby name_gen.rb dict.txt 10000 -d_ | ruby name_gen_test.rb _

if the dictionary of syllables is located at 'dict.txt'.

Here's an example dictionary file:

a|1|1|b,2;c,2
b|0|3|a,0;c,2
c|0|0|a,1;b,1

And an example output for the script:

Start:
  a : 100%

Connections:
  a:
    c     : 40%
    b     : 40%
    [end] : 20%
  c:
    a     : 50%
    b     : 50%
    [end] : 0%
  b:
    c     : 40%
    [end] : 60%

For anyone interested, the final code is available here.


texts:
This is a boggle solver in Java.  I would like code reviewers to optimize the code, suggest better coding practices, and help make it cleaner.

I am also unsure of the complexity and would appreciate an explanation of it.

public final class Boggle {

    private static final NavigableSet<String> dictionary;
    private final Map<Character, List<Character>> graph = new HashMap<Character, List<Character>>();

    static {
        dictionary = new TreeSet<String>();
        try {
            FileReader fr = new FileReader("/Users/ameya.patil/Desktop/text.txt");
            BufferedReader br = new BufferedReader(fr);
            String line;
            while ((line = br.readLine()) != null) {
                dictionary.add(line.split(":")[0]);
            }
        } catch (Exception e) {
            throw new RuntimeException("Error while reading dictionary");
        }
    }

    private Boggle() {}

    public static List<String> boggleSolver(char[][] m) {
        if (m == null) {
            throw new NullPointerException("The matrix cannot be null");
        }
        final List<String> validWords = new ArrayList<String>();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[0].length; j++) {
                solve(m, i, j, m[i][j] + "", validWords);
            }
        }
        return validWords;
    }

    private static void solve(char[][] m, int i, int j, String prefix, List<String> validWords) {
        assert m != null;
        assert validWords != null;

        for (int i1 = Math.max(0, i - 1); i1 < Math.min(m.length, i + 2); i1++) {
            for (int j1 = Math.max(0, j - 1); j1 < Math.min(m[0].length, j + 2); j1++) {
                if (i1 != i || j1 != j) {
                    String word = prefix+ m[i1][j1];

                    if (dictionary.contains(word)) {
                        validWords.add(word);
                    }

                    if (dictionary.subSet(word, word + Character.MAX_VALUE).size() > 0) {
                        solve(m, i1, j1, word, validWords);
                    }
                }
            }
        }
    }

    public static void main (String[] args) {
          char[][] board = { {'a', 'b', 'c', 'd' },
                             {'n', 'x', 'p', 'q' },
                             {'k', 't', 'i', 'w' },
                             {'e', 'f', 'g', 's' },
                          };

          List<String> list = Boggle.boggleSolver(board);
          for (String str :  list) {
              System.out.println(str);
          }
    }
}


texts: Scan the user input and then work with these letters

texts:
The program scans a maximum of 10 chars from user and then offers you 4 options what you can do with that array. Options are:

0 = quit the program,
1 = prints whole array,
2 = count all the small letters,
3 = prints only the numbers,
4 = change the small letters with the big ones and via versa.

This is my homework for school, so the interface needs to be in Czech. I think that overall it's quite good but I want to improve!!

#include <stdio.h>

int main() {

    int char_count = 10;
    char input_chars[char_count];
    int i = 0;
    int applied_numb = 1;
    int last_index;
    int amount_small_char = 0;
    int ascii_code;

    printf("Zadejte maximalne 10 znaku" );
    do {
        printf(" \n Zadejte %d z %d: ", i, char_count);
        input_chars[i] = getchar();
        getchar();
        i++;
            if(i == char_count) {
                printf("Zadali jste maximalni pocet znaku. \n");
        }
    } while(i < char_count && input_chars[i - 1] != '.' );

    if(input_chars[i - 1] == '.')
    {
        // in case of last element is "." substract 2 from last index(because we used do while cycle (i++))
        last_index = i - 2;
    }
    else
    {
        last_index = i - 1;
    }

    while (applied_numb != 0 && applied_numb <= 4 && applied_numb >= 0)
    {
        printf("Vyberte si co chcete s danymi cisli provest: \n 0) konec programu \n 1) vypis \n 2) pocet malych pismen \n 3) vypsat jen cislice \n 4) zmenit mala/velka pismena\n");
        scanf ("%i", &applied_numb);

        switch (applied_numb)
        {
            case 0:
                printf ("KONEC PROGRAMU, SEE YOU SOON :) ");
                break;
            case 1:
                printf("Vypis vaseho vstupuje: ");
                for(i = 0; i <= last_index; i++)
                {
                    printf(" %c",input_chars[i]);
                }
                break;

            case 2:
                for (i = 0; i <= last_index; i++)
                {
                    ascii_code = (int)input_chars[i];
                    if (ascii_code >= 97 && ascii_code <= 122)
                    {
                        amount_small_char = amount_small_char + 1;
                    }
                }
                printf("Pocet malych pismen ve vasim vstupu je:  %d", amount_small_char);
                break;
            case 3:
                printf("Tyto cislice jsou ve vasem vstupu:");
                for (i = 0; i <= last_index; i++)
                {
                    ascii_code = (int)input_chars[i];
                    if (ascii_code >= 48 && ascii_code <= 57)
                    {
                        printf(" %c", input_chars[i]);

                    }
                }
                break;
            case 4:
                printf("Zmena na mala/velka pismena vypada takto:");
                for (i = 0; i <= last_index; i++)
                    {
                        ascii_code = (int)input_chars[i];
                        if (ascii_code >= 97 && ascii_code <= 122)
                        {
                            ascii_code = ascii_code - 32;
                            printf(" %c", ascii_code);
                        }
                        else if(ascii_code >= 65 && ascii_code <= 90)
                        {
                            ascii_code = ascii_code + 32;
                            printf(" %c", ascii_code);
                        }
                        else if((ascii_code <= 64 && ascii_code >= 0) ||
                                (ascii_code >= 91 && ascii_code <= 96) ||
                                (ascii_code >= 123))
                        {
                            printf(" %c", input_chars[i]);
                        }
                    }
                break;
        }

        printf("\n  \n ------------------------------------- \n \n ");
    }
    return 0;
}


texts:
I sometimes hear people say how they can distinguish between good and bad coders of a certain programming language or even programming in general simply by looking at the code they write.

I'm relearning C, and I was just wondering whether my program follows best practices in terms of my commenting, the way I set it up, and generally the way I've incorporated the for and while loops along with macros (whether it be better to use a goto statement here, or a while loop instead of a for loop there, etc).

#include <stdio.h>

#define SIZE (sizeof(words[0])/sizeof(words[0][1]))
#define ROWS 10
#define COLUMNS 20

int main()
{
//The maxmimum letters in a words is 20 and the max words is 10
char words[ROWS][COLUMNS]={0},character;
int count_1=0,count_2=0,i,j;

printf("Enter something:  ");
character=getch();
putch(character);
while(character!='\r')
{
words[count_1][count_2]=character;
//Allows the next index to contain the value of the next inputted character
count_2++;
if(character==' ')
{
//index of inputted characters reset to 0
count_2=0;
//Allows the next row in array to be changed as one row will already satisfy a word
count_1++;
}

character=getch();
putch(character);
}

printf("\n");
//Starts from the last word
for(i=count_1;i>=0;i--)
{
for(j=0;j<SIZE;j++)
{
if(words[i][j]!=0)
printf("%c",words[i][j]);
}
}
}

I know the next bit is a bit opinionated, but does my code give an idea of where I'm at with logic and programming as a whole, or is the first part just some kind of myth (i.e. you can't judge a person by such a small piece of code)?

Note: I deliberately avoided the use of functions and strings. I got this task from C Programming: A Modern Approach, and I'm only attempting to solve a programming task simply by using only the features I've learned thus far in the book.


texts: Are there ways to speed up this string fuzzy matching in Golang?

texts:
I have a piece of python code doing fuzzy matching which works very well and is pretty fast. For reference, it uses the following files:

https://raw.githubusercontent.com/datasets/s-and-p-500-companies/master/data/constituents.csv
https://raw.githubusercontent.com/nlintz/pyBros/master/sp500/sp500.csv

import csv
from fuzzywuzzy import process

def csv_reader(file, key):
    with open(file) as csvfile:
        reader = csv.DictReader(csvfile)
        return [row[key] for row in reader]

const_data = csv_reader("constituents.csv", "Name")
target_data = csv_reader("sp500.csv", "company")

with open('results_python.csv', 'w', newline='') as csvfile:
    fieldnames = ["name", "match_name", "match_score"]
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for row in const_data:
        match = process.extractOne(row, target_data)
        writer.writerow({'name': row, 'match_name': match[0],    'match_score': match[1]})

This is how it performs:

$ time ./fuzzy.py
./fuzzy.py  19,90s user 0,13s system 97% cpu 20,444 total

However, my surprise came when I did a pretty similar code in Golang using a port of the fuzzywuzzy library. I want to understand if the slowness of it is related to the way I structure my code, or some deeper reason within the matching library.

package main

import (
    "encoding/csv"
    "os"
    "strconv"
    "github.com/paul-mannino/go-fuzzywuzzy"
)

func readCsv(file string) [][]string {
    csvFile, _ := os.Open(file)
    defer csvFile.Close()
    r := csv.NewReader(csvFile)
    records, _ := r.ReadAll()
    return records
}

func main() {

    original:= readCsv("constituents.csv")
    target:= readCsv("sp500.csv")
    csvOut, _ := os.Create("results_go.csv")
    csvwriter := csv.NewWriter(csvOut)

    var targetData []string

    for _, line := range target[1:] {
        targetData = append(targetData, line[1])
    }
    csvwriter.Write([]string{"name", "match_name", "match_score"})
    for _, line := range original[1:] {
        match, _ := fuzzy.ExtractOne(line[1], targetData)
        csvwriter.Write([]string{line[1], match.Match, strconv.Itoa(match.Score)})
    }
}

This is how the Go version performs:

$ time ./fuzzy
./fuzzy 75,04s user 1,28s system 98% cpu 1:17,51 total

Are there any possible bad steps that I took in my Go code that made this comparison slow? Are there any improvements you could suggest to make it perform at the very least to a similar speed as the python code?


texts:
Basically, what I mean by splice is to take an array of Enumerables, take the 1st element from the first one, then the 1st element from the second one, and so forth, until we come back to the 1st enumerable, and we then take the next element from it and each of the others.

Sort of like this:
[A A] [B B] [C C] [D D] [E E] [F F]
Splicing these together would produce [A B C D E F A B C D E F]

namespace xofz
{
    using System.Collections.Generic;

    public interface MaterializedEnumerable<out T> : IEnumerable<T>
    {
        long Count { get; }
    }
}

A MaterializedEnumerable is basically an enumerable which has been written to memory, so it can be iterated as many times as you want.  It also gets a Count property.

Here is the actual splice code.  Don't worry about what an OrderedMaterializedEnumerable is, just think of it for now as a wrapper for List<T>

namespace xofz.Transformation
{
    using System.Collections.Generic;
    using System.Linq;
    using xofz.Materialization;

    public class EnumerableSplicer
    {
        public MaterializedEnumerable<T> Splice<T>(IEnumerable<T>[] sources)
        {
            var lists = new List<T>[sources.Length];

            // first, enumerate all the items into separate lists
            for (var i = 0; i < sources.Length; ++i)
            {
                lists[i] = new List<T>(new LinkedList<T>(sources[i]));
            }

            // then, splice the lists together
            var list = new List<T>(lists.Sum(l => l.Count));
            var smallestCount = lists.Select(l => l.Count).Min();

            for (var i = 0; i < smallestCount; ++i)
            {
                list.AddRange(lists.Select(l => l[i]));
            }

            var remainingLists = new LinkedList<List<T>>();
            foreach (var l in lists)
            {
                l.RemoveRange(0, smallestCount);
                if (l.Count > 0)
                {
                    remainingLists.AddLast(l);
                }
            }

            if (remainingLists.Count == 0)
            {
                return new OrderedMaterializedEnumerable<T>(list);
            }

            IEnumerable<IEnumerable<T>> remainingEnumerables = remainingLists;
            list.AddRange(this.Splice(remainingEnumerables.ToArray()));

            return new OrderedMaterializedEnumerable<T>(list);
        }
    }
}

This method is slightly recursive, to handle enumerables of different sizes.  I hope it is easy enough to read!

More transformations I wrote lately are available at xofz.Core on Github.


texts: Checking the difference between old and new XML

texts:
I have two xml files, about 500mb each, an old and a new. I want to find out what items have been added or removed in the new.xml compared with the old.xml.

I had some help on this code and I'm a bit new to C++ but I was wondering if this is the optimal way to approach a problem such as this.

#include <set>
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>

#include "include/pugixml.hpp"

#define con(m) std::cout << m << '\n'
#define err(m) std::cerr << m << std::endl

using str_set = std::set<std::string>;

int main()
{
    pugi::xml_document doc;

    str_set a;
    doc.load_file("old.xml");

    // fill set a with just the ids from file a
    for(auto&& node: doc.child("site_entries").children("entry"))
        a.emplace(node.child("id").text().as_string());

    str_set b;
    doc.load_file("new.xml");

    // fill set b with just the ids from file b
    for(auto&& node: doc.child("site_entries").children("entry"))
        b.emplace(node.child("id").text().as_string());

    // now use the <algorithms> library

    str_set b_from_a;
    std::set_difference(a.begin(), a.end(), b.begin(), b.end()
        , std::inserter(b_from_a, b_from_a.begin()));

    str_set a_from_b;
    std::set_difference(b.begin(), b.end(), a.begin(), a.end()
        , std::inserter(a_from_b, a_from_b.begin()));

    str_set a_and_b;
    std::set_intersection(a.begin(), a.end(), b.begin(), b.end()
        , std::inserter(a_and_b, a_and_b.begin()));

    for(auto&& v: a)
        con("a       : " << v);

    con("");

    for(auto&& v: b)
        con("b       : " << v);

    con("");

    for(auto&& v: b_from_a)
        con("b_from_a: " << v);

    con("");

    for(auto&& v: a_from_b)
        con("a_from_b: " << v);

    con("");

    for(auto&& v: a_and_b)
        con("a_and_b : " << v);

    con("");
}


texts:
Required to splice specific element value in an array based on the condition.
Both the below code does the same job and yields the correct results. But couldn't figure out how to reduce coding structure with ECMAScript and which is performance oriented considering an array would have atleast 1.5k or even larger
This is with ECMAScript
this.candidateColumns.filter(item => item === 'Certificate').map(m => {
    if (!this.showControlsBasedOnPrivileges('CERTIFICATEPRINT')) {
        this.candidateColumns = this.candidateColumns.filter(item => item !== 'Certificate')
    }
});

This is simple forEach Loop code
this.candidateColumns.forEach((currentValue, index) => {
    if (currentValue === 'Certificate' && !this.showControlsBasedOnPrivileges('CERTIFICATEPRINT')) {
        this.candidateColumns = this.candidateColumns.filter(item => item !== 'Certificate')
    }
});

Any other Built In function Approach could be done for better performance or readability


texts: Calculating optimal video capture card configuration based on channels needed

texts:
I have to calculate the configuration of hardware that uses the least number of capture cards based on the number of channels desired. The cards are available in 4, 8, and 16 channel varieties.

It's important to note that the least number of cards is the first priority, and the second priority is using the cheaper (lower channel) cards when possible. Therefore, a 22-channel request could be filled with 2 16-channel cards, however using a 16 and an 8-channel card is more desirable as it uses the same number of physical cards while utilizing a cheaper 8-channel card instead of two 16-channels.

var card_16 = "US-HDVRC2-16-480D";
var card_8 = "US-HDVRC2-8-240D";
var card_4 = "US-HDVRC2-4-120D";

function getCardObject(channels) {
    var cards = {}
    var remainder = channels%16;
    if (channels/16 >= 1) //if there are at least 16 channels
    {
        cards[card_16] = Math.floor(channels/16);
        if (remainder != 0)
        {
            if (remainder > 8)
                cards[card_16] = cards[card_16] + 1;
            else if (remainder > 4)
                cards[card_8] = 1;
            else
                cards[card_4] = 1;
        }
    }
    else if (channels/8 >= 1)  { //if there aren't 16 but at least 8
        if (remainder != 0)
        {
            if (remainder > 8)
                cards[card_16] = 1;
            else if (remainder > 4)
                cards[card_8] = 1;
            else
                cards[card_4] = 1;
        }
    }
    else if (channels/4 >= 1) { //if there are at least 4
        if (remainder != 0)
        {
            if (remainder > 4)
                cards[card_8] = 1;
            else
                cards[card_4] = 1;
        }
    }
    else //if there are less than 4
        cards[card_4] = 1;
    return cards;
};


texts: Obtaining a target number only using the operations ×2, ×3, and +1

texts:
Problem Introduction

  You are given a primitive calculator that can perform the following
  three operations with the current number x: multiply x by 2, multiply
  x by 3, or add 1 to x. Your goal is given a positive integer n, find
  the minimum number of operations needed to obtain the number n
  starting from the number 1.

  Task: Given an integer n, compute the minimum number of operations needed to obtain the number n starting from the number 1.

  Input Format: The input consists of a single integer \$1 <=n <= 10^6.\$

  Output: Print the sequence of intermediate numbers. For example for input \$ n=96234\$, output is 1 3 9 10 11 22 66 198 594 1782 5346
  16038 16039 32078 96234 or 1 3 9 10 11 33 99 297 891 2673 8019 16038
  16039 48117 96234. Both are valid output.

Now I have designed an algorithm and am finding intermediate numbers for each and every number between 1 and n. It is giving me time limit exceeded error. How can I improve its efficiency?

#include <iostream>
#include <climits>
#include <vector>
#include <list>
void primitive_calculator(int64_t number)
{
        std::vector<int64_t> min_steps(number+1,INT_MAX);
        std::list<int64_t>* path=new std::list<int64_t>[number+1];
        min_steps[0]=0; min_steps[1]=0;
        path[0].push_back(0);
        path[1].push_back(1);
        for(int i=2;i<=number;i++)
        {
            if(i%3==0)
            {
                if(min_steps[i/3] < min_steps[i])
                {
                        min_steps[i]=min_steps[i/3]+1;
                        path[i]=path[i/3];
                        path[i].push_back(i);
                }
            }
            if(i%2==0)
            {
                if( min_steps[i/2] < min_steps[i])
                {
                        min_steps[i]=min_steps[i/2]+1;
                        path[i]=path[i/2];
                        path[i].push_back(i);
                }
            }
            if( min_steps[i-1] < min_steps[i])
            {
                min_steps[i]=min_steps[i-1]+1;
                path[i]=path[i-1];
                path[i].push_back(i);
            }
    }
    std::cout<<min_steps[number]<<"\n";
    while(!path[number].empty())
    {
            std::cout<<path[number].front()<<" ";
            path[number].pop_front();
    }
}
int main()
{
    int64_t number;
    std::cin>>number;
    primitive_calculator(number);
    return 0;
}


texts: Listing employees whose employee number is divisible by some given number

texts:
Here I want to improve the code in addListofEmployees and mainMethod. How can I do so?

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class AddEmployees extends Employee {

    public static List<Employee> addListOfEmployees(long upperLimit) {

        List<Employee> list = new LinkedList<>();
        for (long i = 0; i < upperLimit; i++) {
            list.add(new Employee(i));
        }
        return list;
    }

    public static List<Employee> getAllNumbersDividedByProvidedNumber(long upperLimit, int divideBy) {
        return AddEmployees.addListOfEmployees(upperLimit).parallelStream()
                .filter(Employee -> Employee.getNumber() % divideBy == 0).collect(Collectors.toList());

    }

    public static void mainMethod() {
        Scanner sc = null;
        try {
            sc = new Scanner(System.in);
            System.out.println("enter upper limit as lower is zero");
            long upperLimit = sc.nextInt();
            System.out.println("enter the number you want to divide with");
            int divideBy = sc.nextInt();

            for (Employee e : AddEmployees.getAllNumbersDividedByProvidedNumber(upperLimit, divideBy)) {
                System.out.println(e.getNumber());
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        } finally {
            if (sc != null)
                sc.close();
        }

    }

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

Employee Class

package com.lambada.filter_predicatemethod;

public class Employee {

    private long number;

    public Employee() {
    }

    public Employee(long number) {
        this.number = number;
    }

    public long getNumber() {
        return number;
    }

}

Edit

I thinks this can achieving same result but not sure that chaining is a good part

public static List<Employee> getEmployeeDividedBy(long upperLimit, long dividedby) {
        return LongStream.range(0, upperLimit).mapToObj(Employee::new).collect(Collectors.toList()).stream()
                .filter(Employee -> Employee.getNumber() % dividedby == 0).collect(Collectors.toList());
    }


texts:
Here is my source code which group duplicate files together, written in Python 2.7. Any advice on smarter ideas to group duplicate files together more efficient, it will be great. Any general advice on code bugs and code style are also appreciated.

Problem statement:

I am given a list of files e.g. ["1.txt", "2.txt", "3.txt", "4.txt", "5.txt", "6.txt"]. I want to group all files which have the exact same content. Suppose in this example, file "1.txt", "2.txt", "3.txt" are the same, file "4.txt", "5.txt", "6.txt" have common header, but "4.txt", "6.txt" are exactly the same whole content. Then, the output should be two groups "1.txt", "2.txt", "3.txt" and "4.txt", "6.txt".

My major idea:

To avoid reading full content for each file, I generate a hash code for a file header (in my example, I define the file header to be the first two bytes of a file)
If more than 2 (>=2) files have the same header, I will read the full content and see if they are the exact same whole content

from collections import defaultdict
import itertools
def group_duplicate_files(files):
    hash_buf = defaultdict(list)
    for f in files:
        hash_buf[hash_header(f)].append(f)
    result = []
    for file_list in hash_buf.values():
        if len(file_list) < 2:
            continue
        for file_pair in itertools.combinations(file_list,2):
            if compare_full_content(file_pair[0], file_pair[1]):
                n = set()
                n.add(file_pair[0])
                n.add(file_pair[1])
                found = False
                # try to merge with existing set
                for i,r in enumerate(result):
                    if len(r.intersection(n)) > 0:
                        found = True
                        break
                if found:
                    n = n.union(result[i])
                    result.remove(result[i])
                    result.append(n)
                else:
                    result.append(n)
    return result

def hash_header(filename):
    f = open(filename, "r")
    header = f.read(10)
    return hash(header)
def compare_full_content(filename1, filename2):
    file1 = open(filename1, 'r')
    file2 = open(filename2, 'r')
    content1 = file1.read()
    content2 = file2.read()
    i = 0
    j = 0
    while i < len(content1) and j < len(content2):
        if content1[i] != content2[j]:
            return False
        i += 1
        j += 1
    if i < len(content1):
        return False
    if j < len(content2):
        return False
    return True

if __name__ == "__main__":
    files = ["1.txt", "2.txt", "3.txt", "4.txt", "5.txt", "6.txt"]
    print group_duplicate_files(files)


texts: Find maximum value of Point represented by an Array of values for each coordinate

texts:
Suppose there is an array A = {3,2,5}, then points for this array correspond to indexes (i,j) where i <= j = {(0,0), (0,1), (0,2), (1,1), (1,2), (2,2)}. The program returns max(sum) such that sum = A[i] + A[j] + (j - i). For the above array :

point (0,0) will have sum = (3 + 3) + (0 - 0) = 6
point (0,1) will have sum = (3 + 2) + (1 - 0) = 6
point (0,2) will have sum = (3 + 5) + (2 - 0) = 10
point (1,1) will have sum = (2 + 2) + (0 - 0) = 4
point (1,2) will have sum = (2 + 5) + (2 - 1) = 8
point (2,2) will have sum = (5 + 5) + (2 - 2) = 10

Therefore program should return max(sum) = 10
I have solved this problem, but I'm struggling to reduce the complexity of the solution to O(n). Is there a more elegant, efficient way to this?

static int solution(int[] arr) {
    //when array is empty
    if(arr.length == 0) {
        return 0;
    }
    //when array is of length 1
    if(arr.length == 1) {
        return 2*arr[0];
    }
    List<Integer> list1 = new ArrayList<Integer>();
    for(int i=0;i<arr.length;i++) {
        list1.add(arr[i]);
    }
    //copy old list to new one and sort the new one
    List<Integer> list2 = new ArrayList<Integer>(list1);
    Collections.sort(list2);
    //replace values to indexes using 1st list
    for(int i=0;i<list2.size();i++) {
        list2.add(i,list1.indexOf(list2.remove(i)));
    }
    //sort old list. Now my 1st list contains sorted values, and 2nd one       contains corresponding old indexes
    Collections.sort(list1);
    int i = list1.size()-1;
    //set max to point (n-1,n-1)
    int max = 2*list1.get(i);
    while(i > 0) {
        int j = 1;
        while(j < i) {
            int sum = (list1.get(i) + list1.get(i-j)) + (list2.get(i) -list2.get(i-j));
            if(sum > max) {
                max = sum;
            }
            j++;
        }
        i--;
    }
    return max;
}


texts: Parse numbers from text based on relative position to certain substrings

texts:
The input is a product code. I want to pull out the "percentage" portion of that code. For example, if the code contains the substring BIO, I want all the numbers that follow it until I hit another non-numeric character. You can see from the PATINDEXs the other situations - it probably doesn't add much typing them in English.

Here's the tests:

Product          Returns
DS2BIO5          5%
DS2BIO20WB       20%
DS2BIO2RED7      2%
DS2BIO11         11%
E75              75%
E85              85%
NL10ET87         10%
MG15ET89         15%

I don't have performance issues, mainly because my data set is pretty small. I just don't think I'm competent when it comes to string manipulation in T-SQL and I'd like to use best practices. Also, if I had another condition I would have another IF nesting and I'm already at my limit for what I can tolerate.

ALTER FUNCTION dbo.fnExpectedBlend
    (
        @Item VARCHAR(30)
    )
RETURNS NUMERIC(15, 6)
AS
    BEGIN
        DECLARE @Pos INT

        IF PATINDEX('%BIO[0-9]%', @Item) > 0
            BEGIN
                SET @Pos = PATINDEX('%BIO[0-9]%', @Item) + 3
                SET @Item = SUBSTRING(@Item, @Pos, LEN(@Item))
                SET @Pos = PATINDEX('%[^0-9]%', @Item)
                IF @Pos > 1
                    SET @Item = SUBSTRING(@Item, 1, @Pos - 1)

            END
        ELSE
            BEGIN
                IF PATINDEX('E[0-9][0-9]', @Item) > 0
                    SET @Item = SUBSTRING(@Item, 2, LEN(@Item))
                ELSE
                    BEGIN
                        IF PATINDEX('%[0-9]ET[0-9]%', @Item) > 0
                            SET @Item = SUBSTRING(@Item, 3, 2)
                        ELSE
                            SET @Item = '0'
                    END
            END

        RETURN ISNULL(CAST(@Item AS NUMERIC(15,6)) / 100, 0)
    END


texts: Two versions of Word Break II - exhaustive combinations

texts:
I am solving Word Break II from leetcode:

  Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

  Note:

  The same word in the dictionary may be reused multiple times in the segmentation.
  You may assume the dictionary does not contain duplicate words.

  Input:

s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] Output:

[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]

  Explanation: Note that you are allowed to reuse a dictionary word.

I think my Python has improved since I posted island problem last. Your input is appreciated.

Here are the two solutions:

def inverse_iterative(s, wdict):
    st = []
    ans = []

    for w in wdict:
        if s.startswith(w):
            if len(s) == len(w):
                ans.append(w)
                return ans
            st.append((w, 0, [w]))

    while st:
        cur_w, cur_idx, cur_list = st.pop()
        cur_start = cur_idx + len(cur_w)

        for w in wdict:
            if not s[cur_start:].startswith(w):
                continue
            if len(w) == len(s[cur_start:]):
                ans.append(' '.join(cur_list+[w]))
            else:
                st.append((w, cur_start, cur_list+[w]))
    return ans

def inverse_helper(s, wdict, memo):
    if s in memo:
        return memo[s]
    if not s:
        return []

    res = []
    for word in wdict:
        if not s.startswith(word):
            continue
        if len(word) == len(s):
            res.append(word)
        else:
            result_of_rest = helper(s[len(word):], wordDict, memo)
            for r in result_of_rest:
                r = word + ' ' + r
                res.append(r)

    memo[s] = res
    return res

ans_iterative = inverse_iterative(s, wdict)
ans_recursive = inverse_helper(s, wdict, {})


texts:
I'm building a very simple Lisp interpreter. Similar to the the one from here. Here is what I have so far for the parsing part, that is, everything from "text is passed to the the program" to "ast is built". How does the below look? What can be improved? The hardest part for me was the recursive read_from_tokens function.
import re
Symbol = str

def pops(L, d=None):
    "Pop from the left of the list, or return the default."
    return L.pop(0) if L else d

def parse(program):
    "Read a Scheme expression from a string and return tokens in AST."
    program = preprocess(program)
    assert program.count(')') == program.count('('), "Mismatched parens"
    return read_from_tokens(tokenize(program))

def preprocess(s):
    "Replace comments with a single space."
    return re.sub(r';.+', ' ', s)

def tokenize(s):
    "Convert a string into a list of tokens."
    return s.replace('(', ' ( ').replace(')', ' ) ').split()

def atom(token):
    "Return a number (only accepted literal) or a symbol."
    try:
        return int(token) if token.isdigit() else float(token)
    except ValueError:
        return Symbol(token)

def read_from_tokens(tokens):
    "Read one or more expression from a sequence of tokens. Returns a list of lists."
    L = []
    while (token := pops(tokens, ')')) != ')':
        L.append(atom(token) if token!='(' else read_from_tokens(tokens))
    return L

if __name__ == '__main__':
    print (parse("(define (+ 2 2) 10) (* pi (* r r))"))
    print (parse("(define r 10)"))
    print (parse("(* pi (* (+ 1 1) r))"))


texts: Haskell program with basic CLI parsing, file reading, and decoding file contents into specified types

texts:
I recently completed the following exercise, but wanted some feedback on how idiomatic etc. my haskell program is. This is from a course which introduces us to file IO before we cover the theory of monads, so my monad-knowledge is still in its infancy. Any feedback much appreciated.
Here's the task:

In StudentTeacher.hs, observe that we have an old version of our Person type with the Student
and Teacher constructor. Fill in studentTeacherBasic so that it will use arguments to determine
the right type of person. If the arguments contain -s or --student, read two lines, for name and age,
and make a student. If there is -t or --teacher, read two lines for the name and department. If
there are no arguments, print:
Please specify the type of person!
Print the resulting person otherwise.
Fill in studentTeacherAdvanced, which should have the same result as your basic version, but
read its input differently. Take a file name as the first argument. If it ends in .student, read lines from
the file assuming they contain a student's information. If it’s .teacher, assume a teacher. Print the
same failure message in any other case.

Here's my answer:
module StudentTeacher where

import Data.List.Split (splitOn)
import Text.Read (readMaybe)
import System.IO (openFile, withFile, IOMode(..), hGetLine, hGetContents, Handle, stdin)
import System.Environment (getArgs)
import Data.Maybe (isNothing)

data Person =
  Student String Int |
  Teacher String String
  deriving (Show)

type PersonDecoder = String -> Maybe Person
type CLIParser = [String] -> Maybe (PersonDecoder, (IO Handle))

studentTeacher :: CLIParser -> IO ()
studentTeacher cliparser = do
  arguments <- getArgs
  maybePerson <- case (cliparser arguments) of
    Nothing -> return Nothing
    Just (decoder, getHandle) -> do
      handle <- getHandle
      decodePersonFromHandle decoder handle
  case maybePerson of
    Nothing -> putStrLn "Please specify the type of person"
    Just person -> print person

studentTeacherBasic :: IO ()
studentTeacherBasic = studentTeacher parseArgsFlag

decodePersonFromHandle :: PersonDecoder -> Handle -> IO (Maybe Person)
decodePersonFromHandle decoder handle = do
  line1 <- hGetLine handle
  line2 <- hGetLine handle
  return $ decoder $ line1 ++ "\n" ++ line2

parseArgsFlag :: CLIParser
parseArgsFlag [] = Nothing
parseArgsFlag ("-t":_) = Just (decodeTeacher, wrapStdIn)
parseArgsFlag ("-s":_) = Just (decodeStudent, wrapStdIn)
parseArgsFlag ("--teacher":_) = parseArgsFlag ["-t"]
parseArgsFlag ("--student":_) = parseArgsFlag ["-s"]

wrapStdIn :: IO Handle
wrapStdIn = do
  return stdin

decodeTeacher :: PersonDecoder
decodeTeacher encoded =
  case lines of [] -> Nothing
                [_] -> Nothing
                (name:dept:_) -> Just (Teacher name dept)
  where lines = splitOn "\n" encoded

decodeStudent :: PersonDecoder
decodeStudent encoded =
  case lines of [] -> Nothing
                [_] -> Nothing
                (name:age:_) -> decodeStudentLines name age
  where lines = splitOn "\n" encoded

decodeStudentLines :: String -> String -> Maybe Person
decodeStudentLines name age =
  case decodedAge of Nothing -> Nothing
                     (Just ageInt) -> Just (Student name ageInt)
  where decodedAge = readMaybe age :: Maybe Int

studentTeacherAdvanced :: IO ()
studentTeacherAdvanced = studentTeacher parseArgsSuffix

parseArgsSuffix :: CLIParser
parseArgsSuffix [] = Nothing
parseArgsSuffix (fname:_) =
  if hasSuffix fname "student" then Just (decodeStudent, openFile fname ReadMode)
  else if hasSuffix fname "teacher" then Just (decodeTeacher, openFile fname ReadMode)
  else Nothing

hasSuffix :: String -> String -> Bool
hasSuffix filename suffix = if length components == 0 || length components == 1
  then False
  else last components == suffix
  where
    components = splitOn "." filename


texts: Hash Map implementation with a function to set all values

texts:
This is an interview question I saw online and thought to give it a try.
The question is about implementing a hash map with a setAll(V value) function. This function assignes a value to all the keys in the map at O(1).
Examples:

HashMapSetAll<Integer,String> map = new HashMapSetAll<Integer,String>();
map.put(1, "1");
map.put(2, "2");
map.setAll("all");
map.put(3,"3");

System.out.println(map.get(1)); // prints "all"
System.out.println(map.get(2)); // prints "all"
System.out.println(map.get(3)); // prints "3"

I added the implementation below - please tell me what you think about it - I mostly care about correctness and efficiency.

Also, pay attention to the call to Thread.sleep(0,1) - the reason I'm calling it is beacuase isAfter method of ZonedDateTime smallest unit compare is nano-seconds (and I want to make sure that at least one nano-seconds passes between to calls to ZonedDateTime.now()). Please tell me if there is a cleaner way of doing this time compare.

HashMapSetAll.java:

import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;

public class HashMapSetAll<K,V> extends HashMap<K,V> {

    private Map<K,ZonedDateTime> keyDates;
    private ZonedDateTime setAllTime;
    private V setAllVal;

    public HashMapSetAll() {
        super();
        keyDates = new HashMap<K,ZonedDateTime>();
        setAllTime = null;
        setAllVal = null;
    }

    @Override
    public V get(Object key) {
        ZonedDateTime time = this.keyDates.get(key);
        if (time == null)
            return null;

        if ( (this.setAllTime == null) || (time.isAfter(this.setAllTime)) )
            return super.get(key);

        return this.setAllVal;
    }

    @Override
    public V put(K key, V value) {
        V oldVal = super.put(key, value);

        this.keyDates.put(key, ZonedDateTime.now());
        try {
            Thread.sleep(0, 1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return oldVal;
    }

    public void setAll(V value) {
        this.setAllTime = ZonedDateTime.now();
        try {
            Thread.sleep(0, 1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.setAllVal = value;
    }
}

Also added some tests in HashMapSetAllTest.java:

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class HashMapSetAllTest {

    HashMapSetAll<Integer, String> setAllMap = new HashMapSetAll<Integer, String>();

    @BeforeEach
    void setUp() throws Exception {
        setAllMap.clear();
    }

    @Test
    void testPutFirst() {
        String val = setAllMap.put(1, "hi");
        assertNull(val);

    }

    @Test
    void testPutSecond() {
        String val;

        setAllMap.put(1, "hi");
        val = setAllMap.put(1, "hi2");

        assertTrue(val.equals("hi"));
    }

    @Test
    void testGetNormalNull() {
        assertNull(setAllMap.get(1));
    }

    @Test
    void testGetNormalValue() {
        setAllMap.put(1, "hi");
        assertTrue(setAllMap.get(1).equals("hi"));
    }

    @Test
    void testGetValAfterSetAll() { // value assigned after setAll
        setAllMap.setAll("all");
        setAllMap.put(1, "mine");

        assertTrue(setAllMap.get(1).equals("mine"));
    }

    @Test
    void testGetValBeforeSetAll() { // values assigned before setAll
        setAllMap.put(1, "mine");
        setAllMap.setAll("all");

        assertTrue(setAllMap.get(1).equals("all"));
    }

    @Test
    void testGetValBeforeAndAfterSetAll() { // values assigned before setAll
        setAllMap.put(1, "1");
        setAllMap.setAll("all");
        setAllMap.put(2, "2");

        assertTrue(setAllMap.get(1).equals("all"));
        assertTrue(setAllMap.get(2).equals("2"));
    }
}


texts: Simple implementation of a generic stack

texts:
I'm fairly new to C++ programming. To help I've been writing my own data structures for practice. I'd liked this to be judged as if it was written by a professional, and receive honest feedback. I already have a few concerns.

Am I managing memory correctly? I don't believe I have any leaks. A lot of advice I get when using pointers is to use smart pointers, but raw pointers are fine when the class encapsulates all pointers correct?
I'm unhappy my << operator overload has to call to peekAll inside the class. I feel like I'm going about this in the wrong way. Aside from that should I overload any other operators? I didn't feel arithmetic operators made much sense.

#include <ostream>

template <typename T>
class BBStack {
public:
BBStack(T type) {
    head = new Node(type);
}

virtual ~ BBStack() {
    Node* temp = head;
    while (head != nullptr) {
        temp = head->next;
        delete head;
        head = temp;
    }
    delete temp;
}

void push(T type) {
    Node *newNode = new Node(type, head);
    head = newNode;
}

T peek() const {
    return head->data;
}

T pop() {
    if (head == nullptr) {
        std::cout<<"Error stack is empty"<<std::endl;
        return NULL;
    } else {
        Node *temp = head;
        T result = temp->data;
        head = head->next;
        delete temp;
        return result;
    }
}

std::ostream& peekAll(std::ostream& out) const {
    if (head == nullptr) return out << "Stack is empty";
    Node* temp = head;

    while (temp != nullptr) {
        out << temp->data << " ";
        temp = temp->next;
    }

    delete temp;
    return out;
}

private:
    struct Node {
        Node(T type, Node* _next = nullptr) : data(type), next(_next) {}
        Node(Node* node) : data (node->data), next (node->next) {}

        T data;
        Node* next;
    };
    Node* head;

};

template <typename T>
std::ostream& operator<< (std::ostream& out, const BBStack<T>& stack) {
    return stack.peekAll(out);
}


texts: Windows filepath and filename validation

texts:
I have a Windows program that prompts the user to input a file path and filename. I then check that the file exists with Directory.Exists. Then the user inputs a filename and I check it using this answer to check whether the filename is valid or not (it may or may not yet exist).

using System;
using System.IO;
using System.Text.RegularExpressions;

public static string GetFilePath()
{
    string filePath = " ";
    bool directoryFound = true;
    do
    {
        if (!directoryFound)
        {
            Console.WriteLine("This directory not found:\n{0}\nPlease double check file path. \nPlease Double check that this program has read and write access to the directory.\n", filePath);
        }

        Console.WriteLine("Please specify file location:");
        filePath = @Console.ReadLine();
        Console.Clear();

        directoryFound = Directory.Exists(filePath);
        if (filePath.Length >= 240) //This looks like a bad solution
        {
            directoryFound = false;
            Console.WriteLine("Please keep the filepath under 240 chars so that you still are able to provide a name for the file.");
        }

    } while (!directoryFound);

    filePath = GetFileName(filePath);

    return filePath ;
}

    public static string GetFileName(string filePath)
    {
        string fileName = " ";
        bool isValidName = true;
        int fileNameMaxLength = 0;
        do
        {
            if (!isValidName)
            {

                Console.WriteLine("{0} \nis not a valid filename. Make sure you enter a valid filename.\nYour max filename length should be {1}", fileName, fileNameMaxLength);
            }

            Console.WriteLine("Please enter the name of the file:");
            fileName = Console.ReadLine();
            Console.Clear();

            string illegalChars = @"^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\"";|/]+$";

            isValidName = Regex.IsMatch(fileName, illegalChars, RegexOptions.CultureInvariant);

            if (fileName.Length + filePath.Length > 254) //254 instead of 260 in order to account for file extension
            {
                isValidName = false;
                fileNameMaxLength = 254 - filePath.Length;
            }

        } while (!isValidName);
        return Path.Combine(filePath, (fileName + ".ppm"));
    }

}

How could I make this be more elegant? I especially don't like:

if(filePath.Length >= 240)

I need to make sure that:

The filepath exists
The filename is valid
That filename + filepath <= 260 (this is max char limit on Windows)
That my program doesn't crash while doing this